blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
5d1232fa95f1d30fb79551128f7dfa84941a07de | SireeshaPandala/Python | /Python_Lesson2_SourceCode/ProgrammingForBigDataCA2CarRental-master/Tuple.py | 193 | 3.9375 | 4 | num_list = []
for i in range(6):
num_list.append(int(input("enter a number")))
n = len(num_list)
print(f'number list is {num_list}')
num_tuple = (num_list[0],num_list[n-1])
print(num_tuple) |
dd39728113b9589f4a69129dcb77071d58d6a08b | SireeshaPandala/Python | /Python_Lesson4/Python_Lesson4/Employee.py | 1,579 | 4 | 4 | class Employee():
employees_count = 0
total_salary = 0
avg_salary = 0
def __init__(self, name, family, salary, department):
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.employees_count += 1
Employee.total_salary = Employee.total_salary + salary
# Function for average salary
def avg_salary(self):
avg_sal = float(Employee.total_salary / Employee.employees_count)
print(f'The avarage salary of total number employees is {avg_sal}')
# total count of employees
def count_employee(self):
print(f'Total number of employees are {Employee.employees_count} ')
# display the details of the employee
def show_details(self):
print(f' name : {self.name} \n family : {self.family} \n salary : {self.salary} \
\n department : {self.department}')
# inherited class from Employee
class Fulltime_emp(Employee):
def _init_(self, nme, fmly, slry, dept):
Employee._init_(self, nme, fmly, slry, dept)
emp1 = Employee("jack","linen",12000,"Web developer")
emp2 = Employee("woxen","lingush",17021,"IOS developer")
emp3 = Employee("nick","martial",1212,"Anroid developer")
emp4 = Employee("sanchez","alexies",12132," Data analyst")
emp5 = Employee("remisty","kingon",145011,"Data scientist")
f_emp = Fulltime_emp("Harika","Harres",12234,"Python_developer")
f_emp.show_details()
emp1.avg_salary()
emp1.count_employee()
emp1.show_details()
emp1.count_employee()
emp1.avg_salary()
Employee.employees_count |
0006e05bf9c4ce0377506756e72398b560e3cc21 | swimbikerun96/Brian-P.-Hogan---Exercises-for-Programmers | /#25 Password Strength Indicator/Password Strength Indicator - Constraints.py | 1,900 | 4.125 | 4 | #Create lists to check the password entered against
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
special_characters = [' ','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\'',']','^','_','`','{','|','}','~']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def passwordValidator(password):
#Create a list to store password characters in
mylist = []
#Check for Weak and Very Weak Passwords
if len(password) < 8:
if password.isnumeric() == True:
return 1
elif password.isalpha() == True:
return 2
else:
return 3
#Check for Strong and Very Strong Passwords
elif len(password) > 8:
for character in password:
if character.isdigit() == True:
mylist.append("Numbers")
elif character.isalpha() == True:
mylist.append("Letters")
elif character in special_characters:
mylist.append("sc")
if "sc" in mylist and "Letters" in mylist and "Numbers" in mylist:
return 5
elif "Letters" in mylist and "Numbers" in mylist:
return 4
else:
return 6
#Dictionary to match up returned values from function to statements for the user
strength_dict = {
1 : "is a very weak password.",
2 : "is a weak password.",
3 : "is complex, yet short. Consider revising.",
4 : "is a strong password.",
5 : "is a very strong password.",
6 : "is long, yet simple. Consider revising."
}
#While Loop to handle user input
while True:
pw = input("Please Enter a Password: ")
verdict = passwordValidator(pw)
output = f'"{pw}" {strength_dict[verdict]}'
print(output)
|
a791ea7d63df1623866c8b996435277f64f19736 | swimbikerun96/Brian-P.-Hogan---Exercises-for-Programmers | /#23 Troubleshooting Car Issues/constraints.py | 2,701 | 3.90625 | 4 | #Silent car question
while True:
sc = input('Is the car silent when you turn the key? ')
if sc.lower() == 'yes' or sc.lower() == 'y':
#Question for coroded battery terminals
while True:
cbt = input('Are the Battery terminals coroded? ')
if cbt.lower() == 'yes' or cbt.lower() == 'y':
print('Clean terminals and try starting again.')
break
elif cbt.lower() == 'no' or cbt.lower() == 'n':
print('Replace cables and try again.')
break
else:
print('Only "Yes" or "No" are acceptable answers.')
continue
elif sc.lower() == 'no' or sc.lower() == 'n':
#Question for clicking noise
while True:
cn = input('Does the car make a clicking noise? ')
if cn.lower() == 'yes' or cn.lower() == 'y':
print('Replace the battery.')
break
elif cn.lower() == 'no' or cn.lower() == 'n':
#Question for engine cranking up
while True:
cu = input('Does the car crank up but fail to start?')
if cu.lower() == 'yes' or cu.lower() == 'y':
print('Check the spark plug connections.')
break
elif cu.lower() == 'no' or cu.lower == 'n':
#Question for engine starting then dying
while True:
stn = input('Does the engine start and then die? ')
if stn.lower() == 'yes' or stn.lower() == 'y':
#Question for Fuel Injection
while True:
fi = input('Does your car have fuel injection? ')
if fi.lower() == 'yes' or fi.lower() == 'y':
print('Get it in for service')
break
elif fi.lower() == 'no' or fi.lower() == 'n':
print('Check to ensure the choke is opening and closing.')
break
else:
print('Only "Yes" or "No" are acceptable answers')
continue
else:
print('Only "Yes" or "No" are acceptale answers.')
continue
else:
print('Only "Yes" or "No" are acceptale answers.')
continue
|
b4d37c55d725ab325947da7bbd6d16d1c48f0fe2 | ajaykrishna-ayyala/competitiveprograming | /Week_2/Day4/StringPermutations.py | 1,491 | 3.765625 | 4 | import unittest
main_set=[]
def get_permutations(string):
# Generate all permutations of the input string
global main_set
main_set=[]
if len(string) == 0: return set([''])
string_list = list(string)
permute(string_list,0,len(string)-1)
# print (main_set)
return set(main_set)
def addtoset(string_list):
string = ''.join(string_list)
# print (string)
main_set.append(string)
def permute(string_list,start,end):
if start == end :
addtoset(string_list)
else:
for i in range (start,end+1):
string_list[start],string_list[i]=string_list[i],string_list[start]
permute(string_list,start+1,end)
string_list[start], string_list[i] = string_list[i], string_list[start]
# Tests
class Test(unittest.TestCase):
def test_empty_string(self):
actual = get_permutations('')
expected = set([''])
self.assertEqual(actual, expected)
def test_one_character_string(self):
actual = get_permutations('a')
expected = set(['a'])
self.assertEqual(actual, expected)
def test_two_character_string(self):
actual = get_permutations('ab')
expected = set(['ab', 'ba'])
self.assertEqual(actual, expected)
def test_three_character_string(self):
actual = get_permutations('abc')
expected = set(['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
|
8084646384853a54dff0e4528d9b5f1d9bf5c033 | ajaykrishna-ayyala/competitiveprograming | /Week_2/Day4/PermutationPal.py | 1,428 | 3.96875 | 4 | import unittest
def has_palindrome_permutation(the_string):
# Check if any permutation of the input is a palindrome
count=0
dict={}
for i in range(0,len(the_string)):
if (dict.__contains__(the_string[i])):
dict[the_string[i]]+=1
else:
dict[the_string[i]]=1
count=0
for key in dict.keys():
count+=dict[key]%2
# print (the_string+'----'+count)
if(count>1):
return False
# print(the_string + '----' + str(count))
return True
# Tests
class Test(unittest.TestCase):
def test_permutation_with_odd_number_of_chars(self):
result = has_palindrome_permutation('aabcbcd')
self.assertTrue(result)
def test_permutation_with_even_number_of_chars(self):
result = has_palindrome_permutation('aabccbdd')
self.assertTrue(result)
def test_no_permutation_with_odd_number_of_chars(self):
result = has_palindrome_permutation('aabcd')
self.assertFalse(result)
def test_no_permutation_with_even_number_of_chars(self):
result = has_palindrome_permutation('aabbcd')
self.assertFalse(result)
def test_empty_string(self):
result = has_palindrome_permutation('')
self.assertTrue(result)
def test_one_character_string(self):
result = has_palindrome_permutation('a')
self.assertTrue(result)
unittest.main(verbosity=2)
|
b1b4cdd9fed0c909e20559a4a4db4a20c7355225 | SPEECHCOG/pc_models_analysis | /python_module/multiple_execution.py | 2,638 | 3.828125 | 4 | """
@date 31.03.2020
It changes the json configuration file according to the language code given, and run the training accordingly:
1: English
2: French
3: Mandarin
4: Lang1 (German)
5: Lang2 (Wolof)
"""
import argparse
import json
import os
import sys
from train import train
def change_configuration_file(lang_code, json_path='config.json'):
"""
It reads json configuration file (config.json) and changes the language according to the language code provided
:param lang_code int stating the language to be used.
:param json_path string path of the json configuration file
:return: it changes the file and run train or predict with the new file
"""
with open(json_path) as f:
configuration = json.load(f)
previous_lang = configuration['training']['language']
if lang_code == 1:
new_lang = 'english'
elif lang_code == 2:
new_lang = 'french'
elif lang_code == 3:
new_lang = 'mandarin'
elif lang_code == 4:
new_lang = 'LANG1'
elif lang_code == 5:
new_lang = 'LANG2'
else:
Exception('Only options: 1-5 (english, french, mandarin, LANG1, LANG2)')
# Update info
configuration['training']['train_in'][0] = configuration['training']['train_in'][0].replace(
previous_lang, new_lang)
configuration['training']['train_out'][0] = configuration['training']['train_out'][0].replace(
previous_lang, new_lang)
configuration['training']['language'] = new_lang
# save json
folder_path, file_name = os.path.split(json_path)
output_file_path = os.path.join(folder_path, new_lang + '_' + file_name)
with open(output_file_path, 'w') as f:
json.dump(configuration, f, indent=2)
return output_file_path
if __name__ == '__main__':
# Call from command line
parser = argparse.ArgumentParser(description='Script for running multiple times train.py script.'
'\nUsage: python multiple_execution.py '
'<language_code>.\nLanguage code:\n\t1: English\n\t2:French\n\t3:'
'Mandarin\n\t4:Lang1(German)\n\t5:Lang2(Wolof)')
parser.add_argument('--lang_code', type=int, default=3)
parser.add_argument('--config', type=str, default='./config.json')
args = parser.parse_args()
new_config_file = change_configuration_file(args.lang_code, json_path=args.config)
# Train model
train(new_config_file)
os.remove(new_config_file)
sys.exit(0) |
f7a6151c458d14dbe7c57cc7b813a805e2e58bb7 | zhuyu1326/python-learn-code | /findMinAndMax.py | 413 | 3.71875 | 4 | #-*- coding:utf-8 -*-
def findMinAndMax(L):
if len(L) == 0:
return (None, None)
if len(L) == 1:
return (L[0], L[0])
if len(L) >=2:
max = L[0]
min = L[0]
for i in L:
if i >= max:
max = i
if i <= min:
min = i
return max, min
L = [1, 2, 3, 4, 5 ,6 , 7, 7, 666]
print(findMinAndMax(L)) |
c8f1f681c6e84edee725b3d30b1459424b0cf169 | zhuyu1326/python-learn-code | /douhao.py | 887 | 3.75 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
假定有下面这样的列表:
spam = ['apples', 'bananas', 'tofu', 'cats']
编写一个函数,它以一个列表值作为参数,返回一个字符串。该字符串包含所
有表项,表项之间以逗号和空格分隔,并在最后一个表项之前插入and。例如,将
前面的spam 列表传递给函数,将返回'apples, bananas, tofu, and cats'。但你的函数应
该能够处理传递给它的任何列表。
'''
def comma(someParameter):
i = 0
tempstr = someParameter[0]
for i in range(len(someParameter)):
if i == 0:
tempstr = tempstr
elif i == len(someParameter) - 1:
tempstr = tempstr + ', and' + someParameter[i]
else:
tempstr = tempstr + ', ' + someParameter[i]
print(tempstr)
a = ['apples', 'bananas', 'tofu', 'cats']
comma(a)
|
d425c560e23116592e8d6a0f1ee07b7b18fa800d | teasakotic/stari_zadaci_cpp | /2 kolokvijum/2 kolokvijum/sing-oop2-2018-master/py-game/04-pygame.py | 678 | 4 | 4 | import pygame
"""
https://nerdparadise.com/programming/pygame/part1
"""
pygame.init()
screen = pygame.display.set_mode((800,600))
done = False
x,y = 30,30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
y -= 3
if pressed[pygame.K_DOWN]:
y += 3
if pressed[pygame.K_LEFT]:
x -= 3
if pressed[pygame.K_RIGHT]:
x += 3
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 128, 255), pygame.Rect(x, y, 60, 60))
pygame.display.flip()
clock.tick(100)
|
8e66906960d53ff604235e94256663315f4d84a1 | Abraham-25/Practica-6-Clases-Abraham-Infante- | /E-3.py | 548 | 4 | 4 | #Crear tres clases ClaseA, ClaseB, ClaseC que ClaseB herede de ClaseA y ClaseC herede de ClaseB.
# Definir un constructor a cada clase que muestre un mensaje.
# Luego definir un objeto de la clase ClaseC.
class ClaseA():
def c1(self):
print("Soy el revolucionario")
class ClaseB(ClaseA):
def c2(self):
print("Sere el hombre mas rico del mundo")
class ClaseC(ClaseB):
def c3(self):
print("Traere las paz al mundo")
llamando=ClaseA()
ClaseA.c1()
llamando3=ClaseB()
ClaseB.c2()
llamando2=ClaseC()
ClaseC.c3() |
041b172ba9e90f63eb5b3843eb68d6f05636a6ca | saksim/python_data_analysis | /high_dimension_data.py | 1,941 | 3.6875 | 4 | #! -*-encoding=utf-8-*-
import pandas as pd
import hypertools as hyp
from hypertools.tools import cluster
data = pd.read_csv('F:\\mushrooms.csv')
#print data.head()
'''
Now let’s plot the high-dimensional data in a low dimensional space by passing it to HyperTools.
To handle text columns, HyperTools will first convert each text column into
a series of binary ‘dummy’ variables before performing the dimensionality reduction.
For example, if the ‘cap size’ column contained ‘big’ and ‘small’ labels,
this single column would be turned into two binary columns:
one for ‘big’ and one for ‘small’, where 1s represents the presence of that feature and 0s represents the absence
(for more on this, see the documentation for the get_dummies function in pandas).
'''
hyp.plot(data,'o') #高维度数据在低纬度空间中的展示图(使用HyperTools)
#由以上所画图可知,相似的特征出现在近邻的群中,并且很明显有几个不一样的特战群。
#即:所有的特征群不一定是完全相等,之后可以根据数据中我们喜欢的特征进行颜色标记。
#hyp.plot(data,'o',group=class_labels.legend=lisk(set(class_labels)))
#以上需要预先分类,才能使用
hyp.plot(data,'o',n_clusters=50)#根据分类数进行染色展示
#为了得到登录的群标签,聚类工具可能会通过hyp.tools.cluster被直接调用,并得到类别结果再传递给plot
#[注意:对于母包和子包,如果导入母包没有用*,则无法识别子包!!!]
cluster_labels = cluster(data,n_clusters=50)
hyp.plot(data,'o',group=cluster_labels)
#[注意:HYPERTOOLS默认使用PCA进行降维,所以如果想用其他的算法进行降维,可以如下]
from sklearn.manifold import TSNE
from hypertools.tools import df2mat
TSNE_model = TSNE(n_components=3)
reduced_data_t = TSNE_model.fit_transform(df2mat(data))
hyp.plot(reduced_data_t,'o') |
212ef10fd0d2d8fb41f5255bae25d30865160fb0 | crsnplusplus/bartez | /bartez/dictionary/trie_node.py | 1,517 | 3.625 | 4 | from abc import ABCMeta, abstractmethod
class BartezNode(object):
__metaclass__ = ABCMeta
"""Trie Node used by BartezTrie class"""
def __init__(self, parent, char):
self.__char = char
self.__parent = parent
def get_char(self):
return self.__char
def get_parent(self):
return self.__parent
@abstractmethod
def accept(self, visitor):
pass
class BartezNodeNonTerminal(BartezNode):
"""Trie Node Non Terminal used by BartezTrie class"""
def __init__(self, parent, char):
BartezNode.__init__(self, parent, char)
self.__children = []
def get_children(self):
return self.__children
def accept(self, visitor):
visitor.visit_non_terminal(self)
def get_child(self, char):
for child in self.__children:
if child.get_char() == char:
return child
return None
def has_terminal(self):
for child in self.__children:
if child.get_char() == '#':
return True
return False
def has_children(self):
return len(self.__children) > 0
def add_child(self, child):
assert(self.get_child(child.get_char()) == None)
self.__children.append(child)
class BartezNodeTerminal(BartezNode):
"""Trie Node Terminal used by BartezTrie class"""
def __init__(self, parent):
BartezNode.__init__(self, parent, '#')
def accept(self, visitor):
visitor.visit_terminal(self)
|
8ea3a28909ff8435e0e67cfe362334aba91d46f0 | Maheen92-Iqbal/MIT-Python-Programming-Course | /RadiationExposure.py | 534 | 3.609375 | 4 |
import math
def f(x):#we get the height through this curve function by entering the time duration
return 10*math.e**(math.log(0.5)/5.27 * x)
def RadiationExposure(start,stop,step):
count = 0
while start < stop:
area = step * f(start)
count = count + area #through approximation we count the number of area rectangles under the curve and find the total radiation that is exposed
start = start + step
print count
|
8fd4efd7d4758cd68458154f0bd8ae70269eeb1c | chrisyan82000/leetcode | /1650.py | 736 | 3.5 | 4 | def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
if not root:
return root
queue = [root]
while queue:
new_queue = []
for node in queue:
if node.left:
new_queue.append(node.left)
if node.right:
new_queue.append(node.right)
if not new_queue:
return self.lca(root, queue)
queue = new_queue
def lca(self, root, nodes):
if root is None or root in set(nodes):
return root
left = self.lca(root.left, nodes)
right = self.lca(root.right, nodes)
return root if left and right else left or right
|
7cb0fe658d8359c299ca1cca662c19c015d7441a | pvaliani/codeclan_karaoke | /tests/song_test.py | 714 | 4.21875 | 4 | import unittest
from classes.song import Song
class TestSong(unittest.TestCase):
def setUp(self):
self.song = Song("Beautiful Day", "U2")
# - This test determines that a song exists by comparing the object self.song with attribute "name" to the value of "Beautiful Day by U2"
# - self.song.name reads as self.song -> the song object from classes.song and .name is the attribute of the song as defined in the Song class
# - Check that the song has a title
def test_song_has_name(self):
self.assertEqual(self.song.name, "Beautiful Day")
# - Check that the song has an artist
def test_song_has_artist(self):
self.assertEqual(self.song.artist, "U2")
|
f2ceb39db53d1560502f883b236e7d927f9984d3 | muthuubalakan/handwritten-digit-recognizer-cnn | /neuralmodels/model.py | 870 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import os
# Data set in csv file
DATA_SET_CSV = "assets/datasets/train.csv"
if not os.is_file(DATA_SET_CSV):
print("The file is missing...")
# Read data from csv file.
data = pd.read_csv("assets/datasets/train.csv").as_matrix()
classifier = DecisionTreeClassifier()
xtrain = data[0:21000, 1:]
train_label = data[0:21000, 0]
classfier.fit(xtrain, train_label)
# testing
xtest = data[21000:, 1:]
actual_label = data[21000:, 0]
def main(number):
digit = xtest[number]
digit.shape = (28, 28)
# visualize the digit
plt.imshow(255-digit, cmap='gray')
make_prediction = classifier.predict( xtest[number] )
return make_prediction
if __name__ == __main__:
number = int(input("Enter a number: "))
main(number)
|
9e8ac169d32d0342a8d25a562fdffa0e5e233b86 | 4ilo/Advent-Of-Code-2019 | /day4/day4.py | 1,629 | 3.59375 | 4 | #!/usr/bin/python3
import re
RANGE = (357253, 892942)
def validate(password, part2=False):
pass_str = str(password)
# 2 adjacent letters are the same
matches = re.findall(r"(.)\1", pass_str)
if not matches:
return 0
elif part2:
ok = False
for match in matches:
if pass_str.count(match) == 2:
ok = True
if not ok:
return 0
# Digits should never decrease from left to right
for i, c in enumerate(pass_str):
if i < 5 and int(c) > int(pass_str[i + 1]):
return 0
return 1
if __name__ == "__main__":
# Part 1 examples
should_pass = [122345, 111111]
should_fail = [223450, 123789]
for passw in should_pass:
if not validate(passw):
print("[{}] Should have passed.".format(passw))
for passw in should_fail:
if validate(passw):
print("[{}] Should have failed.".format(passw))
# Part 2 examples
should_pass = [112233, 111122]
should_fail = [123444]
for passw in should_pass:
if not validate(passw, part2=True):
print("[{}] Should have passed.".format(passw))
for passw in should_fail:
if validate(passw, part2=True):
print("[{}] Should have failed.".format(passw))
# Soluton part 1
counter = 0
for i in range(RANGE[0], RANGE[1]):
counter += validate(i)
print("Result 1: {}".format(counter))
# Soluton part 2
counter = 0
for i in range(RANGE[0], RANGE[1]):
counter += validate(i, part2=True)
print("Result 2: {}".format(counter))
|
01f8194929ec365020a6559d22fc609065472a62 | 4ilo/Advent-Of-Code-2019 | /day14/day14.py | 1,022 | 3.609375 | 4 | #!/usr/bin/python3
from collections import defaultdict
FILE = "example.txt"
rest = defaultdict(lambda: 0)
def find_needed(reqs, end, amount=1):
if end == 'ORE':
return amount
req = reqs[end]
print(req)
needed = 0
for dep in req["dep"]:
needed += find_needed(reqs, dep[1], int(dep[0]))
print(needed)
rest[dep[1]] = int(req["amount"]) - int(dep[0])
print(rest)
return needed
if __name__ == "__main__":
with open(FILE) as file:
data = file.read().splitlines()
#print(data)
reactions = []
for line in data:
pre, post = line.split(" => ")
post = tuple(post.split(" "))
pre = [tuple(x.split(" ")) for x in pre.split(", ")]
reactions.append([pre, post])
reqs = {}
for line in reactions:
reqs.update({
line[-1][1]: {
"amount": line[-1][0],
"dep": line[0]
}
})
test = find_needed(reqs, "FUEL")
print(test)
|
c09ff6194e83e302dec63ee602841151f4cb2aef | Twoody/CtCI_v6_Python | /randoms/expressString.py | 1,236 | 3.734375 | 4 | '''
Tanner 20180919
Write a function to add two simple mathematical expressions
which are of the form:
Ax^a + Bx^b + ...
That is, the expression is a sequence of terms, where each
term is simply a contant times an exponent.
Do not do string parsing, and use w/e data structure desired.
Thoughts:
I am unsure of what a mathematical expression is, and
what we are suppose to be passing as variables and adding...
What is being asked here???
'''
global x
x = 10
class Expression:
def __init__(self, const, exp): #constant, expression
self.const = const
self.exp = exp
def getsum(self):
return self.const * x**self.exp
def printExpr(self):
s = "\t(" + str(self.const) + ')'
s += "(" + str(x) + "^" + str(self.exp) + ')'
print(s)
def addExpressions(exprArray):
ret = 0
for expr in exprArray:
ret += expr.getsum()
return ret
def printExpressions(exprArray):
for expr in exprArray:
expr.printExpr()
def main():
#Book says to answer this with classes...
expr1 = Expression(1,1)
expr2 = Expression(2,2)
expr3 = Expression(3,3)
exprArray = [expr1, expr2, expr3]
total = addExpressions(exprArray)
printExpressions(exprArray)
print( '\t' + str(total))
if __name__ == "__main__":
main()
|
9675fabd0c4e3c7a443cee4304c49457961f3eb3 | Twoody/CtCI_v6_Python | /2_linkedLists/questions/q3.py | 514 | 4.03125 | 4 | '''
3. Delete Middle Node
Implement an algorithm to delete a node in the middle of a
singly linked list, given only access to that node.
The middle is any node but the first and last node, not
necessarily the exact middle.
Example:
I: the node c from the linked list:
a -> b -> c -> d -> e -> f
O: Nothing is retured. The new linked list looks like:
a -> b -> d -> e -> f
not allowed?
'''
def q1():
print('PASSED ALL TESTS')
return True
if __name__ == "__main__":
q1()
|
9f939317f636304f2ca575332bce620f17b1f16d | Twoody/CtCI_v6_Python | /500Questions_intPrep/knightstour_V4.py | 4,189 | 3.6875 | 4 | '''
'''
def sortByLowestNeighbor(akms):
''' Need to visit corners and borders first '''
''' Will INSERTION SORT by a custom `weight` of moves available neighbors '''
''' '''
for cur in akms:
moves = akms[cur]
nmoves = []
for move in moves:
weight = len(akms[move])
if weight == 8 or nmoves == []:
nmoves.append(move)
else:
lNmoves = len(nmoves)
for j in range(0, lNmoves):
nmove = nmoves[j]
nweight = len(akms[nmove])
if weight <= nweight:
nmoves.insert(j, move)
break
elif j == lNmoves-1:
nmoves.append(move)
akms[cur] = nmoves
return akms
def isLegalKM(b, x, y):
if x < 0 or y < 0 :
return False
elif y >= len(b):
return False
elif x >= len(b[y]):
return False
elif b[y][x] == '':
return False
return True
def getAKMs(b):
akms = {}
for y in range(0, len(b)):
for x in range(0, len(b[y])):
xs1 = [x+1, x-1]
ys1 = [y+2, y-2]
xs2 = [x+2, x-2]
ys2 = [y+1, y-1]
akms[b[y][x]] = []
for i in range(0, len(xs1)):
for j in range(0, len(ys1)):
if isLegalKM(b, xs1[i], ys1[j]) == True:
akms[b[y][x]].append(b[ys1[j]][xs1[i]])
for i in range(0, len(xs2)):
for j in range(0, len(ys2)):
if isLegalKM(b, xs2[i], ys2[j]) == True:
if b[ys2[j]][xs2[i]] not in akms[ b[y][x] ]:
akms[b[y][x]].append(b[ys2[j]][xs2[i]])
akms = sortByLowestNeighbor(akms)
return akms
def getLongestKnightsTour(b, startx, starty):
start = b[starty][startx]
akm = getAKMs(b) #Get available knight moves
s = [] #Stack
l = [] #longest walk
v = {} #Visited
ws = {} #Walks
ls = 0 #Size of longest walk
cursize = 0 #Keep track of size
bs = len(b) * len(b[0]) #Board size
s.append(start)
cursize += 1
while s != []:
curnode = s[cursize-1]
needspopped = True #Needs popped if no new moves added;
v[curnode] = True
for move in akm[curnode]:
if move in v and v[move] == True:
continue
s.append(move)
if str(s) in ws:
s.pop(-1)
continue
needspopped = False
cursize += 1
ws[str(s)] = True
break #Found legal move; Only can make one move out of sequence
if cursize == bs:
return (s, cursize)
if cursize > ls:
l = s.copy()
ls = cursize
if needspopped == True:
v[curnode] = False
s.pop(-1)
cursize -= 1
return (l, ls)
def merge(tour):
if len(tour) <=1:
return tour
midpoint = len(tour)//2
lTour = tour[:midpoint]
rTour = tour[midpoint:]
return mergesort(merge(lTour), merge(rTour))
def mergesort(lTour, rTour):
''' quick merge sort implementation to show we visited all nodes '''
if len(lTour) == 0:
return rTour
elif len(rTour) == 0:
return lTour
iLeft = 0
iRight = 0
merged = []
targetLen = len(lTour) + len(rTour)
while len(merged) < targetLen:
if lTour[iLeft] <= rTour[iRight]:
merged.append(lTour[iLeft])
iLeft += 1
else:
merged.append(rTour[iRight])
iRight += 1
if iRight == len(rTour):
merged += lTour[iLeft:]
break
elif iLeft == len(lTour):
merged += rTour[iRight:]
break
return merged
if __name__ == "__main__":
b = [
[1, 2, 3, 4, 5, 6, 7, 8],
[9,10,11,12,13,14,15,16],
[17,18,19,20,21,22,23,24],
[25,26,27,28,29,30,31,32],
[33,34,35,36,37,38,39,40],
[41,42,43,44,45,46,47,48],
[49,50,51,52,53,54,55,56],
[57,58,59,60,61,62,63,64]
]
#akms = getAKMs(b)
#for spot in akms:
# print('\t' + str(spot) + ':\t' + str(akms[spot]))
knightstour = getLongestKnightsTour(b, 0, 0)
proposedSeq = knightstour[1]
tour = knightstour[0]
print(proposedSeq)
print(tour)
print(merge(tour))
print()
knightstour = getLongestKnightsTour(b, 0, 3)
proposedSeq = knightstour[1]
tour = knightstour[0]
print(proposedSeq)
print(tour)
print(merge(tour))
print()
''' TEST WITH PHONE PAD '''
''' TODO: '''
b = [
[1,2,3],
[4,5,6],
[7,8,9],
['',0,'']
]
knightstour = getLongestKnightsTour(b, 0, 0)
proposedSeq = knightstour[1]
tour = knightstour[0]
print(proposedSeq)
print(tour)
print(merge(tour))
print()
|
5b431d4f88cee8a15a82025664253ddfc4c563c8 | Twoody/CtCI_v6_Python | /20181113_prep/heaps.py | 4,268 | 3.984375 | 4 | '''
Tanner Woody
20181112
Purpose:
heapify.py is meant to show that a heap is a complete binary tree.
heapify.py is meant to teach what a heap is, and lead to a heap sort.
Core Principals on Heaps:
1. Heap must be Complete Binary Tree (CBT)
2. Heap weight must be greater than weight of any child
'''
class Node:
def __init__(self, value, parent=None, right=None, left=None):
self.value = value
self.parent = parent
self.right = right
self.left = left
def __str__(self):
return str(self.value)
def details(self):
ret = str(self.value) +':\n'
ret += '\tparent:\t' + str(self.parent) +'\n'
ret += '\tleft:\t' + str(self.left) +'\n'
ret += '\tright:\t' + str(self.right) +'\n'
return ret
class Heap:
def __init__(self, values=None):
self.head = None
self.tail = None
self.size = 0
if values is not None:
self.add(values)
def __str__(self):
l = self.toArr()
seq = self.getSequence()
i = 0
ret = ''
for n in l:
if i in seq and i != 0:
#New level, print newline
ret += '\n'
ret += str(n) + ' '
i += 1
return ret
def getSequence(self):
cur = 0
i = 0
a = []
while cur <= self.size:
a.append(cur)
cur += pow(2,i)
i += 1
return a
def toArr(self):
#BFS to convert heap to array
a = []
c = self.head
s = [c] #stack to visit
while s != []:
c = s.pop(0)
a.append(c.value)
if c.left:
s.append(c.left)
if c.right:
s.append(c.right)
return a
def add(self, value):
#O(shiftTail) + O(heapify) + O(c) --> O(3 * binLog(n))
if isinstance(value, list):
for v in value:
self.add(v)
return self.tail
self.size += 1
if self.head is None:
self.head = Node(value)
self.tail = self.head
return self.tail
t = self.tail
n = Node(value, self.tail)
if t.left is None:
#Keep the tail the same
t.left = n
elif t.right is not None:
raise TypeError('ERROR: HEAP IS NOT A COMPLETE BINARY TREE AND NEEDS BALANCED: ')
else:
#Will need to shift tail
t.right = n
t = self.shiftTail()
#Lastly, we need to see if we need to heapify the array...
#This is only necessary in heapsort, and could be omitted if building a heap from scratch...
suc = self.heapify(n)
return self.tail
def heapify(self, n):
#O( binLog(n) )
#Traverse up `n` heapifying along the way
cur = n.parent
while cur is not None:
if n.value > cur.value:
#swap nodes and do not lose track of n.value
self.swap(n, cur)
n = cur
cur = cur.parent
return n
def swap(self, n1, n2):
#Swap node1 and node2
t = n1.value
n1.value = n2.value
n2.value = t
return True
def shiftTail(self):
#O(2 * binLog(n))
ns = self.size+1 #(n)ext (s)size
c = self.head #cur node
r = [] #Route to traverse from head
didFirst = False #Flag for skipping bottom layer
while ns > 1:
if ns%2 == 0:
ns = ns/2
if didFirst == True:
r.insert(0, 'l')
else:
didFirst = True
else:
ns = (ns-1)/2
if didFirst == True:
r.insert(0, 'r')
else:
didFirst = True
for d in r:
if d == 'r':
c = c.right
elif d == 'l':
c = c.left
else:
raise OSError('NEVER SHOULD HAPPEN')
self.tail = c
return self.tail
if __name__ == "__main__":
h = Heap([33])
assert h.size == 1
assert str(h) == '33 '
h = Heap([33, 22])
assert h.size == 2
assert str(h) == '33 \n22 '
h = Heap([33, 22,11])
assert h.size == 3
assert str(h) == '33 \n22 11 '
h = Heap([33, 22,11,10])
assert h.size == 4
assert str(h) == '33 \n22 11 \n10 '
h = Heap([33, 22,11,10,9,8,7,6,5,4])
assert h.size == 10
assert str(h) == '33 \n22 11 \n10 9 8 7 \n6 5 4 '
h = Heap([33, 22,11,10,9,8,7,6,5,4,3,2])
assert h.size == 12
assert str(h) == '33 \n22 11 \n10 9 8 7 \n6 5 4 3 2 '
h = Heap([33, 22,11,10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3])
assert h.size == 17
assert str(h) == '33 \n22 11 \n10 9 8 7 \n6 5 4 3 2 1 0 -1 \n-2 -3 '
h = Heap([1])
h = Heap([1,2])
assert str(h) == '2 \n1 '
h.add(4)
assert str(h) == '4 \n1 2 '
h = Heap([1,2,3,4,])
assert str(h) == '4 \n3 2 \n1 '
h = Heap([1,2,3,4,5,6,7,8])
assert str(h) == '8 \n7 6 \n4 3 2 5 \n1 '
h.add(88)
assert str(h) == '88 \n8 6 \n7 3 2 5 \n1 4 '
assert h.toArr() == [88,8,6,7,3,2,5,1,4]
|
6014df3a20629be8e80096cc780a81e8cb6b490d | Twoody/CtCI_v6_Python | /500Questions_intPrep/mergesort_twounsortedarrays.py | 1,130 | 4.09375 | 4 | def mergeTwo(arr1, arr2, args=None):
returntuple = False
if args is None:
args = {}
if 'returntuple' in args and args['returntuple'] == True:
returntuple = True
''' Assuming arr1 and arr2 are sorted at this point '''
if arr1 is None:
if arr2 is None:
return []
return arr2
if arr2 is None:
return arr1
n = len(arr1)
m = len(arr2)
for i in range(0, n):
if arr1[i] > arr2[0]:
#Swap current arr1 node and head of arr2
tmp = arr1[i]
arr1[i] = arr2[0]
arr2[0] = tmp
for j in range(0, m-1):
#Allocate the new head within arr2
if arr2[j] > arr2[j+1]:
tmp = arr2[j]
arr2[j] = arr2[j+1]
arr2[j+1] = tmp
else:
break
if returntuple == True:
return (arr1, arr2)
return arr1 + arr2
def mergesort(arr):
if len(arr) <= 1:
return arr
midpoint = len(arr) // 2
lArr = arr[:midpoint]
rArr = arr[midpoint:]
return mergeTwo(mergesort(lArr), mergesort(rArr))
if __name__ == "__main__":
a = [33,22,12,55, 2, 3,11, 1]
c = [44,23,55,66,12, 1, 2, 3,4,5]
b = mergesort(a)
d = mergesort(c)
ret = mergeTwo(b,d, {'returntuple':True})
print(ret[0])
print(ret[1])
|
3acd49be1964d9f9c794f97ab9cc1269471a1b44 | Twoody/CtCI_v6_Python | /2_linkedLists/questions/q1.py | 266 | 3.546875 | 4 | '''
1. Remove Dups
Write code to remove duplicates from an unsorted linked list.
Follow up:
How would you solve the probem if a temporary buffer is
not allowed?
'''
def q1():
print('PASSED ALL TESTS')
return True
if __name__ == "__main__":
q1()
|
43dc2d778d68dedf09430d0e6a8fb65b633ca9eb | Twoody/CtCI_v6_Python | /randoms/inttest.py | 1,568 | 3.765625 | 4 | '''
for n>0 and n<1000, solve all instances of:
a^3 + b^3 = c^3 + d^3
a**3 + b**3 = c**3 + d**3
Brute force would look like for i, for j, for k, for l... which would
run as 1000**4 iterations about.
NOT OPTIMAL
A better solution is to make a set of all of the cubed numbers first.
'''
def getcubes(n=0):
mList = []
for i in range(0,n):
iCubed = i**3
mList.append(iCubed)
return mList
def equation(a,b,c,d):
if (a+b-c-d == 0):
return True
else:
return False
def brute1(intSetMax=0, intSetMin=0):
cubes = getcubes(intSetMax)
successes = []
for i in range(intSetMin, len(cubes)):
a = cubes[i]
for j in range(i+1, len(cubes)):
b = cubes[j]
for k in range(j+1, len(cubes)):
c = cubes[k]
for l in range(k+1, len(cubes)):
d = cubes[l]
if(equation(a,b,c,d) == True):
successes.append([a,b,c,d])
return successes
def getCDList():
'''mdic key is based off of sum of mdic value pairs'''
mdic = {}
for i in range(1,1000):
c = i**3
for j in range(1,1000):
d = j**3
mdic[str(c+d)] = (c,d)
return mdic
def brute2(resDic):
# d = a**3 + b**3 - c**3
successes = []
for i in range(1, 1000):
a = i**3
for j in range(1, 1000):
b = j**3
if (resDic[str(a+b)]):
CDpair = resDic[str(a+b)]
c = CDpair[0]
d = CDpair[1]
successes.append([a,b,c,d])
return successes
def main():
intSetMax = 100
#cubes = getcubes(intSetMax)
#x = brute1(intSetMax)
#for j in x:
# print(j)
mdic = getCDList()
mList = brute2(mdic)
for arr in mList:
print(arr)
if __name__ == "__main__":
main()
|
4dab177838a46c84b505b84805375fe8826848a2 | datorre5/CIS2348-FALL2020 | /3.18.py | 808 | 3.828125 | 4 | # Daniel Torres
# PSID: 1447167
# Zybooks 3.18
wall_height = int(input('Enter wall height (feet):\n'))
wall_width = int(input('Enter wall width (feet):\n'))
wall_area = wall_height * wall_width
print('Wall area:',wall_area,'square feet')
gallons = wall_area / 350
cans = round(gallons)
print('Paint needed:','{:.2f}'.format(gallons),'gallons')
print('Cans needed:',cans,'can(s)\n')
print('Choose a color to paint the wall:')
color = str(input())
if color == 'red':
red_paint = cans * 35
print('Cost of purchasing red paint:','${}'.format(red_paint))
elif color == 'blue':
blue_paint = cans * 25
print('Cost of purchasing blue paint:','${}'.format(blue_paint))
elif color == 'green':
green_paint = cans * 23
print('Cost of purchasing green paint:','${}'.format( green_paint))
|
a41b9059446e0700fda503cd0647712d6c95a55d | datorre5/CIS2348-FALL2020 | /12.7.py | 677 | 4.0625 | 4 | #Daniel Torres
#PSID: 1447167
# Take age input form user
def get_age():
age = int(input()) # take age input
if 18 <= age <= 78:
return age
else:
# raise a exception
raise ValueError("Invalid age.")
# Calculate fat burning heart rate
def fat_burning_heart_rate():
age = get_age()
# calculate & print
maximum_heart_rate = 220-age
heart_rate = maximum_heart_rate * 0.7
print('Fat burning heart rate for a', age, 'year-old:',heart_rate,'bpm')
# Main
if __name__ == '__main__':
try:
fat_burning_heart_rate()
except ValueError as vs:
print(vs)
print('Could not calculate heart rate info.\n')
|
f25ecf69bcb1c5f168f74fd923d72b9a53248763 | MomSchool2020/show-me-your-cool-stuff-LisaManisa | /Lesson3.py | 583 | 4.15625 | 4 | print("Hello World!")
# if you have a line of text that you want to remove,
#"comment it out" by adding in a hashtag.
# print("Hello World!")
# text in Python is always in quotation marks
print("Lisa")
print("Hello World. Lisa is cool")
print("Lisa said, 'I love you'")
print('Lisa said, "I love you"')
# if you put anything in single quotes, it won't run.
print (print("Hello World!"))
print("Hello World!")
print("I'm the smartest in the class!!")
# use backslash for ignoring the next thing in the code.
print('print("That\'s Mine!")')
# \n means new line
print("Hello\nWorld")
|
aa3df860a775d8f74eaf59c7e54fde713a4698f0 | sankeerthmamidala/python | /draw_S.py | 281 | 3.65625 | 4 | from turtle import *
pen1 = Pen()
pen2 = Pen()
pen1.screen.bgcolor('#3ec732')
pen1.goto(0,300)
pen1.goto(150,150)
pen1.goto(300,300)
pen1.goto(300,0)
pen.up()
pen.goto(350,0)
pen.down()
for i in range(0,250):
pen2.backward(3)
pen2.right(1)
pen1.fd(3)
pen1.right(1)
|
040c8f1d7abaee1063000a4811771828addb8f0f | sankeerthmamidala/python | /first.py | 65 | 3.65625 | 4 | a = int(input(print('enter the nummber',' ')))
a= a+1;
print(a);
|
ab9b610a947309886e99d0678eba60e11b426a76 | mihabin/wmctf-register | /src/region.py | 495 | 3.546875 | 4 | from country_list.country_list import countries_for_language
region_code = [i[0] for i in countries_for_language('zh_CN')]
def list_region(lang: str = 'en_US'):
try:
return countries_for_language(lang)
except:
return countries_for_language('en_US')
def get_region_name(region_code = 'CN', lang: str = 'en_US'):
return ','.join(i[1] for i in countries_for_language(lang) if i[0] == region_code)
def is_valid_region_code(code: str):
return code in region_code
|
821f16b00b90c79867dfbfbf7f93d92d9ce3a23b | agray998/qa-python-assessment-example | /exampleAssessment/Code/example.py | 503 | 4.5625 | 5 | # <QUESTION 1>
# Given a string, return the boolean True if it ends in "py", and False if not. Ignore Case.
# <EXAMPLES>
# endsDev("ilovepy") → True
# endsDev("welovepy") → True
# endsDev("welovepyforreal") → False
# endsDev("pyiscool") → False
# <HINT>
# What was the name of the function we have seen which changes the case of a string? Use your CLI to access the Python documentation and get help(str).
def endsPy(input):
strng = input.lower()
return strng.endswith('py', -2)
|
344b74138c8d12653ae2c8c5403248e1009fe8aa | luxmeter/sudokusolver | /sudokusolver/model/iterators.py | 1,004 | 3.75 | 4 | """Provides iterators to iterate through
the nodes of the rows and columns of the ConstraintMatrix."""
class ColumnIterator(object):
"""Iterates through a sequence of vertically connected nodes."""
def __init__(self, start, reversed=False):
self._current = start
self._reversed = reversed
def __iter__(self):
next_node = 'top' if self._reversed else 'bottom'
while self._current:
current, self._current = \
self._current, vars(self._current)[next_node]
yield current
class RowIterator(object):
"""Iterates through a sequence of horizontally connected nodes."""
def __init__(self, start, reversed=False):
self._current = start
self._reversed = reversed
def __iter__(self):
next_node = 'left' if self._reversed else 'right'
while self._current:
current, self._current = \
self._current, vars(self._current)[next_node]
yield current
|
6ee37c9ee3b0227b623f669fe828473d75ec716d | ramnathpatro/Python-Programs | /Algorithm_Programs/monthlyPayment.py | 581 | 3.765625 | 4 | import re
from Algorithm_Programs.utility import algorithm
ref = algorithm
def monthly_payment():
P1 = input("Enter the principal loan")
Y1 = input("Enter the Year")
R1 = input("Enter the interest")
cheack_P = re.search(r"^[\d]+$", P1)
cheack_Y = re.search(r"^[\d]{1}$", Y1)
cheack_R = re.search(r"^[\d]{2}|[\d]{1}$", R1)
if cheack_P and cheack_R and cheack_Y:
P = int(P1)
Y = int(Y1)
R = int(R1)
print(ref.payment(P, Y, R))
else:
print("Wrong input")
if __name__ == '__main__':
monthly_payment()
|
8fae5343cbecfcf4f25e57a9a4b5ebbdedebc67c | ramnathpatro/Python-Programs | /Functional_Programs/Coupon_Numbers.py | 506 | 3.703125 | 4 | import random
import re
inp = input("How much coupon you want")
generated_cop = []
coupon = 0
x = re.search(r"^[\d]+$", inp)
rang = 1000
if x:
inp = int(inp)
if inp <= rang:
while coupon < inp:
coupon_gen = random.randrange(rang)
if coupon_gen not in generated_cop:
generated_cop.append(coupon_gen)
coupon += 1
print(generated_cop)
else:
print("Enter valid Number only")
else:
print("Enter Number only")
|
ca24b56a383926f19ef37888caa487424ecd81a5 | ramnathpatro/Python-Programs | /Functional_Programs/Flip_Coin.py | 473 | 3.9375 | 4 | import re
import random
inp = input("how many time you flip the coin")
heads = 0
tails = 0
flip_coin = 0
check = re.search(r"^[\d]+$", inp)
#print(check.group())
if check:
inp = int(inp)
while flip_coin < inp:
flip_coin += 1
coin_tos = random.randrange(2)
if coin_tos == 0:
heads += 1
print("Head is", heads / inp * 100, "%")
print("Tails", 100 - heads / inp * 100, "%")
else:
print("Enter the Number only")
|
6e8a31960b340922a3feed81385e27d501f12244 | dillanmann/AdventOfCode2019 | /py/day4_bonus.py | 878 | 3.625 | 4 | # run with `cat <input_file> | py day4_bonus.py`
import sys
def never_decreases(digits):
last = digits[0]
for digit in digits:
if digit < last:
return False
last = digit
return True
def valid_doubles(digits):
has_double = False
for i in range(1, len(digits)):
if digits[i] == digits[i-1]:
if digits.count(digits[i]) > 2:
continue
else:
has_double = True
return has_double
if __name__ == "__main__":
matches = []
input = "271973-785961"
print(input)
lower_bound, upper_bound = tuple([int(s) for s in input.split('-')])
for num in range(lower_bound, upper_bound + 1):
digits = [int(d) for d in str(num)]
if never_decreases(digits) and valid_doubles(digits):
matches.append(num)
print(len(matches)) |
0d5dac3a095a6aaa2025d2d3f463b568a90fe276 | IgorCrepo/AiSD | /kopiec.py | 1,851 | 3.8125 | 4 |
class Heap(object):
def __init__(self):
self.heap = [0]
self.currentSize = 0
def __str__(self):
heap = self.heap[1:]
return ' '.join(str(i) for i in heap)
def Up(self, index):
while (index // 2) > 0:
if self.heap[index] < self.heap[index // 2]:
temp = self.heap[index // 2]
self.heap[index // 2] = self.heap[index]
self.heap[index] = temp
index = index // 2
def insert(self, key):
self.heap.append(key)
self.currentSize += 1
self.Up(self.currentSize)
def Down(self, index):
while(index * 2) <= self.currentSize:
minimumChild = self.minChild(index)
if self.heap[index] > self.heap[minimumChild]:
temp = self.heap[index]
self.heap[index] = self.heap[minimumChild]
self.heap[minimumChild] = temp
index = minimumChild
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heap[i * 2] < self.heap[i * 2 + 1]:
return i * 2
else:
return i * 2 + 1
def delete(self):
deletedNode = self.heap[1]
self.heap[1] = self.heap[self.currentSize]
self.currentSize -= 1
self.heap.pop()
self.Down(1)
return deletedNode
def build(self, tab):
i = len(tab) // 2
self.currentSize = len(tab)
self.heap = [0] + tab[:]
while (i > 0):
self.Down(i)
i = i - 1
bh = Heap()
bh.build([11,5,8,0,3,5])
print('Del:', bh.delete())
print('Del:', bh.delete())
print('Del:', bh.delete())
bh.insert(3)
print('Del:', bh.delete())
print(bh)
|
57c2fe53bdc866ad125d4076372da7cb33b677b9 | 0uterHeaven/FoodProject | /What to eat.py | 453 | 3.875 | 4 |
import random
hungry = input('What do you want to eat: Thai, Italian, Chinese, Japanese, Continental, Mexican, Junk, homemade or random? ')
ethnicity = ['Thai', 'Italian', 'Chinese', 'Japanese', 'Continental', 'Mexican', 'Junk', 'Homemade']
if hungry == 'random':
print(random.choice(ethnicity))
#ethnicity = ['Thai', 'Italian', 'Chinese', 'Japanese', 'Continental', 'Mexican', 'Junk', 'Homemade']
#print(random.choice(ethnicity)) |
99e4b05aed5a6ddf6bc9cd994edbb043ac530915 | Chukak/python-algorithms | /sorting/insertion.py | 373 | 4.09375 | 4 | """ Insertion sort """
array = [234, 345, 4, 32, 45455, 56, 76, 345, 46, 8678676, 567, 43, 2, 5, 8, 105, 4, 17]
def insertion_sort(array):
for i in range(len(array)):
x = i
for j in range(i + 1, len(array)):
if array[x] > array[j]:
x = j
array[x], array[i] = array[i], array[x]
insertion_sort(array)
print(array) |
13d0a7f9f92d01d9075eda1875e3e4eeb84a729f | Chukak/python-algorithms | /sorting/quicksort.py | 773 | 4.09375 | 4 | """ Quicksort sorting """
import random
array = [234, 345, 4, 32, 45455, 56, 76, 345, 46, 8678676, 567, 43, 2, 5, 8, 105, 4, 17]
def quicksort(array):
if not array:
return []
element = random.choice(array)
less = list(filter(lambda x: x < element, array))
equally = list(filter(lambda x: x == element, array))
more = list(filter(lambda x: x > element, array))
return quicksort(less) + equally + quicksort(more)
def quicksort_2(array):
if array:
element = random.choice(array)
return quicksort_2([x for x in array if x < element]) + \
[x for x in array if x == element] + quicksort_2([x for x in array if x > element])
else:
return []
print(quicksort(array))
#print(quicksort_2(array))
|
231b812ebd89cf804f350a03e3ca5d0b11023cb8 | TonaGonzalez/CSE111 | /02TA_Discount.py | 1,162 | 4.15625 | 4 | # Import the datatime module so that
# it can be used in this program.
from datetime import datetime
# Call the now() method to get the current date and
# time as a datetime object from the computer's clock.
current = datetime.now()
# Call the isoweekday() method to get the day
# of the week from the current datetime object.
weekday = current.isoweekday()
subtotal = float(input("Please enter the subtotal: "))
tax = subtotal * .06
total = subtotal + tax
if weekday == 2 or weekday == 3:
if subtotal >= 50:
discount = subtotal * .10
discount2 =subtotal - discount
tax2 = discount2 * .06
total2 = discount2 + tax2
print(f"Discount amount is {discount:.2f}")
print(f"Tax amount is {tax2:.2f}")
print(f"Total is {total2:.2f}")
else:
difference = 50 - total
print(f"Tax amount is {tax:.2f}")
print(f"Total is {total:.2f}")
print("TODAY'S PROMOTION!")
print(f"If you buy ${difference:.2f} more, you'll get a 10% discount in your subtotal")
else:
print(f"Tax amount is {tax:.2f}")
print(f"Total is {total:.2f}")
|
a3991ade1335bc3b3004d40131a6f075937e88d2 | dhockaday/melodically | /melodically/rhythm.py | 2,720 | 4 | 4 | def get_durations(bpm):
"""
Function that generate a dictionary containing
the duration in seconds of various rhythmic figures.
:param bpm: beat per minutes
:return: rhythmic dictionary
"""
beat_time = 60 / bpm
return {
'1': beat_time * 4,
'2': beat_time * 2,
'4': beat_time * 1,
'4dot': beat_time * 3 / 2,
'4t': beat_time * 2 / 3,
'8': beat_time * 1 / 2,
'8t': beat_time * 1 / 3,
'16': beat_time * 1 / 4,
'16t': beat_time * 1 / 6,
}
def get_nearest_rhythm(interval, rhythmical_durations):
"""
Given a certain interval in seconds, gets the rhythmical duration
that has the lower distance with it.
:param interval: duration in seconds
:param rhythmical_durations: dictionary returned by the get_durations
:return:
"""
# the keys and the values obtained from the methods "values" and "keys"
# of a dictionary are correctly ordered, so we can calculate
# the distances from the keys, get the index of the argmin
# and use it to get the correct key
# values of the rhythmical_durations dictionary
rhythmical_durations_values = list(rhythmical_durations.values())
# keys of the rhythmical_durations dictionary
rhythmical_durations_keys = list(rhythmical_durations.keys())
# list comprehension used to map the distance function to the values
distances = [abs(interval - x) for x in rhythmical_durations_values]
# argmin of the distance (an index)
result_index = distances.index(min(distances))
# using the index to get the correct rhythmical duration key
return rhythmical_durations_keys[result_index]
normalized_durations = get_durations(60)
# TODO: check README if correct
def sequence_fits_measures(rhythmic_sequence, measures):
"""
Checks if a rhythmic sequence fits inside a certain number of 4/4 measures.
:param rhythmic_sequence: list of rhythmical symbols
:param measures: number of measures
:return: True if the sequence fits the measures
"""
rhythmic_sequence_values = [normalized_durations[key.replace('r', '')] for key in rhythmic_sequence]
return sum(rhythmic_sequence_values) <= 4 * measures
def clip_rhythmic_sequence(rhythmic_sequence, measures):
"""
Returns a new list of rhythmical symbols
that fits in a certain number of measures
:param rhythmic_sequence: list of rhythmical symbols
:param measures: number of measures
:return: new list of rhythmical symbols that fits int the number of measures
"""
result = rhythmic_sequence.copy()
while not sequence_fits_measures(result, measures):
del result[-1]
return result
|
292da9f51f3a824f1dd98f55d406eda2571dcc04 | mosheb3/WorldOfGames | /SevenBoom.py | 367 | 3.828125 | 4 | ## Moshe Barazani
## Date: 04-02-2020
def play_seven_boom():
num = input("Enter Number: ")
while not num.isdigit():
num = input("Enter Number: ")
for x in range(int(num)):
x+=1
if not (x % 7):
print("BOOM!")
else:
if "7" in str(x):
print("BOOM!")
else:
print(x) |
db35406d0a741624cba50bdfafd0734cde28f68c | Tom-Oosterbaan/C21-Think-Code-level-1 | /Eindopdracht/Eindopdracht.py | 228 | 3.8125 | 4 | guess = input("why was 6 afraid of 7? ")
if guess == "because 7 ate 9":
print("funny, right?")
else:
print("Nope, That's not it!")
print("Thanks for playing!")
def smiley():
print(":)")
smiley()
smiley()
smiley() |
26d11ca3eb7dbf0e0c295fcb0521a76278cf8d03 | Pablo-D-P-C/ficha_empleados | /datos.py | 694 | 3.875 | 4 | print("Completa el formulario para añadir un nuevo usuario")
while True:
nombre = input("Nombre: ").upper()
edad = input("Edad: ")
localidad = input("Localidad: ").upper()
provincia = input("Provincia: ").upper()
salario = input("Salario: ")
dni = input("DNI: ").upper()
print("Deceas añadir otro usuario: Si ó No?")
add = input().lower()
datos = "{}, {}, {}, {}, {}, {}""\n".format(nombre, edad, localidad, provincia, salario, dni)
with open("empleados.csv", "a") as empleados_file:
empleados_file.write(str(datos))
if add == "si":
continue
else:
print("Saliendo ..........")
break
|
656224c5e11814b8d58d01949dc467aa9c63e6e1 | nyhyang/Lab-14 | /app/models.py | 1,312 | 3.515625 | 4 | import sqlite3 as sql
def insert_user(nickname, email):
with sql.connect("app.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO user (nickname, email) values (?, ?)",
(nickname, email))
con.commit()
def insert_trip(user_id, destination, name_of_trip, trip_date, duration, budget, friend):
with sql.connect("app.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO trip (destination, name_of_trip, trip_date, duration, budget, friend) values (?, ?, ?, ?, ?, ?)",
(destination, name_of_trip, trip_date, duration, budget, friend))
trip_id = cur.lastrowid
cur.execute("INSERT INTO user_trip (user_id, trip_id) values (?, ?)",
(user_id, trip_id))
con.commit()
def retrieve_trip(user_id):
with sql.connect("app.db") as con:
con.row_factory = sql.Row
cur = con.cursor()
result = cur.execute("select t.* from trip t, user_trip ut where t.trip_id= tu.trip_id and tu.user_id= ?", (user_id)).fetchall()
return result
def delete_trip(trip_id):
with sql.connect("app.db") as con:
con.row_factory = sql.Row
cur = con.cursor()
cur.execute("delete from trip where trip_id=?", (trip_id))
|
9707ab2fe38a9cf9a45659c488c323731d589cf0 | gabrieldsumabat/DocSimilarity | /tests/TestSimilarity.py | 1,176 | 3.515625 | 4 | import unittest
from code.Similarity import find_euclidean_distance, get_doc_distance_list, sort_sublist_by_element_desc
class TestSimilarity(unittest.TestCase):
def test_find_euclidean_distance(self):
dummy_dict1 = {
"a": 1,
"b": 2,
"c": 3
}
dummy_dict2 = {
"a": 1,
"c": 2,
"d": 3
}
distance = find_euclidean_distance(dummy_dict1, dummy_dict2)
self.assertEqual(distance, 3.7416573867739413)
def test_get_doc_distance_list(self):
dummy_dict = {
0: {
"a": 1,
"b": 2,
"c": 3
}, 1: {
"a": 1,
"c": 2,
"d": 3
}
}
dummy_list = get_doc_distance_list(dummy_dict)
self.assertEqual(dummy_list, [[0, 1, 3.7416573867739413]])
def test_sort_sublist_by_distance(self):
dummy_list = [[0, 1, 3.7416573867739413], [0, 2, 5.7416573867739413], [0, 1, 4.7416573867739413]]
sorted_list = sort_sublist_by_element_desc(1, dummy_list)
self.assertEqual(sorted_list[0][1], 2)
|
6553c371c8c1cc2e6671ad3c357e35dfb15e1b23 | bsvonkin/Year9DesignCS4-PythonBS | /GuiDemo04.py | 374 | 3.5 | 4 | import tkinter as tk
root = tk.Tk()
lab = tk.Label(root, text = "Enter a number:")
lab.grid(row = 0, column = 0)
ent = tk.Entry(root)
ent.grid(row = 1, column = 0)
btn = tk.button(root, text = "Press Me")
btn.grid(row = 2, column = 0)
output = tk.Text(root)
output.configure(state = "disable")
output.grid(row = 0, column = 1, rowspan = 1)
root.mainloop() |
7956465a4c4703780cd7fbcecf28f230f042d271 | bsvonkin/Year9DesignCS4-PythonBS | /TakingInputInt.py | 166 | 3.9375 | 4 | #Input
#Assignment Statement
r = input("What is the radius")
r = int(r)
h = int(input("What is the height"))
#Process
sa = 2*3.14*r*r + 2*r*h*3.14
#Output
print(sa)
|
ec25ab4e6785ea9456a4c00c7945f40e5f111181 | Yuanty378/shiyan01 | /test1.py | 348 | 3.890625 | 4 | #message = "hello word!";
#print(message)
"""
a = int(input("请输入: "))
b = int(input("请输入: "))
print("input获取的内容: ",a+b)
"""
"""
练习:通过代码获取两段内容,并且计算他们长度的和。
"""
a = input("请输入: ")
b = input("请输入: ")
c = len(a)
d = len(b)
print("两段字符串的长度和是: ",c+d)
|
dd39e4444900ca40c744ec7860f916145be46d66 | Hyperboloider/lab9 | /lab9f.py | 614 | 3.796875 | 4 | def matches(string, symbols):
match = []
for word in string:
for symbol_f in symbols:
if word[0] == symbol_f:
for symbol_l in symbols:
if word[-1] == symbol_l:
match.append(word)
return match
def inp(msg = ''):
temp =''
lst = []
string = input(msg)
for letter in string:
if letter != ' ':
temp += letter
else:
lst.append(temp)
temp = ''
lst.append(temp)
return lst
def output(lst):
print('result: ')
for item in lst:
print(item) |
8b64b9e9b17445193dbd8e9973620fc2d95a570c | reget17/Python_Lessons | /lesson_003/00_bubbles.py | 1,001 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import simple_draw as sd
sd.resolution = (1200, 600)
# Нарисовать пузырек - три вложенных окружностей с шагом 5 пикселей
# Написать функцию рисования пузырька, принммающую 2 (или более) параметра: точка рисовании и шаг
def bubble(point, step):
radius = 50
for _ in range(3):
radius += step
sd.circle(point, radius, width=1)
# test
# Нарисовать 10 пузырьков в ряд
# Нарисовать три ряда по 10 пузырьков
# for y in range(100, 301, 100):
# for x in range(100, 1001, 100):
# point = sd.get_point(x, y)
# bubble(point, 5)
# Нарисовать 100 пузырьков в произвольных местах экрана случайными цветами
for _ in range(100):
point = sd.random_point()
bubble(point, 10)
sd.pause()
|
29efd589cc6dcf5299f9e67d7f8149d871294d6f | reget17/Python_Lessons | /lesson_003/08_smile.py | 1,595 | 3.625 | 4 | # -*- coding: utf-8 -*-
# (определение функций)
from random import random
import simple_draw
import random
import math
import numpy as np
# Написать функцию отрисовки смайлика в произвольной точке экрана
# Форма рожицы-смайлика на ваше усмотрение
# Параметры функции: кордината X, координата Y, цвет.
# Вывести 10 смайликов в произвольных точках экрана.
# 123
def smile(point_x, point_y, color):
ellipse_point_left = simple_draw.get_point(point_x - 70, point_y - 50)
ellipse_point_right = simple_draw.get_point(point_x + 70, point_y + 50)
simple_draw.ellipse(ellipse_point_left, ellipse_point_right, color, width=1)
circle_point_left = simple_draw.get_point(point_x - 30, point_y + 10)
circle_point_right = simple_draw.get_point(point_x + 30, point_y + 10)
simple_draw.circle(circle_point_left, 5, width=1)
simple_draw.circle(circle_point_right, 5, width=1)
# улыбка
smile_radius = 30
smile_coordinates = []
for i in np.arange(3.9, 5.5, 0.1):
smile_x = round(smile_radius * math.cos(i))
smile_y = round(smile_radius * math.sin(i))
smile_coordinates.append(simple_draw.get_point(point_x + smile_x, point_y + smile_y))
simple_draw.lines(smile_coordinates, color, width=1)
for _ in range(10):
x = random.randint(50, 550)
y = random.randint(50, 550)
smile(x, y, simple_draw.COLOR_YELLOW)
simple_draw.pause()
|
c3881ca019e5cbd81b9a1cacccd0249fdbb942b3 | mrajibrm/PYTHON | /random22.py | 5,625 | 4 | 4 | import random
import matplotlib.pyplot as plt
import math
import numpy as np
import matplotlib.patches as mpatches
# Problem 1.4
# In Exercise 1.4, we use an artificial data set to study the perceptron
# learning algorithm. This problem leads you to explore the algorithm further
# with data sets of different sizes and dimensions.
def generate_dataset(n):
# split the points randomly to either the +1 class or the -1 class
pos1 = n - random.randrange(1, n)
neg1 = n - pos1
# randomly generate slope and y-intercept for line
m = round(random.uniform(-1,1), 1)
b = round(random.uniform(-5,5), 1)
# set min and max x and y values for the points
min_val = -20
max_val = 20
# generate x values above and below f(x)
x1 = [random.randrange(min_val, max_val) for i in range(pos1)]
x2 = [random.randrange(min_val, max_val) for i in range(neg1)]
# generate y values above and below f(x)
y1 = [random.randrange(math.floor(m*x+b)+min_val, math.floor(m*x+b)) for \
x in x1]
y2 = [random.randrange(math.ceil(m*x+b), max_val+math.floor(m*x+b)) for x \
in x2]
return min_val, max_val, m, b, x1, x2, y1, y2, pos1, neg1
def plot_fx(min_val, max_val, m, b):
""" Plots the f(x) line and axes labels.
"""
# plot f(x) line
plt.plot(np.arange(min_val, max_val), m*np.arange(min_val, max_val) + \
b, color='green')
# axes labels
plt.xlabel('X axis')
plt.ylabel('Y axis')
def plot_points(x1, x2, y1, y2):
""" Plots the generated points, sorted into the +1 and -1 classes.
"""
plt.scatter(x1, y1, c='red') # +1 points
plt.scatter(x2, y2, c='blue') # -1 points
def combine_data(pos1, neg1, x1, x2, y1, y2):
""" Combines the dummy point (x[0]), x and y values, and group value into
an array.
"""
d = [] # create empty set to put datapoint values
for i in range(0, pos1):
d.append([1, x1[i], y1[i], 1]) # append all +1 datapoints
for j in range(0, neg1):
d.append([1, x2[j], y2[j], -1]) # append all -1 datapoints
return d;
def perceptron_calc(w, x):
""" Calculates the cross product of the x-values and the corresponding
weights.
"""
return w[0]*x[0] + w[1]*x[1] + w[2]*x[2]
def sign(x):
""" Gives sign of value
"""
return 1 if x>=0 else -1
def update_rule(w, d):
""" Updates the weights according to the perceptron linear algorithm.
"""
w[0] += d[0] * d[3] # update dummy weight
w[1] += d[1] * d[3] # update x value weight
w[2] += d[2] * d[3] # update y value weight
return [w[0], w[1], w[2]]
def plot_gx(weights, min_val, max_val):
m_g = -weights[1]/weights[2] # calculate g(x) slope
b_g = -weights[0]/weights[2] # calculate g(x) y-intercept
# plot h(x)
plt.plot(np.arange(min_val, max_val), m_g*np.arange(min_val, max_val) + \
b_g, color='yellow')
def perceptron_learning_algorithm(pos1, neg1, x1, x2, y1, y2, n, min_val, \
max_val, m, b):
dataset = combine_data(pos1, neg1, x1, x2, y1, y2)
# set starting weight values and iteration count
weights = [0.0, 0.0, 0.0]
count = 0
# classified is false until all points have been accurately classified
classified = False
while not classified:
count += 1 # increment count every iteration
data_count = 0 # increment count every datapoint
random.shuffle(dataset) # shuffle to access different points
for datapoint in dataset:
# check if sign of calculated classification is equal to actual
if(sign(perceptron_calc(weights, datapoint)) != datapoint[3]):
# if not, update weights
weights = update_rule(weights, datapoint)
else:
data_count += 1 # correct sign adds to total correct count
if(data_count == n):
classified = True # once all points are classified, set to True
# plot points, f(x), and g(x), and add legend
plot_fx(minimum_val, maximum_val, slope, y_intercept)
plot_points(x1, x2, y1, y2)
plot_gx(weights, minimum_val, maximum_val)
fx = mpatches.Patch(color='green', label='f(x)')
gx = mpatches.Patch(color='yellow', label='g(x)')
plt.legend(handles=[fx, gx])
plt.show()
return count
# a
minimum_val, maximum_val, slope, y_intercept, x1, x2, y1, y2, \
num_positive_points, num_negative_points = \
generate_dataset(20)
plot_fx(minimum_val, maximum_val, slope, y_intercept)
plot_points(x1, x2, y1, y2)
plt.show()
# b
count = perceptron_learning_algorithm(num_positive_points, \
num_negative_points, x1, x2, y1, y2, 20, \
minimum_val, maximum_val, slope, y_intercept)
print("Number of updates until convergence:", count)
# f is fairly close to g.
# c
minimum_val, maximum_val, slope, y_intercept, x1, x2, y1, y2, \
num_positive_points, num_negative_points = \
generate_dataset(20)
perceptron_learning_algorithm(num_positive_points, num_negative_points, x1, \
x2, y1, y2, 20, minimum_val, maximum_val, \
slope, y_intercept)
# d
minimum_val, maximum_val, slope, y_intercept, x1, x2, y1, y2, \
num_positive_points, num_negative_points = \
generate_dataset(100)
perceptron_learning_algorithm(num_positive_points, num_negative_points, x1, \
x2, y1, y2, 100, minimum_val, maximum_val, \
slope, y_intercept)
#e.
minimum_val, maximum_val, slope, y_intercept, x1, x2, y1, y2, \
num_positive_points, num_negative_points = \
generate_dataset(1000)
perceptron_learning_algorithm(num_positive_points, num_negative_points, x1, \
x2, y1, y2, 1000, minimum_val, maximum_val, \
slope, y_intercept)
# f is almost inseperable from g, and it look quite a bit longer in terms of
# updates for the algorithm to converge. |
fc808427cd358046e223304d41d129e66c3e2b9b | AleksandrSarkisov/sort-methods | /sort_methods.py | 2,370 | 4.09375 | 4 | def sort_select(a:list):
'''
Сортирует массив методом выбора
'''
if len(a) <= 1:
return a
i = 0
while i < (len(a)-1):
for j in range(i+1, len(a)):
if a[i] > a[j]:
a[i], a[j] = a[j], a[i]
i += 1
return a
def sort_insert(a:list):
'''
Сортирует массив методом вставки
'''
if len(a) <= 1:
return a
for i in range(1,len(a)):
j = i
while j > 0 and a[j] < a[j-1]:
a[j], a[j-1] = a[j-1], a[j]
j -= 1
return a
def sort_bubble(a:list):
'''
Сортирует массив методом пузырька
'''
if len(a) <= 1:
return a
for i in range(len(a)-1,0):
for j in range(i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
return a
def sort_quick(a:list):
'''
Сортирует массив методом Тони Хоара (быстрая сортировка)
'''
if len(a) <= 1:
return a
b = a[0]
l = []
r = []
m = []
for i in range(len(a)):
if a[i] < b:
l.append(a[i])
elif a[i] > b:
r.append(a[i])
else:
m.append(a[i])
sort_quick(l)
sort_quick(r)
k = 0
for i in l+m+r:
a[k] = i
k += 1
return a
def sort_merge(a:list):
'''
Сортирует массив методом слияния
'''
if len(a) <= 1:
return a
l = a[:len(a)//2]
r = a[len(a)//2:]
sort_merge(l)
sort_merge(r)
c = [0] * (len(l)+len(r))
i = j = k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
c[k] = l[i]
i += 1
else:
c[k] = r[j]
j += 1
k += 1
while i < len(l):
c[k] = l[i]
i += 1
k += 1
while j < len(r):
c[k] = r[j]
j += 1
k += 1
a[:] = c[:]
return a
a = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]
c = [1,2,3,6,5,4]
d = [6,5,4,1,2,3]
e = [5,8,10,1,3,4]
print(a,b,c,d, e)
print(sort_select(a), sort_select(b), sort_select(c), sort_select(d), sort_select(e))
print(sort_insert(a), sort_insert(b), sort_insert(c), sort_insert(d), sort_insert(e))
print(sort_bubble(a), sort_bubble(b), sort_bubble(c), sort_bubble(d), sort_bubble(e))
print(sort_quick(a), sort_quick(b), sort_quick(c), sort_quick(d), sort_quick(e))
print(sort_merge(a), sort_merge(b), sort_merge(c), sort_merge(d), sort_merge(e))
|
c619969b5428467ad282834a205dd840fb710826 | Edinas09/Challenges | /CountsDown.py | 263 | 4.03125 | 4 | # Please write a program, in any language, that counts down from 100 to 0 in steps of 2,
# and prints the numbers to the console or screen.
def counts_down():
for value in range(100, 0, -2):
print(value)
if __name__ == '__main__':
counts_down()
|
4ee46d33355e847ecdfd0bf756afb09c4e57897b | Edinas09/Challenges | /MakingAnagramas.py | 1,055 | 3.796875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the makeAnagram function below.
def makeAnagram(a, b):
list_a = Counter(a)
list_b = Counter(b)
countador_a = 0
countador_b = 0
resultado = 0
for key, value in list_a.items():
if key not in list_b:
countador_b = countador_b + value
if key in list_b and value > list_b[key]:
countador_b = countador_b + value - list_b[key]
for key, value in list_b.items():
if key not in list_a:
countador_a = countador_a + value
if key in list_a and value > list_a[key]:
countador_a = countador_a + value - list_a[key]
print(countador_a)
print(countador_b)
resultado = countador_a + countador_b
return resultado
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
print(res)
# fptr.write(str(res) + '\n')
# fptr.close()
|
d63166b955a07b1f19c0a9f23cd8e02925ce0ceb | Edinas09/Challenges | /itaretesNumber.py | 597 | 4.03125 | 4 | # Write a program, in any language (incl pseudocode) that iterates the numbers from 1 to 100.
# For any value divisible by 4, the program should print "Go".
# For any value divisible by 5, the program should print "Figure".
# For any value divisible by 4 and 5, the program should print "GoFigure".
def iterates_numbers():
for value in range(1, 101):
if value % 4 == 0 and value % 5 == 0:
print("GoFigure")
elif value % 4 == 0:
print("GO")
elif value % 5 == 0:
print("Figure")
if __name__ == '__main__':
iterates_numbers()
|
3ea78de4a3085d9463d8900cde3e1151947340a7 | Edinas09/Challenges | /SwapNodesALGO.py | 1,928 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
#
# Complete the 'swapNodes' function below.
#
# The function is expected to return a 2D_INTEGER_ARRAY.
# The function accepts following parameters:
# 1. 2D_INTEGER_ARRAY indexes
# 2. INTEGER_ARRAY queries
#
class Node:
def __init__(self, value, level):
self.value = value
self.level = level
self.left = None
self.right = None
def __repr__(self):
return f"<Value: {self.value} | level: {self.level} >"
def create_nodes(indexes):
node = Node(1,1)
list_node = [node]
fila = deque()
fila.append(node)
for left, right in indexes:
node = fila.popleft()
if left != -1:
node.left = Node(left, node.level+1)
list_node.append(node.left)
fila.append(node.left)
if right != -1:
node.right = Node(right, node.level+1)
list_node.append(node.right)
fila.append(node.right)
return list_node
def swapNodes(indexes, queries):
# Write your code here
result = create_nodes(indexes)
print(result[0].right)
print(result[0].left)
print(result[1].right)
print(result[1].left)
print(result[2].right)
print(result[2].left)
print(indexes)
print(queries)
return result
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
indexes = []
for _ in range(n):
indexes.append(list(map(int, input().rstrip().split())))
queries_count = int(input().strip())
queries = []
for _ in range(queries_count):
queries_item = int(input().strip())
queries.append(queries_item)
result = swapNodes(indexes, queries)
print(result)
# fptr.write('\n'.join([' '.join(map(str, x)) for x in result]))
# fptr.write('\n')
# fptr.close()
|
05f560e6687bb95d517bb651acec2e3568bcb02a | b55888938/270201050 | /lab8/example2.py | 245 | 4.03125 | 4 | def get_reversed(lists):
reverse_list = []
n = len(lists) - 1
if n < 0:
return reverse_list
else:
reverse_list.append(lists[n])
return reverse_list + get_reversed(lists[:n])
print(get_reversed([1,2,3,4])) |
195d9760157a5b0a063c440e1f905c9f832d7baa | b55888938/270201050 | /lab4/example5.py | 210 | 4.0625 | 4 |
numb_numb = int(input("How many fibonacci numbers?"))
sum_1 = 0
sum_2 = 1
print(sum_1)
print(sum_2)
for i in range(numb_numb - 2):
sum_3 = sum_1 + sum_2
sum_1 = sum_2
sum_2 = sum_3
print(sum_3) |
feaf4b357c323a5099219062a09918416b6c5c1c | b55888938/270201050 | /lab4/example1.py | 87 | 3.828125 | 4 | a = int(input("Enter an integer."))
for i in range(1, 11):
print(a, "X", i, "=", a*i) |
62295fb7d63d29becc26c4ac978f13fae9f16ef2 | b55888938/270201050 | /lab3/example1.py | 218 | 3.71875 | 4 | numb = input("Please enter a number.")
a = len(numb)
sum = 0
if int(numb[a-2]) == 0:
for i in range (a-1 ,a):
sum += int(numb[i])
print(sum)
else:
for i in range (a-2 ,a):
sum += int(numb[i])
print(sum) |
a31958f6182b3968efbae1d271c1a26d7fb28efb | Chris-Slade/CS1538-Team-Project | /event.py | 6,243 | 3.90625 | 4 | """Classes of events in the simulation, and an event queue."""
import heapq
import drinks
import util
from person import Person
class EventQueue(object):
"""A priority queue for Events."""
def __init__(self):
self._queue = []
def push(self, event):
"""Add an event to the queue."""
assert isinstance(event, Event), \
'Cannot push non-event ({}) to event queue'.format(type(event))
heapq.heappush(self._queue, event)
def pop(self):
return heapq.heappop(self._queue)
def peek(self):
return self._queue[0]
def clear(self):
self._queue.clear()
def __len__(self):
return self._queue.__len__()
def __iter__(self):
return self._queue.__iter__()
def __str__(self):
return self._queue.__str__()
################################### Events ####################################
class Event(object):
"""An event in the simulation.
Every event has a time, which is a nonnegative number.
Comparisons between events are done on the event times. To compare
identity, use the `is` operator.
"""
def __init__(self, time):
assert time >= 0, "Can't have negative time"
self._time = time
def get_time(self):
return self._time
def __eq__(self, other):
return self._time == other._time
def __lt__(self, other):
return self._time < other._time
def __le__(self, other):
return self._time <= other._time
def __gt__(self, other):
return self._time > other._time
def __ge__(self, other):
return self._time >= other._time
def __repr__(self):
return '<{}: {}>'.format(
self.__class__.__name__,
util.sec_to_tod(self._time)
)
def to_dict(self):
return {
'type' : self.__class__.__name__,
'time' : self.get_time()
}
class TimeEvent(Event):
"""A generic event that can be used to indicate special times (such as the
turn of an hour).
"""
pass
class HappyHourEnd(Event):
"""Event for when happy hour ends."""
def __str__(self):
return 'Happy hour ended at {}'.format(util.sec_to_tod(self.get_time()))
########################### Events that have people ###########################
class PersonEvent(Event):
"""An event with a person, which has a reference in the event object."""
def __init__(self, time, person):
super().__init__(time=time)
assert person is None or isinstance(person, Person), \
'Need a person'
self._person = person
def get_person(self):
return self._person
def __repr__(self):
return '<{}: {} at {}>'.format(
self.__class__.__name__,
self._person,
util.sec_to_tod(self._time)
)
def to_dict(self):
return {
'type' : self.__class__.__name__,
'time' : self.get_time(),
'person' : str(self.get_person())
}
############################### Customer Events ###############################
class CustomerEvent(PersonEvent):
def __init__(self, time, customer):
super().__init__(time=time, person=customer)
# Alias the get_person() method
CustomerEvent.get_customer = CustomerEvent.get_person
class Arrival(CustomerEvent):
"""Customer arrived."""
def __str__(self):
return '{} arrived at {}'.format(
self.get_customer(),
util.sec_to_tod(self.get_time())
)
class Departure(CustomerEvent):
"""Customer departed."""
def __str__(self):
return '{} departed at {}'.format(
self.get_customer(),
util.sec_to_tod(self.get_time())
)
class OrderDrink(CustomerEvent):
"""Customer orders a drink."""
def __str__(self):
return '{} ordered a drink (wants {} more) at {}'.format(
self.get_customer(),
self.get_customer().drinks_wanted(),
util.sec_to_tod(self.get_time())
)
class DeliverDrink(CustomerEvent):
"""Drink delivered to customer. NB: Server doesn't have to be contained in
this event.
"""
def __str__(self):
return 'Drink was delivered to {} at {}'.format(
self.get_customer(),
util.sec_to_tod(self.get_time())
)
class CustomerSeated(CustomerEvent):
"""Dummy event for showing when a customer is seated."""
def __init__(self, time, customer, server):
super().__init__(time=time, customer=customer)
self._server = server
def get_server(self):
return self._server
def to_dict(self):
tmp = super().to_dict()
tmp['seated_by'] = str(self.get_server())
return tmp
def __str__(self):
return '{} was seated by {} at {}'.format(
self.get_customer(),
self.get_server(),
util.sec_to_tod(self.get_time())
)
################################ Server Events ################################
class IdleEventMixin(object):
def __str__(self):
return '{} is idle at {}'.format(
self.get_person(),
util.sec_to_tod(self.get_time())
)
class ServerEvent(PersonEvent):
def __init__(self, time, server):
super().__init__(time=time, person=server)
ServerEvent.get_server = ServerEvent.get_person
class ServerIdle(ServerEvent, IdleEventMixin):
pass
############################## Bartender Events ###############################
class BartenderEvent(PersonEvent):
def __init__(self, time, bartender):
super().__init__(time=time, person=bartender)
BartenderEvent.get_bartender = BartenderEvent.get_person
class BartenderIdle(BartenderEvent, IdleEventMixin):
pass
################################ Miscellaneous ################################
class PreppedDrink(Event):
def __init__(self, time, order):
super().__init__(time=time)
self._order = order
def get_order(self):
return self._order
def __str__(self):
return 'Drink order for {} prepared at {}'.format(
self.get_order().customer,
util.sec_to_tod(self.get_time())
)
|
2c5ac096ec3a632930f550114f504dee8fb4ef87 | enrib82/Pr-ctica-2 | /Numero mayor.py | 164 | 3.875 | 4 | a=int(input("Ingrese un numero: "))
b=int(input("Ingrese un numero: "))
if a > b:
print "el numero mayor es" ,a,
else:
print "el numero mayor es" ,b,
|
349ab833260612e5a8a095f7bb6e81d51e36e1a0 | KnightApu/Dynamic-Programming | /edit-distance2.py | 1,337 | 3.859375 | 4 |
# coding: utf-8
# In[17]:
import json
with open('E:\Spell and Grammar Checker\MS Word Add-in\csvtconvertson/miniDictionary.json', encoding="utf8") as f:
data = json.load(f)
str1 = "দেশর"
for i in range (len(data)):
print(data[i]['words'])
print (editDistance(str1, data[i]['words'], len(str1), len(data[i]['words'])))
def editDistance(str1, str2, m , n):
# If first string is empty, the only option is to
# insert all characters of second string into first
if m==0:
return n
# If second string is empty, the only option is to
# remove all characters of first string
if n==0:
return m
# If last characters of two strings are same, nothing
# much to do. Ignore last characters and get count for
# remaining strings.
if str1[m-1]==str2[n-1]:
return editDistance(str1,str2,m-1,n-1)
# If last characters are not same, consider all three
# operations on last character of first string, recursively
# compute minimum cost for all three operations and take
# minimum of three values.
return 1 + min(editDistance(str1, str2, m, n-1), # Insert
editDistance(str1, str2, m-1, n), # Remove
editDistance(str1, str2, m-1, n-1) # Replace
)
|
09b5e0397a0ff3776aed37f44fda22069263005b | berge156/Database-Managment-Chapman-University | /assignment_2/databaseFunctions.py | 1,720 | 4.0625 | 4 | import sqlite3
from Students import Students
def SelectAllFunction(cursor):
cursor.execute("SELECT * FROM Students")
all_rows = cursor.fetchall()
print(all_rows)
def SelectMajor(cursor, user_major):
cursor.execute("SELECT * FROM Students WHERE Major = ?", (user_major,))
all_rows = cursor.fetchall()
print(all_rows)
def SelectGPA(cursor, user_gpa):
cursor.execute("SELECT * FROM Students WHERE GPA = ?", (user_gpa,))
all_rows = cursor.fetchall()
print(all_rows)
def SelectAdvisor(cursor, user_advisor):
cursor.execute("SELECT * FROM Students WHERE FacultyAdvisor = ? ", (user_advisor,))
all_rows = cursor.fetchall()
print(all_rows)
def CreateStudent(cursor):
fname = raw_input("Enter First Name: ")
lname = raw_input("Enter Last Name: ")
gpa = raw_input("Enter GPA: ")
major = raw_input("Enter Major: ")
advisor = raw_input("Enter Faculty Advisor: ")
stu = Students(fname, lname, gpa, major, advisor)
cursor.execute("INSERT INTO Students('FirstName', 'LastName', 'GPA', 'Major', 'FacultyAdvisor')"
"VALUES (?, ?, ?, ?, ?)", stu.student_info())
def DeleteRecord(cursor, user_delete):
cursor.execute("DELETE FROM Students WHERE StudentId = " + user_delete)
all_rows = cursor.fetchall()
print(all_rows)
def UpdateStudentMajor(cursor, new_major, stud_id):
cursor.execute("UPDATE Students SET Major = ? WHERE StudentId = ?", (new_major, stud_id,))
all_rows = cursor.fetchall()
print(all_rows)
def UpdateStudentAdvisor(cursor, new_advisor, stud_id):
cursor.execute("UPDATE Students SET FacultyAdvisor = ? WHERE StudentId = ?", (new_advisor, stud_id))
all_rows = cursor.fetchall()
print(all_rows)
|
2c39ed3bf73a4c5728a039b11f6d782129941be3 | DegtyarBo/Portfolio | /calculator(ASCII)/calculator(ASCII).py | 3,946 | 3.796875 | 4 | first_value = input('Enter the first value: ')
second_value = input('Enter the second value: ')
operation = input('Operation: ')
# Первое Значение
if len(first_value) == 1:
n1 = (ord(first_value[0])-48) * 1
n0 = n1
if len(first_value) == 2:
n1 = (ord(first_value[0])-48) * 10
n2 = (ord(first_value[1])-48) * 1
n0 = n1+n2
if len(first_value) == 3:
n1 = (ord(first_value[0])-48) * 100
n2 = (ord(first_value[1])-48) * 10
n3 = (ord(first_value[2])-48) * 1
n0 = n1+n2+n3
if len(first_value) == 4:
n1 = (ord(first_value[0])-48) * 1000
n2 = (ord(first_value[1])-48) * 100
n3 = (ord(first_value[2])-48) * 10
n4 = (ord(first_value[3])-48) * 1
n0 = n1+n2+n3+n4
if len(first_value) == 5:
n1 = (ord(first_value[0])-48) * 10000
n2 = (ord(first_value[1])-48) * 1000
n3 = (ord(first_value[2])-48) * 100
n4 = (ord(first_value[3])-48) * 10
n5 = (ord(first_value[4])-48) * 1
n0 = n1+n2+n3+n4+n5
if len(first_value) == 6:
n1 = (ord(first_value[0])-48) * 100000
n2 = (ord(first_value[1])-48) * 10000
n3 = (ord(first_value[2])-48) * 1000
n4 = (ord(first_value[3])-48) * 100
n5 = (ord(first_value[4])-48) * 10
n6 = (ord(first_value[5])-48) * 1
n0 = n1+n2+n3+n4+n5+n6
if len(first_value) == 7:
n1 = (ord(first_value[0])-48) * 1000000
n2 = (ord(first_value[1])-48) * 100000
n3 = (ord(first_value[2])-48) * 10000
n4 = (ord(first_value[3])-48) * 1000
n5 = (ord(first_value[4])-48) * 100
n6 = (ord(first_value[5])-48) * 10
n7 = (ord(first_value[6])-48) * 1
n0 = n1+n2+n3+n4+n5+n6+n7
if len(first_value) == 8:
n1 = (ord(first_value[0])-48) * 10000000
n2 = (ord(first_value[1])-48) * 1000000
n3 = (ord(first_value[2])-48) * 100000
n4 = (ord(first_value[3])-48) * 10000
n5 = (ord(first_value[4])-48) * 1000
n6 = (ord(first_value[5])-48) * 100
n7 = (ord(first_value[6])-48) * 10
n8 = (ord(first_value[7])-48) * 1
n0 = n1+n2+n3+n4+n5+n6+n7+n8
# Второе Значение
if len(second_value) == 1:
n1 = (ord(second_value[0])-48) * 1
n00 = n1
if len(second_value) == 2:
n1 = (ord(second_value[0])-48) * 10
n2 = (ord(second_value[1])-48) * 1
n00 = n1+n2
if len(second_value) == 3:
n1 = (ord(second_value[0])-48) * 100
n2 = (ord(second_value[1])-48) * 10
n3 = (ord(second_value[2])-48) * 1
n00 = n1+n2+n3
if len(second_value) == 4:
n1 = (ord(second_value[0])-48) * 1000
n2 = (ord(second_value[1])-48) * 100
n3 = (ord(second_value[2])-48) * 10
n4 = (ord(second_value[3])-48) * 1
n00 = n1+n2+n3+n4
if len(second_value) == 5:
n1 = (ord(second_value[0])-48) * 10000
n2 = (ord(second_value[1])-48) * 1000
n3 = (ord(second_value[2])-48) * 100
n4 = (ord(second_value[3])-48) * 10
n5 = (ord(second_value[4])-48) * 1
n00 = n1+n2+n3+n4+n5
if len(second_value) == 6:
n1 = (ord(second_value[0])-48) * 100000
n2 = (ord(second_value[1])-48) * 10000
n3 = (ord(second_value[2])-48) * 1000
n4 = (ord(second_value[3])-48) * 100
n5 = (ord(second_value[4])-48) * 10
n6 = (ord(second_value[5])-48) * 1
n00 = n1+n2+n3+n4+n5+n6
if len(second_value) == 7:
n1 = (ord(second_value[0])-48) * 1000000
n2 = (ord(second_value[1])-48) * 100000
n3 = (ord(second_value[2])-48) * 10000
n4 = (ord(second_value[3])-48) * 1000
n5 = (ord(second_value[4])-48) * 100
n6 = (ord(second_value[5])-48) * 10
n7 = (ord(second_value[6])-48) * 1
n00 = n1+n2+n3+n4+n5+n6+n7
if len(second_value) == 8:
n1 = (ord(second_value[0])-48) * 10000000
n2 = (ord(second_value[1])-48) * 1000000
n3 = (ord(second_value[2])-48) * 100000
n4 = (ord(second_value[3])-48) * 10000
n5 = (ord(second_value[4])-48) * 1000
n6 = (ord(second_value[5])-48) * 100
n7 = (ord(second_value[6])-48) * 10
n8 = (ord(second_value[7])-48) * 1
n00 = n1+n2+n3+n4+n5+n6+n7+n8
#Операция
if operation == '+':
answer = n0 + n00
if operation == '-':
answer = n0 - n00
if operation == '*':
answer = n0 * n00
if operation == '/':
answer = n0 / n00
#Ответ
print('Answer: ' + '%s %s %s = %s' %(first_value, operation, second_value, answer))
|
bcb8b80ca2f312ce7b3158ab9712260a902cd6c6 | Novi0106/IronAndre | /Week 7/GNOD/.ipynb_checkpoints/GNOD_Functions-checkpoint.py | 5,666 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# %%
def billboard_scraper():
#import libraries
import requests
from bs4 import BeautifulSoup
import pandas as pd
from tqdm.notebook import tqdm
#set parameters
url = "https://www.billboard.com/charts/hot-100"
response = requests.get(url)
response.status_code
#create soup
soup = BeautifulSoup(response.content, 'html.parser')
#populate lists with parsed content
song = []
artist = []
rank = []
len_charts = len(soup.select('span.chart-element__information__song'))
for i in tqdm(range(len_charts)):
song.append(soup.select("span.chart-element__information__song")[i].text)
artist.append(soup.select("span.chart-element__information__artist")[i].text)
rank.append(soup.select("span.chart-element__rank__number")[i].text)
billboard100 = pd.DataFrame({"song":song, "artist":artist})
return billboard100
# %%
def basic_recommendation_engine(billboard):
song = input("What is the name of your song?")
#get the billboard record - if available
check = billboard[billboard['song'].str.lower().str.replace(" ","").str.contains(song)]
#get the index of the song in the entry
index = check.index.tolist()
#run the recommendation
if len(check) != 0:
answer = input("Do you mean " + billboard.song[index].values[0] + " by " + billboard.artist[index].values[0] + "?")
#make a song suggestion
if answer.lower() == 'yes':
suggestion = billboard.sample().index.tolist()
print("Nice! This is a hot song! You might also like " + billboard['song'][suggestion].item() + " by " + billboard['artist'][suggestion].item())
else:
return clustering(), song
# %%
def clustering():
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
tracks = pd.read_csv('tracks.csv')
# load and scale the dataframe with all track details
numeric = tracks.select_dtypes(exclude = 'object')
scaler = StandardScaler().fit(numeric)
scaled = scaler.fit_transform(numeric)
numeric_scaled = pd.DataFrame(scaled)
# construct the K means prediction model and reference df
kmeans = KMeans(n_clusters = 8, random_state=40).fit(numeric_scaled)
clusters = kmeans.predict(numeric_scaled)
track_cluster = pd.DataFrame(tracks)
track_cluster['cluster'] = clusters
return kmeans, track_cluster
# %%
def spotify_recommendation(kmeans, track_cluster, sp, song):
import pandas as pd
from IPython.display import IFrame
# compare user input
song_id = sp.search(q = song, type = 'track', limit=1)['tracks']['items'][0]['uri']
features = pd.DataFrame(sp.audio_features(song_id)).drop(columns = ['type','id','uri','track_href','analysis_url', 'time_signature'])
prediction = kmeans.predict(features)[0]
suggestion = track_cluster[track_cluster.cluster == prediction].sample(1)
suggestion = suggestion['name'].values[0]
artist = sp.search(q = suggestion, type = 'track', limit=1)['tracks']['items'][0]['artists'][0]['name']
track_id = sp.search(q = suggestion, type = 'track', limit=1)['tracks']['items'][0]['id']
message = print(" How about trying out " + str(suggestion) + " by " + str(artist) + "?")
display(IFrame(src=f"https://open.spotify.com/embed/track/{track_id}",
width="320",
height="80",
frameborder="0",
allowtransparency="true",
allow="encrypted-media",))
# %%
def GNOD_recommender(client_id, client_secret):
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=client_id, client_secret=client_secret))
billboard = billboard_scraper()
song = input("What is the name of your song? Answer: ").lower().replace(" ", '')
#get the billboard record - if available
check = billboard[billboard['song'].str.lower().str.replace(" ","").str.contains(song)]
#get the index of the song in the entry
index = check.index.tolist()
# check if the check has returned a value or not (is the song hot or not?)
if len(check) == 0:
song_check = sp.search(q = song, type = 'track', limit=1)['tracks']['items'][0]['name']
artist_check = sp.search(q = song, type = 'track', limit=1)['tracks']['items'][0]['artists'][0]['name']
answer = input("Do you mean " + song_check + " by " + artist_check + "? Answer: ")
if answer.lower() == 'yes':
kmeans,track_cluster = clustering()
spotify_recommendation(kmeans, track_cluster, sp, song)
else:
print("Hmm looks like there are multiple songs with that title, please try with a different song by the same artist!")
else:
answer = input("Do you mean " + billboard.song[index].values[0] + " by " + billboard.artist[index].values[0] + "?")
# provide a suggestion in case the song is the list
if answer.lower() == 'yes':
suggestion = billboard.sample().index.tolist()
print("Nice! This is a hot song! You might also like " + billboard['song'][suggestion].item() + " by " + billboard['artist'][suggestion].item())
else:
print("Well, not so hot after all. We were thinking about different tracks.")
|
4674bc6ed28801e9264776de99b83af367aa9e01 | tkakar/DataPrep | /Python Codes for Projects/Python Minor Coding Tasks/miscellaneous.py | 1,634 | 3.765625 | 4 | ####### print frizzbuzz question
for i in range(1,101):
if i%3==0 and i%5==0:
print (i, "frizzBuzz")
elif i%3==0:
print (i, "Buzz")
elif i%5==0:
print (i, "frizz")
else: print (i)
### return indices of two numbers whose sum add to a target number
nums = [1, 2, 7, 11, 15, 19];
target = 26;
result=[];
for i in range(0, len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
break
# when array is sorted ####
my_map = {};
size = len(nums);
for i in range( size):
my_map[nums[i]] = i;
print my_map, target;
for i in range(size):
if target - nums[i] in my_map:
print [i+1, my_map[target - nums[i]]+1]
break;
######## Code to check if sum of two consecutive elements in array is equal to target
numbers = [2,7,11,15]
target = 9;
# print target
for i in range(0, len(numbers)):
for j in range(i+1, len(numbers)):
# print (numbers[i] + numbers[j] == target)
if i < j and numbers[i] + numbers[j] == target:
print "ans", [i+1, j+1]
# else:
# continue;
# # optimize above code using hashing to remove the second loop
######## Code to reverse a number
def reverse(x):
if x > 0: # handle positive numbers
a = int(str(x)[::-1])
if x <=0: # handle negative numbers
a = -1 * int(str(x*-1)[::-1])
# handle 32 bit overflow
mina = -2**31
maxa = 2**31 - 1
if a not in range(mina, maxa):
return 0
else:
return a
x = '123'
print reverse(x)
# print x[::-1]
|
44fde5a47ac4b018cd39bd3a83b80d8f5612d9d3 | afcummings/python-challenge | /pypoll/main.py/main.py/pypoll.py | 1,614 | 3.5 | 4 | import csv
candidates = []
total_votes = []
num_votes = 0
with open('election_data.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
column = next(csvreader,None)
for column in csvreader:
num_votes = num_votes + 1
candidate = column[2]
if candidate in candidates:
candidate_info = candidates.index(candidate)
total_votes[candidate_info] = total_votes[candidate_info] + 1
else:
candidates.append(candidate)
total_votes.append(1)
percents = []
maximum = 0
max_votes = total_votes[0]
for count in range(len(candidates)):
new_percents = round(total_votes[count]/num_votes*100, 2)
percents.append(new_percents)
if total_votes[count] > max_votes:
max_votes = total_votes[count]
maximum = count
winner = candidates[maximum]
print("Election Results\n")
print(" \n")
print(f"Total Votes: {num_votes}\n")
for count in range(len(candidates)):
print(f"{candidates[count]}: {percents[count]}% ({total_votes[count]})\n")
print(" \n")
print(f"The winner is: {winner}\n")
results = f"pypoll_results.txt"
with open(results, 'w') as results_write:
results_write.write("Election Results\n")
results_write.write(" \n")
results_write.write(f"Total Votes: {num_votes}\n")
for count in range(len(candidates)):
results_write.write(f"{candidates[count]}: {percents[count]}% ({total_votes[count]})\n")
results_write.write(" \n")
results_write.write(f"The winner is: {winner}\n")
results_write.write(" \n")
|
fb0055af02a4823c00e6baeaa1c44c3089dacd4a | hovell722/eng-54-python-practice-exercises | /exercise_102.py | 610 | 4.3125 | 4 | # # Create a little program that ask the user for the following details:
# - Name
# - height
# - favourite color
# - a secrete number
# Capture these inputs
# Print a tailored welcome message to the user
# print other details gathered, except the secret of course
# hint, think about casting your data type.
name = input("What is you name? ")
name = name.title()
height = int(input("What is your height in cm's? "))
colour = input("What is your favourite colour? ")
number = int(input("Give me a secret number: "))
print(f"Hello {name}, you are {height}cm's tall and your favourite colour is {colour}") |
d2d41bc519f79737818c852306c97b988e89ace7 | hovell722/eng-54-python-practice-exercises | /exercise_107.py | 1,370 | 4.46875 | 4 | # SIMPLEST - Restaurant Waiter Helper
# User Stories
#1
# AS a User I want to be able to see the menu in a formated way, so that I can order my meal.
#2
# AS a User I want to be able to order 3 times, and have my responses added to a list so they aren't forgotten
#3
# As a user, I want to have my order read back to me in formated way so I know what I ordered.
# DOD
# its own project on your laptop and Github
# be git tracked
# have 5 commits mininum!
# has documentation
# follows best practices
# starter code
menu = ['falafel', 'HuMMus', 'coUScous', 'Bacalhau a Bras']
food_order = []
menu[0] = menu[0].title()
menu[1] = menu[1].title()
menu[2] = menu[2].title()
menu[3] = menu[3].title()
print("Here is the menu")
count = 0
for food in menu:
count += 1
print(count, food)
count = 0
while count < 3:
count += 1
order = input("What food would you like to order? Give the number: ")
if order == str(1):
order = menu[0]
elif order == str(2):
order = menu[1]
elif order == str(3):
order = menu[2]
elif order == str(4):
order = menu[3]
food_order.append(order)
count = 0
print("You have ordered: ")
for food in food_order:
count += 1
print(count, food)
# I need to print each item from the list
# print(menu[0])
# before I print I need to make them all capitalized
# print everything |
7c6ffcf1b39e3bdb6f8e581113d9e5b3650e680b | iaq2/Apriori | /Apriori.py | 648 | 3.8125 | 4 |
import pandas as pd
from itertools import combinations
excel_file = "dba_1.xlsx"
database = pd.read_excel(excel_file, header=None)
#print(database)
#min_support = input('Enter Minimum Support Value')
#Gets all unique items
unique_items = set()
for i, entry in database.iterrows():
for item in entry:
unique_items.add(item)
unique_items.remove(pd.np.nan)
print(unique_items)
#combinations of unique items
tables = []
for i in range(1,len(unique_items)):
table = {}
comb = list(combinations(unique_items, i))
print(comb)
for i, entry in database.iterrows():
print(list(entry))
input()
|
e010f17673b3fd82118f26a92283d0f4639f48af | longjiazhen/Python | /MergeSort.py | 1,998 | 3.890625 | 4 | import random
# 递归求列表中最大值
# def getMax(list, L, R):
# if L == R: # base case,停止递归的地方
# return list[L]
# mid = int((L+R)/2) # 如果要防溢出,可以写成 L + ((R-L)/2)
# maxLeft = getMax(list, L, mid)
# maxRight = getMax(list, mid+1, R)
# return max(maxLeft, maxRight)
#
#
# list = [3, 5, 7, 1, 0 ]
# maxItem = getMax(list, 0, len(list)-1)
# print(maxItem)
# 外排
def Merge(list, L, mid, R):
# print(list)
list2 = []
i = L
j = mid + 1
# 两个都没有越界时
while(i<=mid and j<=R):
# print("list[" + str(i) + "]=" + str(list[i]) + " list[" + str(j) + "]=" + str(list[j]))
if list[i] < list[j]:
list2.append(list[i])
i += 1
else:
list2.append(list[j])
j += 1
# 有且只有一个会越界
# 如果左边越界
while(j <= R):
list2.append(list[j])
j += 1
# 如果右边越界
while(i <= mid):
list2.append(list[i])
i += 1
for i in range(0, len(list2)):
list[L + i] = list2[i]
# 注意这里list2的i位置拷贝回list的L+i位置,而不是简单地赋值list=list2
# print(list)
return list
def MergeSort(list, L, R):
# print("Before:", end=" ")
# print(list, end=" ")
# print("L = " + str(L) + " R = " + str(R))
if len(list) <= 1:
return list
if L == R:
return
mid = int((L+R)/2)
MergeSort(list, L, mid)
MergeSort(list, mid+1, R)
list = Merge(list, L, mid, R)
# print("After:", end=" ")
# print(list)
# print("L = " + str(L) + " R = " + str(R))
return list
def CreateRandomList():
list = []
list_len = random.randint(0, 10)
for i in range(list_len):
list.append(random.randint(-100, 100))
return list
list = CreateRandomList()
print(list)
# list = [3, 7, 2, 9]
# Merge(list, 0, 1, 3)
# list = [7, 3, 9, 2]
MergeSort(list, 0, len(list)-1)
print(list)
|
12bfab7e083f2b0326e72ec60cd53c42be2dd280 | monicajoa/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | 425 | 4.15625 | 4 | #!/usr/bin/python3
"""This module holds a function
From JSON string to Object
"""
import json
def from_json_string(my_str):
"""function that returns an object (Python data structure)
represented by a JSON string
Arguments:
my_str {[str]} -- string to convert to object
Returns:
[object] -- (Python data structure) represented by a JSON string
"""
return json.loads(my_str)
|
eb8ac907b35bacba795aae007f4d3adb03a77e23 | monicajoa/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 703 | 4.5 | 4 | #!/usr/bin/python3
"""
This module hold a function that prints a square with the character #.
"""
def print_square(size):
"""
This function prints square by the size
Paramethers:
size: length of the square
Errors:
TypeError: size must be an integer
ValueError: size must be >= 0
Returns:
Nothing
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
if (type(size) is float and size < 0):
raise TypeError("size must be an integer")
for x in range(size):
for y in range(size):
print('#', end="")
print()
|
321d3dffc80229b6788fd004f0baade38341a580 | monicajoa/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 333 | 4 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
if matrix == [[]]:
print("")
else:
for x in matrix:
for j in range(0, len(x)):
if j < len(x) - 1:
print("{:d}".format(x[j]), end=" ")
else:
print("{:d}".format(x[j]))
|
05280ad60cef6f657051257bf420db4722a1ee48 | sakshipadwal/python- | /Python/pyrmaid1.py | 167 | 3.796875 | 4 | def pattern(n):
k= 2 * n-2
for i in range (0, n):
for j in range (0, i + 1):
print("*", end=" ")
print("\r")
pattern(5) |
63dac65210c83675bf6c7b07e055231e7434a8ec | enkefalos/PythonCourse | /hw1_question3.py | 1,184 | 4.28125 | 4 | def compare_subjects_within_student(subj1_all_students :dict,
subj2_all_students :dict):
"""
Compare the two subjects with their students and print out the "preferred"
subject for each student. Single-subject students shouldn't be printed.
Choice for the data structure of the function's arguments is up to you.
"""
for key, val in subj1_all_students.items():
if key != 'subject' and key in subj2_all_students:
print(key, end = ' ')
if max(val) > max(subj2_all_students[key]):
print(subj1_all_students['subject'])
continue
print(subj2_all_students['subject'])
if __name__ == '__main__':
# Question 3
math_grades = {
'subject': 'Math',
'Zvi': (100, 98),
'Omri': (68, 93),
'Shira': (90, 90),
'Rony': (85, 88) }
history_grades = {
'subject': 'History',
'Zvi': (69, 73),
'Omri': (88, 74),
'Shira': (92, 87),
'Rony': (92, 98) }
print('Preffered subject per student')
compare_subjects_within_student(math_grades, history_grades)
|
21d86ad1c6ebf2a3e65014f59a79202004f2bbb8 | hanshiqiang365/turtle_demo | /turtle_sakuragray.py | 1,032 | 3.515625 | 4 | #author: hanshiqiang365 (微信公众号:韩思工作室)
from turtle import *
from random import *
from math import *
import pygame
import time
def tree(n, l):
pd()
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n)
forward(l)
if n > 0:
b = random() * 15 + 10
c = random() * 15 + 10
d = l * (random() * 0.35 + 0.6)
right(b)
tree(n - 1, d)
left(b + c)
tree(n - 1, d)
right(c)
else:
right(90)
n = cos(radians(heading() - 45)) / 4 + 0.5
pencolor(n, n, n)
circle(2)
left(90)
pu()
backward(l)
bgcolor(0.5, 0.5, 0.5)
title('Sakura drawed by hanshiqiang365 - Happy New Year 2020 ')
pygame.mixer.init()
pygame.mixer.music.load("sakura_bgm.mp3")
pygame.mixer.music.play(-1)
time.sleep(10)
ht()
speed(0)
tracer(1000000, 0)
left(90)
pu()
backward(300)
tree(12, 100)
pu()
goto(30, -300)
pd()
write('韩思工作室出品', font=("繁体隶书", 30, "bold"))
done()
|
ad657663dfafaf32f7865234f01722a59b9983bc | absheth/elem_of_AI | /game_of_chance/yahtzee.py | 1,951 | 3.59375 | 4 | # Akash Sheth, 2017 || Game of Chance
# Ref[1]: https://stackoverflow.com/questions/2213923/python-removing-duplicates-from-a-list-of-lists
# Ref[2]: https://stackoverflow.com/questions/10272898/multiple-if-conditions-in-a-python-list-comprehension
# Ref[3]: https://stackoverflow.com/questions/25010167/e731-do-not-assign-a-lambda-expression-use-a-def
import itertools
# take the input from user
print "Enter the space separated roll configuration: "
roll_config = map(int, raw_input().split())
# calculate the score
def calculate_score(roll):
return 25 if roll[0] == roll[1] and roll[1] == roll[2] else sum(roll)
# returns the configuration with expected score
def max_node(roll, configuration):
# lambda -- Ref[2], Ref[3]
def a(roll_a): return roll_a[0] if roll_a[1] else roll_a[2]
# lambda -- Ref[2], Ref[3]
all_combinations = [[a([roll_a, configuration[0], roll[0]]),
a([roll_b, configuration[1], roll[1]]),
a([roll_c, configuration[2], roll[2]])] for roll_a in range(1, 7) for roll_b in range(1, 7) for roll_c in range(1, 7)]
# remove all the duplicates
# Ref[1] -- START
all_combinations.sort()
no_dup_combos = list(all_combinations for all_combinations, _ in itertools.groupby(all_combinations))
# Ref[1] -- END
return [configuration, sum(calculate_score(rolls) for rolls in no_dup_combos) / float(len(no_dup_combos))]
# Finds the next roll
def find_next_roll(roll_config):
whether_roll = [True, False]
current_max = [0, 0]
for dice_1 in whether_roll:
for dice_2 in whether_roll:
for dice_3 in whether_roll:
new_max = max_node(roll_config, [dice_1, dice_2, dice_3])
current_max = new_max if new_max[1] > current_max[1] else current_max
return current_max
solution = find_next_roll(roll_config)
print "Next roll -->", solution[0], "|| Expected Score -->", solution[1]
|
f84afd95a94c6b3fc8c33c6bcd890819558d028b | tyteotin/codewars | /6_kyu/shorten_number.py | 1,759 | 4.09375 | 4 | """
Ok, here is a new one that they asked me to do with an interview/production setting in mind.
You might know and possibly even Angular.js; among other things, it lets you create your own filters that work as functions you put in your pages to do something specific to her kind of data, like shortening it to display it with a more concise notation.
In this case, I will ask you to create a function which return another function (or process, in Ruby) that shortens numbers which are too long, given an initial arrays of values to replace the Xth power of a given base; if the input of the returned function is not a numerical string, it should return the input itself as a string.
An example which could be worth more than a thousand words:
filter1 = shorten_number(['','k','m'],1000)
filter1('234324') == '234k'
filter1('98234324') == '98m'
filter1([1,2,3]) == '[1,2,3]'
filter2 = shorten_number(['B','KB','MB','GB'],1024)
filter2('32') == '32B'
filter2('2100') == '2KB';
filter2('pippi') == 'pippi'
If you like to test yourself with actual work/interview related kata, please also consider this one about building a breadcrumb generator
"""
import math
def shorten_number(suffixes, base):
def lmd(x):
if(isinstance(x, basestring) == False):
return str(x)
elif(x.isdigit() == False):
return x
else:
x = int(x)
count = 0
div_res = x/base
while(div_res >= 1):
div_res /= base
if(count >= len(suffixes) - 1):
break
count += 1
remnant = int(x/math.pow(base, count))
return str(remnant) + suffixes[count]
return lmd
|
14f7a544807a575b1ee39c99bfbdad6c7efd90b1 | tyteotin/codewars | /6_kyu/is_triangle_number.py | 1,168 | 4.15625 | 4 | """
Description:
Description:
A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example,
6 is a triangle number because you can arrange 6 objects into an equilateral triangle:
1
2 3
4 5 6
8 is not a triangle number because 8 objects do not form an equilateral triangle:
1
2 3
4 5 6
7 8
In other words, the nth triangle number is equal to the sum of the n natural numbers from 1 to n.
Your task:
Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any non-integers,
including non-number types, are not triangle numbers).
You are encouraged to develop an effective algorithm: test cases include really big numbers.
Assumptions:
You may assume that the given input, if it is a number, is always positive.
Notes:
0 and 1 are triangle numbers.
"""
def is_triangle_number(number):
if(str(number).isdigit() == False):
return False
elif(float(number).is_integer() == False):
return False
else:
if(((8*number+1)**(1.0/2)).is_integer() == True):
return True
else:
return False
|
7d25f5294b8795457921e6a1f72c7bd10b3c3a07 | Daizt/Python-Learning-Notes | /dynamic_programing/Shortest Common Subsequence.py | 598 | 3.78125 | 4 | # Shortest Common Subsequence
# 最短公共父列
# SCS[i,j] denotes the length of SCS of a[0:i] and b[0:j]
def SCS(a,b):
m,n = len(a),len(b)
scs = [[0 for _ in range(n+1)] for _ in range(m+1)]
scs[0] = list(range(n+1))
for i in range(m+1):
scs[i][0] = i
for i in range(1,m+1):
for j in range(1,n+1):
if a[i-1] == b[j-1]:
scs[i][j] = scs[i-1][j-1] + 1
else:
scs[i][j] = min(scs[i-1][j]+1,scs[i][j-1]+1)
return scs
def main():
a = "ABCBDAB"
b = "BDCABA"
scs = SCS(a,b)
print("the length of SCS is {}".format(scs[len(a)][len(b)]))
if __name__ == "__main__":
main() |
c09107e56d1e89be10428f08e5395588fdd40d23 | Daizt/Python-Learning-Notes | /dynamic_programing/Travelling Salesman Problem.py | 799 | 3.59375 | 4 | # Travelling Salesman Problem
# Using DP: C(S,i) denotes the cost of minimum cost path visiting each vertex in
# set S exactly once, starting at 0 ending at i(Note that i belongs to S). Thus the
# anwer to our problem is C(S,0), where S contains all the given cities.
def shortestPathDP(pos):
pos = [0,0] + pos
N = len(pos)//2
D = [[0 for _ in range(N)]for _ in range(N)]
for i in range(N):
for j in range(i+1,N):
dist = ((pos[i*2]-pos[j*2])**2+(pos[i*2+1]-pos[j*2+1])**2)**0.5
D[i][j] = D[j][i] = dist
def C(S,i):
if len(S) == 1:
return D[0][i]
else:
return min([C(S-{i},k) + D[k][i] for k in S-{i}])
S = set(list(range(N)))
return C(S,0)
def main():
pos = [200,0,200,10,200,50,200,30,200,25]
res = shortestPathDP(pos)
print(res)
if __name__ == "__main__":
main() |
727cc50b1e1907d34daa0cb0b8e4eb7c9af0fb87 | 3point14thon/bill_analyzer | /src/html_cscale.py | 1,384 | 3.515625 | 4 | def mk_color_span(vals, txts, lower_bound=0, upper_bound=1):
'''
Generates a string of html spans whos background colors
corospond to the values in vals. Larger numbers have a
greener color smaller have a redder.
Inputs:
vals (iterable of floats): Values to be used in generating
the rbgs.
txts (iterable of strings): The content of the spans.
lower_bound (float):The lowest value on the numeric scale.
upper_bound (float): The highest value on the numeric scale.
'''
span_start = '<span style="background-color:rgba'
color_doc = [span_start +
f'{c_scale(val, lower_bound, upper_bound)};">' +
str(txt) +
'</span>' for txt, val in zip(txts, vals)]
return ''.join(color_doc)
def c_scale(num_val, lower_bound=0, upper_bound=1):
'''
Returns a tuble of rgb values and opacity based on the inputs.
Larger numbers have a greener color smaller have a redder.
Inputs:
num _val (float): The value of this instance on the scale.
lower_bound (float):The lowest value on the numeric scale.
upper_bound (float): The highest value on the numeric scale.
Outputs: Tuple of rgba values
'''
c_max = 255
c_value = ((num_val-lower_bound)/(upper_bound-lower_bound))*c_max
return (c_max - c_value, c_value, 0, 0.2)
|
2dc9ad367da6489f01198d757997b1d154747f0c | Hersh500/Dynamic-Programming-Practice | /edit_distance.py | 1,293 | 3.90625 | 4 | ''' Edit Distance Problem: Given two strings of size m, n and set of operations replace (R), insert (I) and delete (D) all at equal cost.
Find minimum number of edits (operations) required to convert one string into another.'''
def print_matrix(matrix): #prints all rows in a two dimensional array
for row in matrix:
print(row)
def find_distance (str1, str2, copy, indel): #Uses a two dimensional array to find the edit distance
s = [ [0 for i in range(0, len(str2) + 1)] for j in range(0, len(str1) + 1)]
for i in range(1, len(str1) + 1): #Initializes the array
s[i][0] = s[i-1][0] + indel
for j in range(1, len(str2) + 1):
s[0][j] = s[0][j-1] + indel
for i in range(1, len(str1) + 1): #Loops through the array, using dynamic programming
for j in range(1, len(str2) + 1):
try:
if str1[i] == str2[j]:
s[i][j] = s[i-1][j-1]
else:
s[i][j] = min(s[i-1][j] + indel, s[i][j-1] + indel, s[i-1][j-1] + copy) #Uses the min to find the Minimum Edit Distance, finds the least costly edit
except IndexError:
s[i][j] = min(s[i-1][j] + indel, s[i][j-1] + indel, s[i-1][j-1] + copy)
print_matrix(s)
def main():
str1 = "alligator"
str2 = "gator"
copy = 1
indel = 1
find_distance(str1, str2, copy, indel)
if __name__ == "__main__":
main()
|
24ff0eaf61ebecc102e3769515330bb14c3f007d | genesysrm/Python_DataScience | /calculadorafiesta.py | 1,031 | 3.6875 | 4 | class Festa:
def _init_(self, c,s,d):
self.comida = c
self.suco = s
self.deco = d
def comida(self, qua):
c = 25 * qua
return c
def suco(self, qua, saudavel):
if(saudavel):
s = (5 * qua)
#suco = suco - (suco*0.05)
else:
s = (20 * qua)
return s
def decoracao(self, qua, diferenciada):
if(diferenciada):
valor = 50 + (10*qua)
return valor
else:
valor = 30 + (7.5 * qua)
return
pessoas = int(input("Digite a quantidade de pessoas convidadas para a festa: "))
tipodeco = int(input("Que tipo de decoração deseja 1 Normal ou 2 Diferenciada? Por favor responda com o numero de sua escolha: "))
if tipodeco==2:
dif = True
else:
dif = False
tipodeco = int(input("Que tipo de bebida deseja 1 Saudavel ou 2 Alcolica? Por favor responda com o numero de sua escolha: "))
if tipodeco==21:
saud = True
else:
saud = False
f = Festa()
total = f.total(pessoas,dif,saud)
print("O |
2b39a42620f4699c51c7d2679b042cd55dc6e1d3 | genesysrm/Python_DataScience | /medianotas.py | 478 | 3.609375 | 4 | notas = [5,5,6,6,7,7,8,8,9,9]
print( sum(notas) / float(len(notas)) )
notas= {"tati":[5,9,9], "luiz":[5,4,3],"paula":[6,6,6],"genesys":[6,8,9],"mutu":[7,7,7] }
def media(notas):
soma = 0
for n in notas:
soma = soma + n
return (soma / len(nota)
/////////////////////////////////////////
soma=0
for nome in notas:
media_da_pessoa = media(notas[nome])
print(nome,media_da_pessoa)
soma = soma + media_da_pessoa
media = soma/len(notas)
print(media)
|
d60efd85d0348706c2262820706a4234a775df1a | Sairahul-19/CSD-Excercise01 | /04_is_rotating_prime.py | 1,148 | 4.28125 | 4 | import unittest
question_04 = """
Rotating primes
Given an integer n, return whether every rotation of n is prime.
Example 1:
Input:
n = 199
Output:
True
Explanation:
199 is prime, 919 is prime, and 991 is prime.
Example 2:
Input:
n = 19
Output:
False
Explanation:
Although 19 is prime, 91 is not.
"""
# Implement the below function and run the program
from itertools import permutations
def is_rotating_prime(num):
l=[]
a=list(permutations(str(num),len(str(num))))
for i in a :
l.append("".join(i))
for k in l:
for j in range(2,int(k)):
if (int(k)%j)==0:
return False
return True
class TestIsRotatingPrime(unittest.TestCase):
def test_1(self):
self.assertEqual(is_rotating_prime(2), True)
def test_2(self):
self.assertEqual(is_rotating_prime(199), True)
def test_3(self):
self.assertEqual(is_rotating_prime(19), False)
def test_4(self):
self.assertEqual(is_rotating_prime(791), False)
def test_5(self):
self.assertEqual(is_rotating_prime(919), True)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
2d3f726b72caa4fb12fdd762e24577c5ca2b805d | AiramL/Comp-II-2018.1 | /aula01/Exercicio03.py | 754 | 3.84375 | 4 | from Exercicio01 import montarGradeCurricular
from Exercicio02 import inserirDisciplina
def ler_csv(arquivo):
grade = []
for linha in arquivo:
lista = linha.split(',')
codigo = lista[0]
nome = lista[1]
numRequisitos = lista[2]
requisitos = []
if numRequisitos != 0:
for indice in range(3, len(lista)-1):
requisitos+=[lista[indice]]
grade = montarGradeCurricular(grade, codigo, nome, numRequisitos, requisitos)
arquivo.close()
return grade
arquivo = open('C:\\Users\\airam\\Desktop\\Programao\\Python\\Comp II\\aula01\\gradeCurricular.txt','r') # alterar o diretorio do arquivo para o do seu PC
|
67cf5bd31636ab5f273983e058e620c3b995cb94 | Cegard/Exercises | /Python/fibonacci.py | 1,227 | 4.03125 | 4 | #!/usr/bin/env python
__author__ = "Cegard"
def fibo(n):
"""función iterativa de los n primeros
números de la serie Fibonacci"""
lst = []
a = 0
b = 1
counter = 0
while counter < n:
lst.append(b)
a,b = b,a+b
counter += 1
return lst
def fibo_r(n):
"""función recursiva de los n primeros
números de la serie Fibonacci"""
lst=[]
def _fibo_r(c, pa, pb):
"""clausura que computa los n primeros
números de la serie Fibonacci"""
if c < n:
lst.append(pb)
_fibo_r(c+1,pb,pb+pa)
_fibo_r(0,0,1)
return lst
def gen_fibo(n):
"""generador iterativo de los n primeros
números de la serie Fibonacci"""
a = 0
b = 1
c = 0
while c < n:
yield b
a, b = b, b+a
c += 1
pass
def gen_fibo_r(n):
"""generador recursivo de los n primeros
números de la serie Fibonacci"""
def fibo_r(c, pa, pb):
if c < n:
yield pb
yield from fibo_r(c+1,pb,pa+pb)
yield from fibo_r(0,0,1)
print (list(gen_fibo(6)))
print(list(gen_fibo_r(6)))
print(fibo(6))
print(fibo_r(6)) |
24052748fcbb908a8072d7338c7f0f8c452144ca | arvin1209/python | /basic_google_siri.py | 293 | 3.796875 | 4 | #This should reply hello or 1 depending on what you type
c=str(input("Type something to Pybuddy in quote marks"))
b="hello"
d="what is one times one"
e="what is 1*1"
f="what is 1 times 1"
g="what is one*one"
if c == b:
print("Hello to you too")
if c==d or e or f or g:
print("1")
|
ded4c7f00ce98b8dfcd5a16a0838cffd854c5a83 | MFori/partions_generator | /set.py | 3,179 | 3.75 | 4 | # Set partitions generator
# Author: Martin Forejt
# Version: 1.0
# Email: [email protected]
import sys
import random
# generate all partitions for given N
MODE_ALL = 1
# generate one random partition for given N
MODE_RANDOM = 2
# generate the next partition for given current partition
MODE_NEXT = 3
SUPPORTED_MODES = [MODE_ALL, MODE_RANDOM, MODE_NEXT]
def print_partition(partition):
# print formatted partition
parts = max(partition)
print("{", end="")
for p in reversed(range(1, parts + 1)):
part = [(i + 1) for i in range(len(partition)) if partition[i] == p]
if len(part) == 0:
break
print("{", end="")
print(*part, sep=",", end="")
if p > 1:
print("},", end="")
else:
print("}", end="")
print("}")
def next_partition(prev, m, n):
# return next partition for prev partition
i = 0
prev[i] += 1
while (i < n - 1) and (prev[i] > m[i + 1] + 1):
prev[i] = 1
i += 1
prev[i] += 1
if i == n - 1:
return -1
if prev[i] > m[i]:
m[i] = prev[i]
for j in range(0, i - 1):
m[j] = m[i]
return prev
def random_partition(n):
# generate random partition
items = [0] * n
groups = random.randint(1, n)
# first i items add to i group
for i in range(0, groups):
items[i] = i + 1
# next items add to random group
for i in range(groups, n):
items[i] = random.randint(1, groups)
random.shuffle(items)
return items
def all_partitions(n):
# generate all partitions
count = 0
partition = [1] * n
m = [1] * n
while partition != -1:
print_partition(partition)
partition = next_partition(partition, m, n)
count += 1
print("Total partitions: " + str(count))
return
def print_help():
# print help
print("MODES: 1 => ALL, 2 => RANDOM, 3 => NEXT")
print("set 'mode' 'arg'")
print("set 1/2 'N' (integer 1 5)")
print("set 3 'partition mask' (integer 3 1,2,2,3,1,4,1) represents: {{1,5},{2,3,7},{4},{6}}")
def parse_args(argv):
# parse cmd args
if len(argv) < 2:
return -1
try:
mode = int(argv[0])
if mode not in SUPPORTED_MODES:
return -1
except ValueError:
return -1
if mode == MODE_NEXT:
partition = [int(i) for i in argv[1].split(',')]
return [mode, partition]
else:
try:
n = int(argv[1])
except ValueError:
return -1
return [mode, n]
def main(argv):
conf = parse_args(argv)
if conf == -1:
print_help()
return
# print("configuration: ", end="")
# print(conf)
if conf[0] == MODE_ALL:
all_partitions(conf[1])
elif conf[0] == MODE_RANDOM:
partition = random_partition(conf[1])
print("Random partition: ", end="")
print_partition(partition)
else:
m = [1] * len(conf[1])
partition = next_partition(conf[1], m, len(conf[1]))
print("Next partition is: ", end="")
print_partition(partition)
return
if __name__ == '__main__':
main(sys.argv[1:])
|
f07f8e409d49a168b31dc24f0864eeeabb751b43 | nduprincekc/animation | /Animation.py | 254 | 3.75 | 4 | import turtle
turtle.bgcolor('lightpink')
turtle.pensize(12)
turtle.speed(0.2)
color = ['red','yellow','blue','orange']
for a in range(9):
for i in color:
turtle.color(i)
turtle.circle(50)
turtle.left(10)
turtle.mainloop()
|
9a5edf7340e74a986b4b3955386dd417524eb105 | q13245632/CodeWars | /Moving Zeros To The End.py | 393 | 3.96875 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-09
def move_zeros(array):
zeros = []
lst = []
for i in array:
if (type(i) == int or type(i) == float) and int(i) == 0:
zeros.append(0)
else:
lst.append(i)
lst.extend(zeros)
return lst
def move_zeros(array):
return sorted(array, key= lambda x: x == 0 and type(x) != bool) |
71b1332c26e6f3c998ff0bfa825bacf38b10e2bf | q13245632/CodeWars | /Double Cola.py | 407 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-20
def whoIsNext(names, r):
n = len(names)
if r < n:
return names[r - 1]
i = 0
f = n * (2 ** i)
r -= f
while r > 0:
i += 1
f = n * (2 ** i)
r -= f
r += (n * (2 ** i))
return names[(r / (2 ** i))]
def whoIsNext(names, r):
while r > 5:
r = (r - 4) / 2
return names[r-1] |
Subsets and Splits