blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
493ba33be7b7918663f45ef2d3ed9f6de6ae1bc2 | Steve-V/tgg-BotSteve | /modules/dice.py | 2,930 | 4.21875 | 4 | #!/usr/bin/env python
"""
dice.py - The Geek Group Phenny Module
Phenny Copyright 2008, Sean B. Palmer, inamidst.com
This module is copyright 2011, Steven Vaught
Licensed under the Eiffel Forum License 2.
http://inamidst.com/phenny/
"""
import random
def rolldice(phenny, input):
import random
#chec... |
c32341617aa175b0beed8dbaea181e22465c8a4c | kavanc/Intro-AI | /tutorial_4_AI/astar.py | 4,303 | 3.671875 | 4 | class Node():
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
class Astar:
def __init__(self, start = Non... |
5d24e29078020a31f97767a5e31b9c5a52de5ed6 | argdundee/DbyD | /structure/vsm/model/__init__.py | 2,350 | 3.59375 | 4 | import numpy as np
class BaseModel(object):
"""
Base class for models which store data in a single matrix.
Parameters
----------
matrix : numpy.ndarray
A two-dimensional numpy array storing the results of model
training. Default is `None`.
context_type : string
A stri... |
a39f20fa324d7d4e89d1972be6554907a4afb61c | NktaW/PyFun | /Loopz.py | 466 | 3.640625 | 4 | #Muuttuja wizards, joka sisältää welhojen määrän.
wizards = 0
#Muuttuja answer sisältää vastauksen welhojen lisäämis kysymykseen.
answer = 'y'
while answer == 'y':
#lisätään welho
wizards = wizards + 1
#Lause näyttää viestin jossa näkyy lisättyjen Welhojen kokonaismäärä
print('Welhojen määrä on ' + st... |
0231169d4d05ea4035c9887d563501032bba16ca | Redtone21/Inheritance | /animal.py | 427 | 3.59375 | 4 | class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return f'My name is {self.name}'
class Dog(Animal):
def __init__(self, name, age):
super().__init__(name, age)
def speak(self):
return'whoof whoof!'
c... |
574445e519aab2904fb15643fc16eea80f48ace0 | hajelav/programs | /backtracking/permutStringsDuplicates.py | 1,597 | 4.03125 | 4 | #!/bin/python
import sys
#https://www.youtube.com/watch?v=uFJhEPrbycQ&list=PLFE6E58F856038C69&index=9
'''
program to find all permutation of a given string( a string can have duplicate
chars)
In permutation/combination type of problems, always take two strings
1. originalString
2.ProcessedSoFar
Try to think recursivel... |
f3102fd971c33ead370e2279bd9851c9820241cf | Katte18/Python_labs | /Lab_work_2-6(tuples).py | 1,174 | 4.28125 | 4 | #Lab. work 2-6 (tuples and sets)
#Generate two sets with not unique numbers and few symbols
a = set('abcde823eemnl3')
b = {'V', '2', 'i', 'l', 'l', 'a', '7', '4', '8'}
#Print 1st set
print('The first set is "a": {}'.format(a))
print('The second set is "b": {}'.format(b))
#Create tuple from intersection of ... |
2cc14ea112359010c5de5cd1bee25266db517a70 | banak13/learn | /palindrom.py | 243 | 3.859375 | 4 | def is_palindrome(palindrom):
palindrom = list(palindrom.replace(" ", "").lower())
return palindrom == list(reversed(palindrom))
print(is_palindrome("Zakopane na pokaz"))
print(is_palindrome("Aa"))
print(is_palindrome("111112")) |
eda66b24def5d3b1c1e6ae1849b52ccc7addb8bd | maestro-102/learning | /tasks_acmp/4.py | 381 | 3.640625 | 4 | """
Решение задачи на ACMP.ru
Орешки
https://acmp.ru/index.asp?main=task&id_task=766
"""
my_list_int = []
number = input()
my_list = number.split()
for i in my_list:
i = int(i)
my_list_int.append(i)
composition = my_list_int[0] * my_list_int[1]
if composition < my_list_int[2]:
print('NO')
elif composit... |
5f646dd867a00551475715f6e13835a6e2101e95 | maestro-102/learning | /base/day_7.2.py | 1,415 | 3.84375 | 4 | # Учительница дала Васе и Пете длинный список чисел.
# Вася и Петя должны найти:
# - сумму всех чисел
# - произведение всех чисел
# - разность всех чисел
# а также составить новый список из имеющегося, каждый элемент которого должен быть возведён в степень 3.
#
# Это уже не впервые, поэтому нужно помочь им составить пр... |
d9ec0c192645f2e2f8e246a59c33cf8ec3639afc | rice2007/Battleship | /Battleship.py | 5,271 | 3.59375 | 4 | __author__ = 'AmateurHero'
from random import randint
class Board(list):
def __init__(self):
super().__init__()
for i in range(10):
self.append(["O"] * 10)
def __repr__(self):
board = ''
for row in self:
board += " ".join(row) + '\n'
return boa... |
47c47d86725aedf4b9e8bdac181c09b362a56c9f | gcbanevicius/barcelona | /parsePowerTrace.py | 2,400 | 3.546875 | 4 | #!/usr/bin/env python
from __future__ import print_function
import sys
import re
def adjustTime(time, startTime):
#time = float(time - startTime)
# time = time / 1000 # ms => sec
# return time
# get rid of decimal to avoid weird float precision issues
time = time * 10
startTime = startTi... |
f0fb2312d8df6b08af195e62b0ee05eb1840ef02 | IlyassElmoutaoukkil/hint2pass | /hint2pass.py | 6,693 | 3.71875 | 4 | hints=[]
words=[]
import os;
def addhint():
give=raw_input('any hint?: ')
if(give==''):
checkDes(False)
else:
print('insert '+give+' ...')
hints.append(give)
checkDes(True)
def checkDes(stat):
if (stat):
print(len(hints))
addhint();
else:
os.system('clear');
addword()
def addword():
give=... |
3889081d142cf6c726e6c9666e22473ecbc36606 | hzmsh/DynamicProgramming | /70_Climb Stairs_DP.py | 932 | 3.5625 | 4 | n = 4
# DP; Time Complexity O(n), Space O(n)
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
# base case
if n == 0:
return(0)
if n == 1:
return(1)
if n == 2:
return(2)
... |
aa118b7f4bf7522c8980171e351c781f4a0f192b | dblprog/math-fun | /letterfreq7.py | 2,029 | 3.703125 | 4 | #!/usr/bin/env python3.3
# vigenere 7 freq -- compute word frequencies from standard input
# SOLUTION SPECIFIC TO 7-char keyword; hard-coded
# generalized version to come
import sys
import re
import operator
freq1 = {}
freq2 = {}
freq3 = {}
freq4 = {}
freq5 = {}
freq6 = {}
freq7 = {}
# process input
for line... |
2561e0b30a9f1b52c8b4686ce20702edc29d30b2 | BranFerr/Rectangle_and_Temp_Converter | /Rectangle.py | 258 | 4.125 | 4 | h = input('What is the Height/Length of the Rectangle?\n')
h = int (h)
w = int (input('What is the Width of the Rectangle?\n'))
x = int (h) * w
x = str (x)
h = str (h)
print ('The area of a rectangle of Height/Length '+h+' and width ',w,' is '+x)
|
9c9269650e45d0534e436164486876d914a1ac47 | edubb0389/simulacion | /antonioreal/laboratorio 3/el que esta bien/Cell-Simulation-master/chemistry.py | 2,534 | 3.5 | 4 | class Chemistry:
""" Container for all potential chemicals and reactions """
def __init__(self):
self.chemicals = []
self.masses = {}
self.charges = {}
self.stabilities = {}
self.reactions = []
def addElements(self, names, masses, charges):
for i, name i... |
af91b22cb3d99f9076c96915ee9be3a17a3efff8 | kcstokely/kctools | /kctools/classes/dicts.py | 1,537 | 4.21875 | 4 | ################################################
class odict(dict):
'''
This is a dictionary, where values can be set
and accessed like class attributes dict.key
One could then override dict with: dict=odict
However, overriding dict doesn't change dicts
... |
66b7703af94ac677eaf19bb1bbf5c385dadbb73f | kninad/sample-join | /code/join.py | 2,233 | 3.765625 | 4 | from Table import make_table
def two_table_simple_join(t1, t2, c1, c2, tbl_name=True):
# define join algorithms, both scan and index
def join_without_index(t1, t2, c1, c2):
for index1, value1 in t1.iterate_column(c1):
row1 = t1.get_row(index1)
for index2, value2 in t2.iterate_c... |
24e7e10a31c0db9fa5cf6ecda2ebdccfb44c4547 | lomantic/genetic-algorithm | /readBestRecord.py | 1,133 | 3.5 | 4 | import os
import os.path
import func
import csv
information = []
breakCount = 0
distance = 0
if os.path.isfile('bestResults.csv'):
print("Reading bestResult.csv...\n")
with open('bestResults.csv', mode='r', newline='') as result:
reader = csv.reader(result)
# i = 0
for info in reader:
... |
14c628c71902dd7e19642ff4e170d7a105dcd9c7 | SWB-Dev/PracticePython.org-Exercises | /Exercise15.py | 580 | 4.09375 | 4 | #Exercise 15 - Reverse Word Order
#PracticePython.org
def reverse_string(string):
splitString = string.split()
print(splitString)
reverse = [splitString[-x] for x in range(1,len(splitString)+1)]
print(reverse)
result = " ".join(reverse)
return print(result)
reverse_string("This is a string")
#afte... |
71e4937074d06d78e69305ff1eff26ba46f1bba6 | SWB-Dev/PracticePython.org-Exercises | /Exercise8.py | 1,555 | 4 | 4 | #Exercise 8 - Rock Paper Scissors
#PracticePython.org
from random import randint
keep_playing = "y"
def get_player_input():
choices = ["rock","paper","scissors","quit"]
if single != None:
return choices[randint(0,3)]
choice = input(f"Choose from {choices[:3]}: ").lower()
while choice not in choices... |
c306dca3c73f2af1a40dd046e6ae7978c782d3c0 | harshit9715/python-scripts | /find_key_in_json_recursive.py | 1,003 | 4.03125 | 4 | def keys_exists(element, *keys):
'''
Check if *keys (nested) exists in `element` (dict).
'''
if not isinstance(element, dict):
raise AttributeError('keys_exists() expects dict as first argument.')
if len(keys) == 0:
raise AttributeError('keys_exists() expects at least two arguments, ... |
9ff5f3b41e411ae3f2a0840473c13e629119c329 | Ram1212/python | /if_elif.py | 306 | 4.125 | 4 | #!/usr/bin/python\
score = raw_input("Enter score")
score = float(score)
if score >= 1.0:
elif score >= 0.9:
Grade = 'A'
elif score >= 0.8:
Grade = 'B'
elif score >= 0.7:
Grade = 'C'
elif score >= 0.6:
Grade = 'D'
elif score < 0.6:
Grade = 'E'
else:
print "invalid score"
print Grade
|
48adeb7c23b534df51f34cd25bf18d3ff616788a | DavLivesey/Algoritm_exam_2 | /Photocopies.py | 606 | 3.71875 | 4 |
def spred_out_copies(data_center_size, count_centres):
count_copies = 0
if len(data_center_size) < 2:
return 0
data_center_size.sort(reverse=True)
while data_center_size[0] and data_center_size[1]:
data_center_size[0] -= 1
data_center_size[1] -= 1
count_copies += 1
... |
5ec52b19f58e95f9cdd9ded03bed5afae493d07b | Emrys-Hong/programming_notes | /python/interview/dynamic_programming.py | 1,853 | 3.890625 | 4 | # dynamic programming
# using recursion function would usually take O(2^n) time but if we use the memo function it will take O(n) time just like the bottom up solution
# A memoized solution
def fib_2(n, memo):
if memo[n] is not None:
return memo[n]
if n == 1 or n == 2:
result = 1
else:
... |
424ff7d923835afdbaeacfcbd0c5cc151cb5a2cd | ryokan0123/placeholder_translation | /models/placeholder/dictionary.py | 345 | 3.625 | 4 | from typing import List
from marisa_trie import Trie
class Dictionary:
def __init__(self, words: List[str]):
self._trie = Trie(words)
def find_entries(self, sentence: str) -> List[str]:
entries = []
for i in range(len(sentence)):
entries += self._trie.prefixes(sentence[i:]... |
535c3067d229ecd530eafff2e33758f3f0214dbb | WilbertRayos/BinarySearch | /main.py | 1,486 | 4.40625 | 4 | def binary_search(value_list: list, value_search: int):
# Get list size
list_size = len(value_list)
# Lowest index in the list [Initial]
index_low = 0
# Highest index in the list [Initial]
index_high = list_size - 1
# Will be used as validator if value exists
value_found = False
# ... |
c9c11d78e8b2a98fd437b5bb4d4b2cffa760fb9d | srungarapugopikrishna/problems | /palindrome.py | 346 | 3.890625 | 4 |
import re
input = raw_input()
regex = re.compile('[^a-zA-Z]')
input = regex.sub('', input).lower()
def is_palindrome(input):
ip1 = list(input)
ip2 = list(input)[::-1]
for i in range(0, len(input)):
if ip1[i] != ip2[i]:
return False
return True
if is_palindrome(input):
print ... |
d25fe386e1e105c2a69877e1e71febbeef201ed2 | juneaume/IUNhydroponics | /temphumsensor_final.py | 4,577 | 3.515625 | 4 | import datetime
import time
import RPi.GPIO as GPIO
import Adafruit_DHT
import os.path
import math
##Expert code brought to you by Brittany Armstrong with assistance from Nicholas Bibeau
## These are the GPIO pins that are being read; they're stored this way so they can all be toggled on/off simultaneously
chan_lis... |
c2d3029ebf515703c1b63434646fa156c39bea56 | geekidharsh/ctci-solutions | /bitmanipulation-example.py | 457 | 4.21875 | 4 | # For instance, the binary representation of 6 is:
# 110
# The least significant bit is the bit on the far right
# of the binary representation and the most significant
# bit is the bit on the far left. We order the bits as
# b2, b1, b0
# 1 1 0
# 0 is not set
# 1 is set
# 1 0 1
# b2 b1 b0
def int_to... |
951a5d44409c1a1955133e15c31a5c139776a926 | adamnovak/tsv | /tsv.py | 3,168 | 4.21875 | 4 | #!/usr/bin/env python2.7
# tsv.py: a module for writing TSV (tab-separated value) files
"""
This module defines two classes: a TsvWriter, which can be constructed on a
stream to allow writing TSV data lines and #-delimited comments to that stream,
and a TsvReader, which can be constructed on a stream and iterated over ... |
54320a48b909b9f94baec2d4ef347f4566e95768 | python-practice-b02-006/Koshchei | /OOP/vectors.py | 1,622 | 3.71875 | 4 | class Vector3D():
def __init__(self, x = 0, y = 0, z = 0):
self.x = x
self.y = y
self.z = z
self.length = (x**2 + y**2 + z**2)**0.5
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector(x, y, z)
... |
3fc60a2bab786de7754e6b985b12dc25df018b67 | ppnielsen/python-learning | /complete/day025.py | 1,172 | 3.96875 | 4 | '''
Day 25 Cup of Code: numpy & jupyter notebook
numpy array is vector/matrix like, optimized for speed
Lists require for loops which are costly!
Kahn Academy classes:
vector and matrix math
linear algebra
gaussian distribution 1d & 2d
'''
import numpy as np
# list
L = [1, 2, 3]
print('List:', L)
# array
A = np.arr... |
4117014d2ac3ab4c6512695547fd96e01a6b7a75 | ppnielsen/python-learning | /complete/day019.py | 803 | 4.125 | 4 | '''
Day 19 Cup of Code
'''
def prompts():
'''
Learning argument vector and prompts. Using input within code
'''
from sys import argv
script, username = argv
prompt = '>>> '
# f before a string means format
# the curly brackets are replacement strings
print(f"Hi {username}, I'm th... |
44cc9d0608296f0d2d60b1829be5f300b9cdf6bc | ppnielsen/python-learning | /complete/day037.py | 819 | 3.96875 | 4 | '''
Day 37
given a string of words, reverse all the words
start = 'this is the best'
finsih = 'best the is this
'''
def reverse(s):
# A:
# s = s.split() # splits it into pieces
# s.reverse() # reverses objects
# return s
# B:
# return "-".join(reversed(s.split())) # join is a separator!
... |
672d634186433dcb9153188a1fbb8ca50bfd3508 | ppnielsen/python-learning | /complete/day033.py | 659 | 4.125 | 4 | '''
Cup of Code Day 33
Interview Questions
What is the missing number?
array 1 is non negative numbers
array 2 is shuffled version of array 1 and one integer is missing
which number is missing?
finder([1,2,3,4,5,6,7], [3,7,2,1,4,6])
Could compare second array to first, might also be duplicate elements in array
T... |
acbfe196085f9d03d341a9959c4d6db082b62d74 | ppnielsen/python-learning | /complete/day017.py | 1,747 | 4.125 | 4 | '''
Day 17 of Cup of Code's Python tutorial
Dragon Project: How to Fend Off a Dragon
'''
def dragon_game():
'''
Select a good or bad dragon! Will you guess right?
'''
import random
import time
# Creating our own functions so we can call the code and not have to keep writing it
def displa... |
ea3633776fc9b41178889d16786c5b2208d3c1a9 | 001unknown/hacktoberfest2021 | /Python/quicktutorials.py | 1,174 | 3.953125 | 4 | # string assignment
data = 'hello world'
print(data[0])
print(len(data))
print(data)
#number assignment
value = 123.1
print(value)
value = 10
print(value)
#boolean assignment
a = True
b = False
print(a, b)
#multiple assignment
d, e, f = 1, 2, 3
print(d, e, f)
#none assignment
g = None
print(g)
#flow control statem... |
a1804d0d2df210511e0063629fe997692ae22a46 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio03/Fabio03_11_intervalo_primo.py | 244 | 3.59375 | 4 | def main():
limite_inf = int(input("Limite inferior: "))
limite_sup = int(input("Limite superior: "))
for i in range(limite_inf, limite_sup+1):
h = 0
for c in range(1,i +1 ):
if i % c == 0:
h += 1
if h == 2:
print(c)
main() |
762f13978d84be62adf5a951d462f8233925e5f4 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio03/Fabio03_07_Soma.py | 192 | 3.859375 | 4 | def main():
n = int(input("digite um valor: "))
soma = 0
for c in range(1, n+1):
soma = soma + c
print("{} + {} = {}".format( soma-c, c,soma))
print("O RESULTADO FINAL É",soma)
main() |
8caeb7c0ea606fc6fb7bb806569992a74cdf8473 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio01/Fabio01_46_PARCELAS.py | 277 | 3.9375 | 4 | # Entrada
valor_mercadoria = int(input(" Digite o valor da mercadoria: "))
# Processamento
divisao = valor_mercadoria // 3
resto = valor_mercadoria % 3
entrada = divisao + resto
# Saída
print(" A entrada é {} e as outras duas parcelas são {}".format(entrada, divisao)) |
728dd55e4f5177eeabb3478481e037c83fae24bb | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio02a/Fabio02a_09_primo.py | 252 | 3.828125 | 4 | def main():
primo = int(input("Digite um numero entre 1 e 100: "))
cont= 1
divisor = 0
while cont <= primo:
if primo % cont == 0:
divisor += 1
cont +=1
if divisor == 0:
print("Numero é primo")
else:
print("Numero nao é primo")
main() |
be35f85f1b6859335374959ff46d1c850c46c17c | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio01/Fabio01_16_AREA-QUADRADO.py | 162 | 3.671875 | 4 | # Entrada
lado= int(input("Digite a medida do lado do quadrado: "))
# Processamento
area= lado**2
# Saída
print("A área do quadrado é {} .".format(area)) |
1452a05b5481da640b3037c72db532fbadfb4132 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio01/Fabio01_17_AREA-RETANGULO.py | 204 | 3.734375 | 4 | # Entrada
base= int(input("Digite o valor da base: "))
altura= int(input("Digite o valor da altura: "))
# Processamento
area = base * altura
# Saída
print("A área do retangulo é {}.".format(area)) |
82af166cd9a3b20bffa300d8781c075b0f897716 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio02a/Fabio02a_01_numeros_iguais.py | 446 | 4.0625 | 4 | def main():
# Entrada
n1 = int(input("Valor 1: "))
n2 = int(input("Valor 2: "))
n3 = int(input("Valor 3: "))
# Processamento e Saída
if n1 == n2 == n3:
print("Existem 3 valores iguais")
elif n1 == n2 or n1 == n3:
print("Existem 2 valores iguais")
elif n2 == n1 or n2 == n3:
print("Existem 2 valores iguai... |
a618919a3cc6cacb32b8de2a005c42bbaba80d61 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio02a/Fabio02a_17_Restos.py | 486 | 3.875 | 4 | def main():
n1= int(input("Digite um valor: "))
n2= int(input("Digite outro valor: "))
if n1 % n2 == 1 :
print(n1 + n2 + (n1 % n2))
elif n1 % n2 == 2:
if n1 % 2 == 0:
print("{} é par".format(n1))
else:
print("{} é impar".format(n1))
if n2 % 2 == 0:
print("{} é par".format(n2))
else:
print... |
e42ad8d20e87e39ee6497b849e6af58223261b2f | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio01/Fabio01_22_KM---M.py | 145 | 3.703125 | 4 | # Entrada
km= float(input("Digite um valor em km: "))
# Processamento
m= km * 1000
# Saída
print(" O equivalente em m é {:.2f}".format(m)) |
3f625e91f677068e83aa8388d30e5ab257b92b87 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio02a/Fabio02a_13_Maior_numero.py | 371 | 3.84375 | 4 | def main():
n1, n2, n3, n4, n5 = input("Digite 5 valores separados por espaço: ").split()
if n1 > n2 and n1 > n3 and n1 > n4 and n1> n5:
print(n1)
elif n2 > n1 and n2 > n3 and n2 > n4 and n2 > n5:
print(n2)
elif n3 > n1 and n3 > n2 and n3 > n4 and n3 > n5:
print(n3)
elif n4 > n1 and n4 > n2 and n4 > n3 and n... |
fd6803d9a99ec8b7e03323ad4c4cfcb26ed68375 | dragod812/ANN | /ann.py | 3,914 | 3.546875 | 4 | #import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, -1].values
#handling categorical features
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
LE_X_1 =... |
9df4644bbdf1750284296f4cdfa6c76bb117ff6e | matthewrmills/mth314S | /bookfiles/_build/jupyter_execute/104-Affine_Transformations_Robotics_in-class-assignment.py | 26,610 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# # 104 In-Class Assignment: Transformations & Robotics
#
# <img src="https://people.gnome.org/~mathieu/libart/art-affines.png">
#
# Image from: https://people.gnome.org/~mathieu/libart/libart-affine-transformation-matrices.html
#
# ### Agenda for today's class
#
# 1.... |
52988f34560940efe5450dd40dee04da2f8fe629 | matthewrmills/mth314S | /bookfiles/_build/jupyter_execute/108-Basis_Orthogonal_InnerProduct_in-class-assignment.py | 17,390 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
#
#
# # 108 In-Class Assignment: Change of Basis, Projections, Inner Products
#
# <img alt="Graph showing how one vector can be projected onto another vector by forming a right triangle" src="https://upload.wikimedia.org/wikipedia/commons/9/98/Projection_and_rejection.png" wi... |
4713f53b0b1d4f2a2b9d615fa281d08c0c34179d | nurur/Python-Programming | /fileIO.py | 917 | 3.8125 | 4 |
# File: Write the list of builtin functions and variables to a file
# writing string to a file 1
outfile = file('tmpWrite.txt', 'w')
outfile.write('This is line #1\n')
outfile.write('This is line #2\n')
outfile.write('This is line #3\n')
outfile.close()
# writing list to a file 1
import __builtin__
a = dir(__buil... |
d4863f8ce763738045c5638ce234188c3a0525bd | nurur/Python-Programming | /break.py | 568 | 4.09375 | 4 | # for_break.py
"""Count lines until a line that begins with a double #.
"""
import sys
def countLines(infilename):
infile = file(infilename, 'r')
count = 0
for line in infile:
line = line.strip()
if line[:2] == '##':
break
count += 1
return count
def usage():
p... |
3367a1653e615ffa725d890cdc0e3063ad6cb92e | SiddhiGolatkar/Data-Structures-and-Algorithms-in-Python | /Recursion_factorial.py | 267 | 4.125 | 4 |
# single line to find factorial
def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n-1)
num = 5
print("Factorial of" ,num, "is", factorial(num))
num = int(input("enter a number: "))
print("Factorial of" ,num, "is", factorial(num))
|
d7891956f6117384e9e811a93cb7dfb3dc555dd5 | devopsgroup4/Group4 | /additionof2num.py | 133 | 4.125 | 4 | #!/usr/bin/python
num = 1.5
num1 = 3.5
sum = float(num) + float(num1)
print('The sum of {0} and {1} is {2}'.format(num, num1, sum))
|
be5842367a58b7169f71e3579ca008690191d487 | Mahantesh856/Python-Set2 | /38.py | 390 | 3.859375 | 4 | dict1={'name':'ramakrishna','age':25}
dict2={'empid':1234,'salary':5000}
print dict1
print dict2
dict1.update(dict2)
print dict1
sal=(0.1)*dict1.get('salary')
s=dict1.get('salary')+sal
dict1.update({'salary':int(s)})
dict1.update({'age':26})
dict1.update({'grade':'B1'})
print dict1
print "keys:",dict1.k... |
f1c337fe50c49158812673e079a6f66e45b19bb3 | MagicianQi/CrackingCoding | /2.Linked Lists/2.8.py | 1,737 | 3.921875 | 4 | """
Question 2.8:
Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the
beginning of the loop.
EXAMPLE:
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C
"""
class Node:
def __init__(self, val, next):
... |
1679fdc5d8689d3fbd6ada59bc7728376467653b | MagicianQi/CrackingCoding | /1.Arrays and Strings/1.9.py | 861 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Question 1.9:
String Rotation : Assume you have a method isSubString which checks if one word is substring of another.
Given two strings, s1 and s2, write code to check if s2 is rotation of s1 using only one
call to isSubstring(e.g.,"waterbottle... |
d390e7e76240de43250a7d4aef4395f8408de377 | MagicianQi/CrackingCoding | /4.Trees and Graphs/4.2.py | 936 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Question 4.2:
Minimal Tree: Given a sorted (increasing order) array with unique integer elements, write an algorithm to create
a binary search tree with minimal height.
"""
class Tree:
def __init__(self, val):
self.val = val
self.left = None
... |
e42d3d336d75a1b7c682613d27ac981c4b9f61ca | MagicianQi/CrackingCoding | /3.Stacks and Queues/3.1.py | 3,161 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Question 3.1:
Three in one: Describe how you could use a single array to implement three stacks.
"""
import numpy as np
import random
class Array2Stack:
def __init__(self, length):
self.array = np.arange(length)
self.length = length
self.stack_1 = [0, 0] ... |
8317da9e10ca872c7a8bff63c41249419d2364b3 | MagicianQi/CrackingCoding | /3.Stacks and Queues/3.2.py | 1,160 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Question 3.2:
Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the
minimum element? Push, pop and min should all operate in O(1) time.
"""
class Stack:
def __init__(self):
"""
Take O(n) spac... |
07282fc4d8d0f3c83112e6a5835b091e3ce14ff9 | agerhall/ALM-data-challenge | /retrieval_tree.py | 2,210 | 3.640625 | 4 | def trie(seq, k_max, alphabet=['A', 'C', 'G', 'T']):
"""
Builds a retrieval tree for a given DNA sequence and a given spectrum.
Returns:
- tree = a list of dictionaries, indexed by the spectrum length
"""
tree = []
# Initialization
tree.append(_init(seq, alphabet))
# Recursions
... |
431751337160275bbe52800693941ce1cac0fad9 | Pratima4/Practice_Python | /Maths.py | 934 | 4.0625 | 4 | #factorial
'''
a=int(input("Enter num:"))
def factorial(n):
num = 1
while n>=1:
num = num*n
n=n-1
return num;
print (factorial(a))
#prime number or not
b=int(input("Enter num:"))
for i in range(2,b):
if (b%i) == 0:
print ("No")
else:
print ("Ye... |
6dc48179453e674c168e713561bf0daa44bd2b36 | BrettMcGregor/practicepythonorg | /33birthday_dictionaries.py | 903 | 4.75 | 5 | """
This exercise is Part 1 of 4 of the birthday data exercise series.
For this exercise, we will keep track of when our friend’s birthdays are, and be able to
find that information based on their name. Create a dictionary (in your file) of names and
birthdays. When you run your program it should ask the user to ente... |
815ba764513035a0b0b2c6a12c9f00007c84d388 | BrettMcGregor/practicepythonorg | /14list_remove_dups.py | 663 | 4.03125 | 4 | """
Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates.
Extras:
Write two different functions to do this - one using a loop and
constructing a list, and another using sets
"""
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l... |
843adb8c4bd176050017f9fb5dc5f2f1d1642fa5 | BrettMcGregor/practicepythonorg | /15reverse_word_order.py | 451 | 4.5 | 4 | """
Write a program (using functions!) that asks the user for a long string
containing multiple words. Print back to the user the same string, except
with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.
"""
... |
ed922ee1c9d27c629e3f62e802e1606f243b9724 | HouQi9475/python | /python入门20_返回函数.py | 1,626 | 4.03125 | 4 | print('==========Ramon学python==========')
#高阶函数除了可以把函数作为参数外,还可以把函数作为返回值。
#实现一个可变参数的求和
def getSum(*args):
gs=0
for n in args:
gs=gs+n
return gs
print(getSum(3,5,7,8))
#但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?
#可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def get_Sum():
gs=0
for n in args:
gs=gs+n
return gs
retur... |
9afab044ab323c3eb11dc46d7e83ec60f9dd5d56 | HouQi9475/python | /python入门06_条件判断.py | 442 | 4.0625 | 4 | print ('========Ramon学Python=======')
#条件判断
weight=input('输入你的体重(KG):')
height=input('输入你的身高(m):')
weight=float(weight)
height=float(height)
bmi=weight/height/height
print('您的BMI为%.1f'%bmi)
if(bmi<18.5):
print('体重过轻..')
elif(18.5<=bmi<25):
print('体重正常..')
elif(25<=bmi<28):
print('体重过重..')
elif(28<=bmi<32):
... |
f9a3fd6986b3cd7d5cf62f97deeb6ff96c8767a9 | TAMMoura/HackerRank | /30 Days of Code/Day 06 - Let's Review/Solution.py | 97 | 3.640625 | 4 | N = int(input())
for i in range(0, N):
string = input()
print(string[::2],string[1::2]) |
826bcddc9c3aae4796672083594bcf66c0b74e72 | Rassilion/Denemeler | /python/hesap.py | 729 | 3.65625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
while True:
print "1 toplama \n 2 çıkarma \n 3 çarpma \n 4 bölme"
i1 = raw_input("işlem numarası")
if i1 == "1":
a = float(raw_input("ilk sayı"))
print a
b = float(raw_input("ikinci sayı"))
print a, "+", b, "=", a + b
if i1 == "2":
a = float(raw_... |
a0fbd3492dd92ad8cfe44cdbfc47b43901a27922 | jonchan51/advent-of-code | /python/day1/day1.py | 462 | 3.5 | 4 | def computeFuel(mass):
return mass // 3 - 2
def totalFuel(mass):
fuel = computeFuel(mass)
if (fuel > 0):
return fuel + totalFuel(fuel)
else:
return 0
def part1(data):
return sum([computeFuel(mass) for mass in data])
def part2(data):
return sum([totalFuel(mass) for mass in data... |
5f6d7305a8f2f9b37644a65102a287edd1513da3 | cpe202fall2019/lab1-willski23 | /lab1_test_cases.py | 1,469 | 3.796875 | 4 | import unittest
from lab1 import *
# A few test cases. Add more!!!
class TestLab1(unittest.TestCase):
def test_max_list_iter(self):
"""add description here"""
self.assertEqual(max_list_iter([35, 41, 6, -1, 5]), 41) # standard test
self.assertEqual(max_list_iter([2]), 2) # 1 value in lis... |
c53ce360b9d9747e85beef4da10fb5aee9cf9e3b | zelanko/MyProjectEulerSolutions | /Project_0038/main.py | 1,187 | 4.25 | 4 | """Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, ... |
773e7ea877e8179e62382ca04408d30eb70c078e | zelanko/MyProjectEulerSolutions | /Project_0005/SmallestMultiple.py | 483 | 3.609375 | 4 | """Smallest multiple
[Problem 5](https://projecteuler.net/problem=5)
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"""
candidate = 2520
found = False
while ... |
f0a081a38513425932db5eb0409bbeff047a3793 | zelanko/MyProjectEulerSolutions | /Project_0033/main.py | 2,006 | 3.53125 | 4 | """Digit cancelling fractions
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to
simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling
the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly... |
b34c4762c3ae95aa6234d8a416fca7ceb48ae903 | ShiqiSong/test1 | /listtest.py | 90 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*--8
list=[0,1,2,3,4,5,6,7]
print(list[1:]) |
def1df41c31c3990ebdca18a363cbe3a8c69d6cc | bgereke/coding_practice | /arrays_and_strings/trapping_rain_water.py | 1,010 | 4.03125 | 4 | # Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
# **map pic not provided**
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being... |
6eebf2cfcc93aa6f77dac7c7286726e3aec668b0 | campham210302/khanhcam-d4e18 | /lesson 2/loop.py | 495 | 4.21875 | 4 | # a = range (10)
# #unpack: *
# print (*a)
# #range(stop): range from 0 to before 'stop'
# print(*range (6))
# #range(start,stop): range from 'start' to before 'stop'
# print(*range(10,20))
# #range(start,stop): range from 'start' to before 'stop'
for i in range(10):
print(i)
for i in range(10,-2,-2):
print... |
235523c133c447e961c89def475c20e2f60f4da9 | campham210302/khanhcam-d4e18 | /lesson 3/new.py | 785 | 3.890625 | 4 | # from turtle import *
# forward(200)
# left(90)
# forward(200)
# left(90)
# forward(200)
# left(90)
# forward(200)
# left(90)
# mainloop()
# from turtle import *
# circle(50)
# mainloop()
# begin_fill(red)
# end_fill(red)
# from turtle import *
# circle(50)
# penup()
# setposition(45, 0)
# pendown()
# circle(50)
# ... |
6fe7e68cb480107ba7db9c6aefedc0f0b32cc9ba | HJeffery/Advent_of_code_2020 | /day2.py | 1,736 | 3.953125 | 4 | """
Task:
Find the number of valid passwords
"""
def file_to_list(filename: str):
data = []
with open(filename, 'r') as infile:
for line in infile:
data.append(line.strip("\n"))
return data
def check_password_validity(passwords: list):
valid_passwords = 0
for password in pass... |
2e90b451b0b55985c1fcacdee4b0feb401f67c4d | atilasos/pythonlearning | /ass94.py | 1,229 | 3.859375 | 4 | """
9.4 Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a ... |
022198282852df737a2b3886b15014a56fea7aeb | ibhelmer/diffie_hellman | /DiffieHellman.py | 1,727 | 3.921875 | 4 | # DiffieHellman.py
# Example of exchange key using Diffie-Hellman
# Ib Helmer Nielsen, UCN october 2020
def main():
# Public know Variables
n = 239069244642311244324580962333607220041 # large shared prime number, use PrimGen.py or https://asecuritysite.com/encryption/random3
... |
e9b50c154ea863c6df15368bc8d050e2795b1a6b | Robin8342/RobinHood | /CodeUpCode/MaxMin.py | 331 | 3.5625 | 4 | #5개의 정수들의 최댓값과 최솟값을 구하는 프로그램
#정수는 한 줄에 하나씩 입력
#단 출력값은 첫째쭐에 최댓값 둘째줄에 최솟값을 출력한다.
ListTotal=[]
n = 5
for i in range(n):
ListTotal.append(int(input()))
ListTotal.sort()
print(ListTotal[4])
print(ListTotal[0])
|
2ba86e086fd2cd41702b0c5c478d872f3b243783 | Robin8342/RobinHood | /CodeUpCode/OddNumberMagixSquare.py | 1,054 | 3.953125 | 4 |
while True:
OddNumber = input()
OddNumber = int(OddNumber)
if (OddNumber % 2)==1:
break
else:
print("Only Use OddNumber.")
MagixSquareArray = []
for i in range(OddNumber):
MagixSquareArray.append([0]*OddNumber)
SquareWidth = 0
SquareLength = int(OddNumber//2)
MagixSquareArray[Sq... |
7eb4c08466362b2ebea3aba809e8a82984157f6c | AidarTaziev/EXAMPLE_PERSONAL_SERVICES | /utils/iter_containers/dict_methods.py | 269 | 3.703125 | 4 | def remove_keys_from_dict(keys_list, dict):
for key in keys_list:
if key in dict: del dict[key]
def replace_keys_from_dict(keys_dict, dict):
for key in dict.keys():
if key in keys_dict.keys():
dict[keys_dict[key]] = dict.pop(key)
|
669251477b945868232334f002ca4a6c10b2a3ec | akshayjain3450/Hackerrank-30-days-of-code-in-python | /day6-lets review.py | 353 | 3.546875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
for i in range(0,n):
a1 = ''
a2 = ''
m = str(input())
# print(len(m))
count = -1
for ele in m:
count+=1
if count%2 == 0:
a1=a1+ele
if count%2 != 0:
a2 = a2+ele... |
2975d73dd2de37135cd9d9b7c07314426e4256a7 | bhoomi-28/hotel-management-console-application | /hotel_management_console_app.py | 2,631 | 3.9375 | 4 | username=input("enter username ") #input username
password=input("enter password ") #input password
if username=="hotel_manager" and password=="ht_mg@123": #checking autherisation
staff={1:"anu",2:"bhagya",3:"dev",4:"raj",5:"simran"}
rooms={10:"available",20:"available",30:"... |
4ac2d5f8948c9426f519014cf9c147550a321a48 | naveenpatilm/library-management | /main.py | 2,529 | 3.5625 | 4 | from book import Book
from member import Member
from exception import ValueNotFound
from member_books import MemberBooks
def save_book():
name = input('Enter book name>>>')
author = input('Enter author name>>>')
book = Book(name, author)
book.save()
def view_book():
id = input('Enter book id>>>')
... |
e05a51bb258e02b746000e798c3850ae5772b8fc | Wrendl/Web | /w8/informatics/2/c.py | 126 | 3.9375 | 4 | x = int(input())
y = int(input())
if y==1 and x!=1:
print("NO")
elif x==1 and y!=1:
print("NO")
else:
print("YES") |
58e62a4f5836af8ebbf6a3bd7afe8ee06b124036 | Wrendl/Web | /w8/codingbat/warmup-1/6.py | 92 | 3.75 | 4 | def makes10(a, b):
if a==10 or b==10 or a+b==10:
return True
else:
return False
|
87d44501d3059c349a008d474d2e1a8acaac9d80 | Wrendl/Web | /w8/codingbat/list-2/4.py | 255 | 3.640625 | 4 | def sum13(nums):
sum = 0
nums.append(0)
if len(nums)==0:
return sum
for i in range(len(nums)-1):
if nums[i-1]==13:
sum-=13
else:
sum+=nums[i]
if nums[len(nums)-2]==13:
sum-=13
if sum==-13:
return 0
return sum
|
1c7c0974fe1ec942bdffe9cffe2be5b82db5fa85 | Wrendl/Web | /w8/codingbat/list-1/12.py | 108 | 3.671875 | 4 | def has23(nums):
if nums[0]==2 or nums[0]==3 or nums[1]==2 or nums[1]==3 :
return True
return False
|
94c9f672f16c37ad828ae48b003e15c83ac45775 | clarkdavid2000/attendanceScript | /attendance.py | 1,511 | 3.703125 | 4 | import csv
import xlrd3
def today(file):
l = []
with open(file,'rt') as f:
cr = csv.reader(f)
for row in cr:
l.append(row)
f.close()
return l
def peoples(file):
peopleList = []
wb = xlrd3.open_workbook(filename=file)
sheet1 = wb.sheet_by_inde... |
91e3003acaa350e6ca60a242c5e72d91937d9353 | nihal-flycatchtech/python_training | /prime_or_not.py | 732 | 3.765625 | 4 | def main(num):
file = open("D:\python\prime_or_not.txt", 'w')
file.write("\nfunction with parameter to perform prime or not")
file.write("\ndefine a flag variable")
flag = False
file.write("\nprime numbers are greater than 1")
if num > 1:
file.write("\ncheck for factors"... |
464b1d1b854d925c1dedbf74e586ed390aadf932 | KlaudiaSchoeps/pdsnd_github | /bikeshare.py | 5,481 | 4.25 | 4 | import time
import pandas as pd
import numpy as np
### the following data was given by the programm
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
### the data was merged and now the data applies
def get_filters():
citie... |
5574c52c1afbe96a98584f079336df8c911bbc0b | bonaventura-p/Week_1 | /final_quiz1.py | 573 | 3.875 | 4 |
#user's name
def name():
username = raw_input("""User's name?\n""")
print username
#limit function
def maximum_limit(n, minn, maxn):
if n < minn: #then you manually define the values for minn and maxn
return minn
elif n > maxn:
return maxn
else:
return n
#greetings
def g... |
b1cd6644cb63175accc51de93b969f7e8b50953a | uileyar/hello_python | /001_multiples-3-and-5.py | 886 | 3.6875 | 4 | #!/usr/bin/env python
# coding:utf-8
from util import *
@spend_time
def multiples_1(max_count):
count = 0
for step in [3, 5]:
for n in range(0, max_count, step):
count += n
for n in range(0, max_count, 3*5):
count -= n
print count
@spend_time
def multiples_1_bad(max_coun... |
c74116498d353ef9f859d9520082265b0e8be6fa | uileyar/hello_python | /003_largest_prime_factor.py | 425 | 3.5 | 4 | #!/usr/bin/env python
# coding:utf-8
import timeit
from util import *
def largest_prime_factor(number=600851475143):
i = 2
while i < number/2:
if number % i == 0:
print('{}'.format(i))
largest_prime_factor(number/i)
return
i += 1
print number
def main... |
3eb601ae8fb59761660961fa9347dc524f4922fc | HuangJingGitHub/PracMakePert_py | /leetcode/leetcode_217.py | 342 | 3.546875 | 4 | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums) < 2:
return False
numsSet = set()
numsSet.add(nums[0])
for i in range(1, len(nums)):
if nums[i] in numsSet:
return True
numsSet.add(nums[i])... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.