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
fbbcfec4d5b94e5a30414e962b95ab506a60db77
lelong03/python_algorithm
/array/calculate_sqrt.py
295
3.640625
4
def mysqrt(n): start = 0 end = n mid = float(end + start) / 2 while ( (mid*mid) != n ) and ( abs((mid * mid) - n) > 0.1 ): if (mid*mid) > n: end = mid else: start = mid mid = float(end + start) / 2 return mid print(mysqrt(3))
0847e2a138d297ceb53d34e5c15004424227907e
lelong03/python_algorithm
/array/next_permutation.py
1,358
4.125
4
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. # If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). # The replacement must be in-place, do not allocate extra memory. # Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. def reverse(arr, begin, end): while begin < end: arr[begin], arr[end] = arr[end], arr[begin] begin += 1 end -= 1 def next_permutation(arr, begin, end): partion_index = end-1 while partion_index > -1 and arr[partion_index] >= arr[partion_index+1]: partion_index -= 1 if partion_index == -1: return reverse(arr, begin, end) change_index = end while change_index > -1 and arr[change_index] <= arr[partion_index]: change_index -= 1 arr[change_index], arr[partion_index] = arr[partion_index], arr[change_index] return reverse(arr, partion_index+1, end) a = [1,3,4,2] next_permutation(a, 0, len(a)-1) print a a = [1,4,2,3] next_permutation(a, 0, len(a)-1) print a a = [1,2,3,4] next_permutation(a, 0, len(a)-1) print a a = [4,3,2,1] next_permutation(a, 0, len(a)-1) print a a = [5,1,1] next_permutation(a, 0, len(a)-1) print a
90cc3867cb7a055bfea83ee921836bbb94ff915d
lelong03/python_algorithm
/recursion/list_sub_sets.py
1,117
4.28125
4
# Question: List all sub sets of one set # Solutions: # - with base case n = 0, there is one sub set {} # - with n = 1, there are: {}, {a} # - with n = 2, there are: {}, {a}, {b}, {a,b} # - with n = 3, there are: {}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, {a,b,c} # P(3) = P(2) + {c} # Using Recursion def list_sub_set(a_set, n): set_len = n + 1 if set_len == 0: return [[]] result = [] for subset in list_sub_set(a_set, n-1): result.append(subset) result.append(subset + list(a_set[n])) return result # Combinatorics def list_sub_set_2(a_set): set_length = len(a_set) max = 1 << set_length result = [] for i in range(max): result.append(get_sub_set(a_set, set_length, i)) return result def get_sub_set(a_set, set_length, number): sub_set = [] index = set_length-1 while number > 0: if (number & 1) == 1: sub_set.append(a_set[index]) index -= 1 number >>= 1 return sub_set aset = ['a', 'b', 'c'] print list_sub_set(aset, len(aset)-1) aset = ['a', 'b', 'c', 'd'] print list_sub_set_2(aset)
14c124a1acc458c7a4864df345005edbbc5950af
lelong03/python_algorithm
/recursion/multiply.py
637
4.03125
4
# Question: multiply two positive numbers without using * operator # Solutions: with a * b, we try to count how many squares in the rectangle grid when the length and width of grid are a and b def multiply(a, b): smaller = a if a < b else b bigger = (a+b) - smaller return multiply_helper(smaller, bigger) def multiply_helper(smaller, bigger): if smaller == 0: return 0 if smaller == 1: return bigger half_value = multiply_helper(smaller>>1, bigger) if smaller % 2 == 0: return half_value + half_value else: return half_value + half_value + bigger print multiply(7, 8)
55efe1d1aa2f16790965b6389019c91b96066b90
kevinpatell/Object-Oriented-Programming
/player/player.py
1,497
3.609375
4
class Player: def __init__(self, gold_coins = 0, health_points = 10, lives = 5): self.gold_coins = gold_coins self.health_points = health_points self.lives = lives def __str__(self): return (f"Your Score is\nGold treasure = {self.gold_coins}\nHealth = {self.health_points}\nLife = {self.lives}") def level_up(self): self.lives += 1 def collect_treasure(self): self.gold_coins += 1 if self.gold_coins % 10 == 0: self.level_up() def do_battle(self, damage): self.health_points -= damage if self.health_points < 1: self.lives -= 1 self.health_points = 10 if self.lives == 0: self.restart() def restart(self): self.gold_coins = 0 self.health_points = 10 self.lives = 5 play = Player() # play2 = Player(30, 2, 5) # play3 = Player (7, 9, 3) # print(play2.do_battle(5)) # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # play2.collect_treasure() # (play.do_battle(10)) # (play.do_battle(9)) # (play.do_battle(1)) # # (play.do_battle(8)) # # (play.do_battle(5)) (play.do_battle(11)) # print(play2) print(play) # print(play3)
a064701eb3d31e6496bf0a19a05495dfba855ea3
kapil1308/knn_classifier
/knn_classifier.py
1,863
3.765625
4
from sklearn.datasets import load_breast_cancer # Import the Breast Cancer Wisconsin (Diagnostic) Data Set from sklearn.neighbors import KNeighborsClassifier # Importing the KNNClassifier algorithm to be used in the project from sklearn.model_selection import train_test_split # Importing to divide the dataset into two parts - training and test import matplotlib.pyplot as plt # For plotting a graph cancer = load_breast_cancer() # Loading the cancer dataset print(cancer.target_names) # Print the target names into which the data is classified. In this case two - malignant and benign print(cancer.DESCR) # Print the description of the cancer dataset # Dividing the data # set into two parts - One is the training set to train the algorithm on and the second the testing set x_train, x_test, y_train, y_test = train_test_split(cancer.data, cancer.target,stratify=cancer.target, random_state=66) training_accuracy = [] # Store the accuracy values of all the training data test_accuracy = [] # Store the accuracy values of all the test data # Running a For loop to calcualte accuracy values of number of nearest neighbours ranging from 1 to 11 neighbors_settings = range(1,11) for n_neighbors in neighbors_settings: clf = KNeighborsClassifier(n_neighbors=n_neighbors) clf.fit(x_train,y_train) training_accuracy.append(clf.score(x_train,y_train)) test_accuracy.append(clf.score(x_test,y_test)) # Plotting the accuracies of both the training as well as the testing data to get the optimal accuracy for training set plt.plot(neighbors_settings, training_accuracy, label="Accuracy of the training set") plt.plot(neighbors_settings, test_accuracy, label="Accuracy of the test set") plt.ylabel('Accuracy') plt.xlabel('Number of Neighbours') plt.show()
32c49272ff07c0a0fe55537dac145d63093ff14b
canadiyaman/python-studies
/listsquare.py
460
3.953125
4
def square(the_list): return [x*x for x in the_list] def merge(x, y): if len(x) == 0: return y elif len(y) == 0: return x elif x[-1] <= y[0]: return [x[-1]] + merge(x[:-1], y) else: return [y[0]] + merge(x, y[1:]) the_list = [-8, -5, -3, -1, 4, 7, 12, 24] half_the_list = int(len(the_list)/2) list1 = square(the_list[:half_the_list]) list2 = square(the_list[half_the_list:]) print(merge(list1, list2))
f072351c49d70331e94af6c7557a3cf8e4423380
kvn-lee/RecipeTransformer
/main.py
2,176
3.640625
4
import rparser import recipetranslator import copy prompt = ("Please enter a number for how to change your recipe:" "\n1: To vegetarian" "\n2. From vegetarian" "\n3: To healthy" "\n4: From healthy" "\n5: To Vegan" "\n6: From Vegan" "\n7: To Mexican" "\n8: From Mexican\n") def main(): url = "" while "allrecipes.com/recipe" not in url: url = input("\nPlease enter a valid recipe URL from allrecipes.com: ") # RETURN ORIGINAL RECIPE # recipe = rparser.parse_recipe(url) output_recipe(recipe) # ASK HOW TO CHANGE RECIPE # transformation = 0 toTransform = True while toTransform: while int(transformation) not in range(1, 9): transformation = input(prompt) # TRANSFORM RECIPE # newrecipe = recipetranslator.maintransformation(copy.deepcopy(recipe), int(transformation)) # OUTPUT THE NEW RECIPE POST TRANSFORMATION # output_recipe(newrecipe) # RESET TRANSFORMATION TO 0 TO REPEAT PROCESS # transformation = 0 toStop = 0 while int(toStop) not in range(1, 4): toStop = input('\nRecipe transformed! Would you like to try again? Please enter a number' '\n1: Transform the same recipe' '\n2: Transform a different recipe' '\n3: Exit\n') if int(toStop) == 2: url="" toTransform = False elif int(toStop) == 3: toTransform = False def output_recipe(rec): detailed_recipe = "" while detailed_recipe not in ("y", "n", "Y", "N"): detailed_recipe = input("View detailed recipe? (y/n): ") if detailed_recipe is "y" or detailed_recipe is "Y": detailed = True elif detailed_recipe is "n" or detailed_recipe is "N": detailed = False if detailed: rec.print_recipe(detailed=True) else: rec.print_recipe() if __name__ == '__main__': main()
429a91d928bbf33f9ddf0c5daea25a8777d65084
anutha13/Python
/demo.py
1,058
4.21875
4
from time import sleep from threading import Thread class Hello(Thread): def run(self): for i in range(5): print("hello") sleep(1) class Hi(Thread): def run(self): for i in range(5): print("Hi") t1=Hello() t2=Hi() t1.start() #this is a different thread t1 sleep(0.2) t2.start() #this is another thread t2 t1.join() t2.join() #main thread will not execute until both t1 and t2 will join print("bye") #this whole program is using a main thread #but to run on different core or different threads not in Main thread #we need Thread as a parent of the Hi and Hello class # multi-threading # threading is light-weight process and that process is divided into small parts # that part is called thread # can i execute 2 function on different cores at the same time #zip() zips two list with each other list=['anu','thakur','king] num=['ab','cd','ef'] zipped=zip(list,num) for (a,b) in zipped: print(a,b)
5a0140339b66c37c3d1f7056f8a2b8520630d39c
JasleenUT/Encryption
/ElGamal/ElGamal_Alice.py
1,669
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 23 20:07:58 2018 @author: jasleenarora """ # Read the values from intermediate file with open('intermediate.txt','r') as f: content = f.readlines() p = int(content[0]) g = int(content[1]) a = int(content[2]) c1 = int(content[3]) c2 = int(content[4]) ###fast powered def fastPower(g, A, N): a=g b=1 while A>0: if A%2==1: b=(b*a)%N a=(a*a)%N A=A//2 return b # This script converts an integer to binary def int2bin(integer): if integer == 0: return('00000000') binString = '' while integer: if integer % 2 == 1: binString = '1' + binString else: binString = '0' + binString integer //=2 while len(binString)%8 != 0: binString = '0' + binString return binString # Converts binary to integer def bin2int(binary): return int(binary,2) # this tells the function that the input 'binary' is in base 2 and it converts it to base 10 # This will convert integer to character def int2msg(integer): return bin2msg2(int2bin(integer)) # Write the conversion from binary to character in one line def bin2msg2(binary): return ''.join(chr(int(binary[i*8:i*8+8],2)) for i in range(len(binary)//8)) def ElGamal(p,g,a,c1,c2): # Step1: calculate ((c1)^a)^p-2 temp = fastPower(c1,a,p) s1 = fastPower(temp,p-2,p) # Step2: Multiply this by c2 s2 = (s1*c2)%p # Step3: Convert this to character msg = int2msg(s2) print("The decoded message is: ",msg) ElGamal(p,g,a,c1,c2)
f321b8da5edff31f1c279f8cbde5e92bd78b77f1
PranavTripathi101/AdventOfCode
/Advent of Code/Day3/day3.py
2,073
3.9375
4
def readData(): with open('input.txt') as f: wire1 = f.readline().split(',') wire2 = f.readline().split(',') wire1[-1] = wire1[-1][:-1] wire2[-1] = wire2[-1][:-1] return wire1, wire2 def populatePath(wire): start = [0,0] stepsDict = dict() steps = 1 for step in wire: direction = dirMappings[step[0]] moves = int(step[1:]) for i in range(moves): start[0] += direction[0] start[1] += direction[1] stepsDict[tuple(start)] = steps steps += 1 return stepsDict ''' Have the paths for each wire. Need to find all points of intersection and calculate Manhattan distance from each. Slightly brute force. Build set of (x,y) points for each wire. Compute intersection of sets. For each point in intersection, get manhattan distance from start. Keep track of minimum. Might be too big for memory. Lets see Ok, it worked. For Part2, instead of minimizing the Manhattan distance, we want to minimize the sum of steps each wire takes to get to an intersection point. We return the intersection with the lowest such sum. So in each simulation, we now keep a step counter which increments after each step in any direction. Obviously we cannot add to this to our tuple otherwise the intersection set would be empty unless both wires reached the same point after the same # of steps. (This is because it will hash all fields of the tuple) Therefore, maybe build a dictionary for each position as well. We hash on the position, and the value will be the # of steps to get there. For each intersection point, we use each wire's hash table to get the # of steps it took to get there. Then we minimize the sum. ''' wire1, wire2 = readData() dirMappings = {'U':(0,1), 'D':(0,-1), 'R':(1,0), 'L':(-1,0)} wire1Dict = populatePath(wire1) wire2Dict = populatePath(wire2) minSum = 2e9 for point in wire1Dict: if point not in wire2Dict: continue stepsSum = wire1Dict[point] + wire2Dict[point] minSum = min(minSum, stepsSum) print(minSum)
e79c965a46a710f49d4888c4113ea2fbbbedf9d8
HasanKaval/Assignment_6_Python
/Prime_Numbers_2.py
372
3.96875
4
#Print the prime numbers which are between 1 to entered limit number (n). n = int(input("Please enter a number : ")) numbers = list(range(1,n+1)) prime_list = [] for j in numbers : count = 0 for i in range(1, n+1) : if not (j % i) : count += 1 if not((j == 0) or (j == 1) or (count >= 3)) : prime_list.append(j) print(prime_list)
186a3995a21c3821bb3bfcb6598cc40f40283497
divijwadhawan/DisasterResponsePipeline
/data/process_data.py
3,779
3.8125
4
import sys import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): '''This function is used to load messages and categories files from their filepath to dataframes''' # load messages dataset messages = pd.read_csv("disaster_messages.csv") # load categories dataset categories = pd.read_csv("disaster_categories.csv") #merging both datasets into a single dataframe df = pd.merge(messages,categories) df.head() return df def clean_data(df): '''this funtion inputs merged dataframe of messages and categories and does the following steps : 1. converts merged column of 36 categories into 36 different columns 2. cleans data to extract value for each row and column 3. drops duplicate rows in the dataframe df''' #Spliting categories column into 36 individual columns and saving it as a seprate dataframe df_categories = df['categories'].str.split(';',expand=True) #categories is a list of column names with a not needed character at the end eg: 'related-1' , 'request-0' and so on #this character needs cleaning df_categories.columns = df_categories.iloc[0] #a new list of cleaned column names clean_category_colnames = [] #adding cleaned column name to empty list for column in df_categories: clean_category_colnames.append(column[0:-2]) #replacing columns of categories with cleaned values df_categories.columns = clean_category_colnames #We have value of each column in the last character of the string that we need to extract and convert it to numeric for column in df_categories: # set each value to be the last character of the string df_categories[column] = df_categories[column].str[-1:] #convert column from string to numeric df_categories[column] = df_categories[column].astype(int) #dropping original categories column which we already split and saved into a new dataframe df_categories df = df.drop(columns=['categories']) #merging original dataframe after dropping 'categories' column with the dataframe df_categories which has split 36 values #axis=1 means we concat it column wise df = pd.concat([df, df_categories], axis=1) df.head() #dropping rows where column related value is 2 as this seems a wrong value df = df[df.related != 2] #droping duplicate rows from the dataframe df = df.drop_duplicates() return df def save_data(df, database_filename): '''Saves df into database_filename as an sqlite file''' engine = create_engine('sqlite:///'+database_filename) df.to_sql('DisasterTable', engine, index=False, if_exists='replace') def main(): if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving data...\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to database!') else: print('Please provide the filepaths of the messages and categories '\ 'datasets as the first and second argument respectively, as '\ 'well as the filepath of the database to save the cleaned data '\ 'to as the third argument. \n\nExample: python process_data.py '\ 'disaster_messages.csv disaster_categories.csv '\ 'DisasterResponse.db') if __name__ == '__main__': main()
f3057ca79beff59db0ce1a06a31d3627fe0e67ba
sagarnaikele/Python_HandsOn
/Basic/LogicalPrograms/ArmstrongOfAny.py
633
4.03125
4
def IsArmstrong(number): #123 ----> #1*1*1 + 2*2*2 + 3*3*3 cloneNumber=number sum=0 power=findPower(cloneNumber) while cloneNumber>0: nextSingleDigit=int(cloneNumber%10) tempAlloc=pow(nextSingleDigit,power) sum=sum+tempAlloc cloneNumber=int(cloneNumber/10) return sum == number def findPower(number): power=0 while number>0: power=power+1 number=int(number/10) return power #Calling and execution maxLimit = int(input("Find all armstrong numbers from 1 to ? ")) for num in range(1, maxLimit): if IsArmstrong(num): print(num)
f73ae633877ee78afdbfe8db012f451dfeb4059e
pk026/competative_pragramming
/find_missing_and_repeating.py
348
3.96875
4
def return_missing_and_repeating(array, size): for i in range(size): if array[abs(array[i])-1] > 0: array[abs(array[i])-1] = -array[abs(array[i])-1] else: print "The repeating element is", abs(array[i]) for i in range(size): if array[i] > 0: print "and the missing element is",i+1
2a0c0bb0c9f718791d2742a1e43bfd097c8c5196
maiconarantes/Atividade2
/questao2.py
805
4.28125
4
#_*_coding:latin1_*_ #Elaborar um programa que lê 3 valores a,b,c e verifica se eles formam #ou não um triângulo. Supor que os valores lidos são inteiros e positivos. Caso #os valores formem um triângulo, calcular e escrever a área deste triângulo. Se #não formam triângulo escrever os valores lidos. (Se a &gt; b + c não formam #triângulo algum, se a é o maior). print("Informe um valor para a!") a = float(input()) print("Informe um valor para b!") b = float(input()) print("Informe um valor para c!") c = float(input()) if a < b + c and b < a + c and c < a + b: print("Os Valores acima podem formar um triangulo") area = b * a / 2 print("A area do Triangulo e", area) else: print("Os valores acima não pode formar um triangulo") print(a,b,c)
45760f48c550c564bcb6d242b2713c9e004490e1
am282000/PythonTutorials
/main(0).py
1,041
3.75
4
#import cv2 #we can import it by cv2 name # import math # inbuild module print("Hello World\n") print("5+8") print(5+8) # print (math.gcd(3,6)) # if(age<18): # print("I am inside if ...") # python main.py to runpython script in terminal # install extension code runner for vs code # Python is all about indentation # This hash is called Pound symbol ''' This is a multiline comment ''' # pip install opencv-python #image processing ka package hai a=34 b="maddy" c=45.3 d=3 print(a+3) print(a+c) print(a+d) print(a-d) print(a*d) print(a/d) #rules for creating variable # 1. Start wth letter or an underscore # 2. Can't start with a Number # 3. Only contain alpha numeric char no special symbols at all # 4. variable names are case sensitive typeA =type(a) typeB =type(b) print(typeA) print(typeB) print(type(c)) # Type def e="12" e=int(e) f=777 f=float(f) print(e+f) #Error we cant add sting and int value directly like this x=str(99999) y=int("34") print(x,y) # Strings
d96e0003f97a041987cb123654bbd02b12c62220
ChristianChang97/Computational-Thinking
/ex1.py
283
4.15625
4
print("1TDS - FIAP - Primeiro Programa Python") numero = int (input("Digite um número: ")) #campo para digitação do número quadrado = numero*numero #cálculo do quadrado do número print("O quadrado do número {} é {}".format(numero, quadrado)) #impressão do resultado
ca4309338b560bd5e438c35e18466993cff041e6
DavidCouronne/LaTeXConvertHTML
/testregex.py
2,850
4.03125
4
""" Here is a simple python program showing how to use regular expressions to write a paren-matching recursive parser. This parser recognises items enclosed by parens, brackets, braces and <> symbols, but is adaptable to any set of open/close patterns. This is where the re package greatly assists in parsing. """ import re # The pattern below recognises a sequence consisting of: # 1. Any characters not in the set of open/close strings. # 2. One of the open/close strings. # 3. The remainder of the string. # # There is no reason the opening pattern can't be the # same as the closing pattern, so quoted strings can # be included. However quotes are not ignored inside # quotes. More logic is needed for that.... pat = re.compile(""" ( .*? ) ( \( | \) | \[ | \] | \{ | \} | \< | \> | \' | \" | BEGIN | END | $ ) ( .* ) """, re.X) # The keys to the dictionary below are the opening strings, # and the values are the corresponding closing strings. # For example "(" is an opening string and ")" is its # closing string. matching = {"(": ")", "[": "]", "{": "}", "<": ">", '"': '"', "'": "'", "BEGIN": "END"} # The procedure below matches string s and returns a # recursive list matching the nesting of the open/close # patterns in s. def matchnested(s, term=""): lst = [] while True: m = pat.match(s) if m.group(1) != "": lst.append(m.group(1)) if m.group(2) == term: return lst, m.group(3) if m.group(2) in matching: item, s = matchnested(m.group(3), matching[m.group(2)]) lst.append(m.group(2)) lst.append(item) lst.append(matching[m.group(2)]) else: raise ValueError("After <<%s %s>> expected %s not %s" % (lst, s, term, m.group(2))) # Unit test. if __name__ == "__main__": for s in ("simple string", """ "double quote" """, """ 'single quote' """, "one'two'three'four'five'six'seven", "one(two(three(four)five)six)seven", "one(two(three)four)five(six(seven)eight)nine", "one(two)three[four]five{six}seven<eight>nine", "one(two[three{four<five>six}seven]eight)nine", "oneBEGINtwo(threeBEGINfourENDfive)sixENDseven", r"""\head{\textbf{A. P{}. M. E. P{}.}} \lhead{\small Baccalauréat S} \lfoot{\small{Pondichéry}} \rfoot{\small{4 mai 2018}} \pagestyle{fancy} \thispagestyle{empty}""", "ERROR testing ((( mismatched ))] parens"): print("\ninput", s) try: lst, s = matchnested(s) print("output", lst) except ValueError as e: print(str(e)) print("done")
31437cfb86cb0bdd9ce378ba6aacd44a48c1a3dd
opember44/Engineering_4_Notebook
/Python/calculator.py
1,426
4.34375
4
# Python Program 1 - Calculator # Written by Olivia Pemberton def doMath (num1, num2, operation): # defines do math function # program will need yo to enter 2 numbers to do operation if operation == 1: x = round((num1 + num2), 2) return str(x) if operation == 2: x = round((num1 - num2), 2) return str(x) if operation == 3: x = round((num1 * num2), 2) return str(x) if operation == 4: x = round((num1 / num2), 2) return str(x) if operation == 5: x = round((num1 % num2), 2) return str(x) # this makes the operation add, subtract, multiply, divide, and find # the remainder of the two numbers entered go = "y" # this sets the variable for the whileloop print("After calculations is complete, press Enter to go again") print("Press x then Enter to quit program") # prints the instructions the user needs to work the calculator while go == "y": # starts the calculator a = float(input("Enter 1st Number: ")) b = float(input("Enter 2nd Number: ")) # the user is told to put in the two numbers print("Sum:\t\t" + doMath(a,b,1)) print("Difference:\t" + doMath(a,b,2)) print("Product:\t" + doMath(a,b,3)) print("Quotient:\t" + doMath(a,b,4)) print("Modulo:\t\t" + doMath(a,b,5)) # the program run and finds all the answers to the math functions key = input(" ") # the program can be run again if the user puts in more numbers if key == "x": # the user can end the program by pressing x then enter break
f147bf186c8219367f3824c65cbaefb0b7e0802b
PatelMohneesh/Deep-Learning-Excersise
/Excercise 1/ecbm/features/pca.py
1,070
3.65625
4
import time import numpy as np from numpy import linalg as la def pca_naive(X, K): """ PCA -- naive version Inputs: - X: (float) A numpy array of shape (N, D) where N is the number of samples, D is the number of features - K: (int) indicates the number of features you are going to keep after dimensionality reduction Returns a tuple of: - P: (float) A numpy array of shape (K, D), representing the top K principal components - T: (float) A numpy vector of length K, showing the score of each component vector """ ############################################### #TODO: Implement PCA by extracting eigenvector# ############################################### arr = np.array(X) cov = np.corrcoef(arr, rowvar=0) eig_val, eig_vec = np.linalg.eig(cov) P = eig_vec[:,:K].T T = eig_val[:K] ############################################### # End of your code # ############################################### return (P, T)
a1ce876079788f5c5a681731dc4025c87ba372a6
jishnupramod/expert-python
/ep5_generators.py
662
3.578125
4
# class Generator: # def __init__(self, n): # self.n = n # self.last = 0 # # def __next__(self): # return self.next() # # def next(self): # if(self.last == self.n): # raise StopIteration() # # rv = self.last ** 2 # self.last += 1 # return rv # # gen = Generator(100) # # while(True): # try: # print(next(gen)) # except StopIteration: # break import sys def generator(n): for i in range(n): yield i**2 g = generator(10000) x = [i**2 for i in range(10000)] print("Size of list:", sys.getsizeof(x)) print("Size of generator:", sys.getsizeof(g))
d2af0cb7f8c7fd64e827310cbf31216406f28efb
lmrz/py
/ex15.py
399
3.953125
4
#引入库 from sys import argv #定义库 script, filename = argv #将文件内容赋改txt对象 txt = open(filename) #输出文件名/文件内容 print(f"Here's you file {filename}:") print(txt.read()) #输入文件,“>" 开头 print("Type the filename again:") file_again = input("> ") #将输入的内容赋给txt_again txt_again= open(file_again) #输出内容 print(txt_again.read())
bb5aa2c8fc80036459a6883cd95cd153f833eba7
MarceloSombra/Projeto_3
/Projeto_3_Codigo_Base.py
8,430
3.53125
4
class Loja(object): def __init__(self, estoque, caixa): self.estoque = estoque self.caixa = caixa self.aluguelHora = 5 self.aluguelDia = 25 self.aluguelSemana = 100 self.aluguelFamilia = 0 def receberPedido(self, tipoAluguel, qtdeBike, periodo): self.estoque -= qtdeBike self.qtdeBike = qtdeBike self.tipoAluguel = tipoAluguel # tipoAluguel = H - hora, D - dia, S - semana self.periodo = periodo # Horas, Dias ou Semanas try: if qtdeBike < 0: raise ValueError("Quantidade inválida.") if qtdeBike > self.estoque: raise SystemError("Quantidade inválida.") if qtdeBike >= 3 <= 5: if tipoAluguel == "H" or tipoAluguel == "h": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bikes por {periodo} hora(s). Você ganhou um desconto de 30% por ter escolhido nosso plano Familia.") return ((qtdeBike*(self.aluguelHora*periodo))*0.70) if tipoAluguel == "D" or tipoAluguel == "d": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bikes por {periodo} dia(s). Você ganhou um desconto de 30% por ter escolhido nosso plano Familia.") return ((qtdeBike*(self.aluguelDia*periodo))*0.70) if tipoAluguel == "S" or tipoAluguel == "s": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bikes por {periodo} semana(s). Você ganhou um desconto de 30% por ter escolhido nosso plano Familia.") return ((qtdeBike*(self.aluguelSemana*periodo))*0.70) if qtdeBike < 3: if tipoAluguel == "H" or tipoAluguel == "h": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bike(s) do tipo {self.tipoAluguel} pelo periodo de {periodo} hora(s).") return (qtdeBike*(self.aluguelHora*periodo)) if self.tipoAluguel == "D" or tipoAluguel == "d": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bike(s) do tipo {self.tipoAluguel} pelo periodo de {periodo} dia(s).") return (qtdeBike*(self.aluguelDia*periodo)) if self.tipoAluguel == "S" or tipoAluguel == "s": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bike(s) do tipo {self.tipoAluguel} pelo periodo de {periodo} semana(s).") return (qtdeBike*(self.aluguelSemana*periodo)) else: print("Tipo de aluguel, quantidade ou período inválido.") except ValueError: print("Bicicletaria - Quantidade de bike inválida. Deve-se escolher uma quantidade de bikes para aluguel maior que zero.") return 0 except SystemError: print(f"Bicicletaria - Quantidade de bikes indisponivel em estoque. Escolha uma quantidade de acordo com a disponibilidade {self.estoque}.") return 0 except: print(f"Bicicletaria - Pedido não efetuado. Quantidade de bikes disponiveis para locação: {self.estoque}.") def receberPagamento(self, valorConta, valorPgto): try: if valorPgto <= 0 or valorConta <= 0: raise ValueError("Valor inválido") if valorConta == valorPgto: self.caixa += valorPgto print(f"Bicicletaria - O valor da conta é R$ {valorConta}. O valor pago foi R$ {valorPgto}. Obrigado e volte sempre!") return (valorConta - valorPgto) if valorConta < valorPgto: self.caixa += valorConta print(f"Bicicletaria - O valor da conta é R$ {valorConta}. O valor pago foi R$ {valorPgto}. O valor do troco é R$ {valorPgto - valorConta}.") return (valorPgto - valorConta) if valorPgto < valorConta: self.caixa += valorPgto print(f"Bicicletaria - O valor da conta é R$ {valorConta}. O valor pago foi R$ {valorPgto}. Portanto, ainda há um saldo de R$ {valorConta - valorPgto} em aberto.") return (valorConta - valorPgto) print("Extrato de Locação de Bicicleta") print("Tipo Plano\tQtdeBike\tDuração da Locação\t") except ValueError: print(f"Valor inválido. Valor da Conta: R$ {valorConta}. Valor Pago: R$ {valorPgto}.") return valorConta except: print("Aconteceu alguma coisa. Favor realizar o pagamento. ") return valorConta class Cliente(object): def __init__(self, nome, saldoContaCorrente): self.nome = nome self.saldoContaCorrente = saldoContaCorrente self.contaLocacao = 0.0 def alugarBike(self, qtdeBike, objetoBicicletaria): try: if qtdeBike <= 0: raise ValueError("Quantidade inválida. Por favor escolha a quantidade de Bike(s) que deseja alugar. ") if not isinstance(objetoBicicletaria, Loja): raise SystemError("Não recebeu uma Bicicletaria ") self.contaLocacao += objetoBicicletaria.receberPedido(qtdeBike, self.tipoAluguel, self.periodo) except ValueError: print(f"Cliente {self.nome}. Impossivel realizar o pedido pois a quantidade escolhida {qtdeBike} é inválida.") return 0 except SystemError: print(f"Cliente {self.nome}. Impossivel realizar o pedido pois a bicicletaria não é válida.") return 0 except: print(f"Cliente - {self.nome}. Pedido não efetuado. Conta {self.contaLocacao}") return 0 def pagarConta(self, valorPgto, objetoBicicletaria): try: if valorPgto <= 0: raise ValueError("Valor inválido") if valorPgto > self.saldoContaCorrente: raise ArithmeticError("Valor da conta superior ao saldo disponivel em conta corrente para pagamento. ") if not isinstance(objetoBicicletaria, Loja): raise SystemError("Não recebeu uma Bicicletaria ") self.saldoContaCorrente -= valorPgto divida = objetoBicicletaria.receberPagamento(self.contaLocacao, valorPgto) if divida == 0: self.contaLocacao = 0 if divida > 0: self.contaLocacao = divida else: self.saldoContaCorrente -= divida self.contaLocacao = 0 print(f"Cliente{self.nome} - Pagamento de R$ {valorPgto} da conta de R$ {self.contaLocacao} feito. Conta: R$ {self.contaLocacao}. Saldo conta corrente: R$ {self.saldoContaCorrente}") except ValueError: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado. {valorPgto} deve ser compativel com o valor da conta {self.contaLocacao} ") return 0 except ArithmeticError: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado. {valorPgto} superior ao saldo da conta corrente {self.saldoContaCorrente} ") return 0 except SystemError: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado pois a bicicletaria não é válida. Valor pagamento {valorPgto}. Saldo em conta {self.contaLocacao}. ") return 0 except: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado. Conta {self.contaLocacao}, saldo conta corrente {self.saldoContaCorrente} ") return 0
383cc99de44752de88a43ed0385a2dd2832b2ae3
hanamura-yuki/test
/app/test.py
109
3.515625
4
#!python3 from matplotlib import pyplot as plt plt.plot(range(100), [x ** 2 for x in range(100)]) plt.show()
1916dfb9e0fe6e071f41364a68eade456d4310aa
walterkwon/CWK-Memento-Python
/ep018.py
2,397
4.40625
4
#!/usr/bin/env python3 # Wankyu Choi - Creative Works of Knowledge 2019 # https://www.youtube.com/wankyuchoi # # # Episode 018 - Data Types: Tuple & Set Types def main(): """Entry Point""" print("=" * 10, "Tuple", "=" * 10) a_list = ['wankyu', 'james', 'fred', 'tom', 'harry'] a_tuple = ('wankyu', 'james', 'fred', 'tom', 'harry') print(f'a_list is a {type(a_list)}: {a_list}') print(f'a_tuple a {type(a_tuple)}: {a_tuple}') a_list[0] = 'ben' print(f'a_list is a {type(a_list)}: {a_list}') # tuples are immutable # a_tuple[0] = 'ben' # a_tuple.append('ben') # print(f'a_tuple a {type(a_tuple)}: {a_tuple}') a = ('wankyu') b = ('choi') print(f'{a} {b}') b, a = a, b print(f'{a} {b}') args = (3,'key',True) a, b, c = args print(f'args: 1. {a}, 2. {b}, 3. {c}') print("=" * 10, "Pseudo Tuple Comprehension", "=" * 10) odd_numbers = (x for x in range(10) if x % 2) print(tuple(odd_numbers)) print("=" * 10, "Set", "=" * 10) a_set = {'wankyu', 'james', 'fred', 'tom', 'harry'} another_set = set('wankyu james fred tom harry') print(f'a_set a {type(a_set)}: {a_set}') print(f'another_set a {type(another_set)}: {another_set}') print(f'another_set sorted: {sorted(another_set)}') list_set = set(dir(list)) tuple_set = set(dir(tuple)) print(sorted(list_set)) print(sorted(tuple_set)) # Union: 합집합 A | B print(f'Union: {sorted(list_set | tuple_set)}') print('Union:', sorted(list_set.union(tuple_set))) # Intersection: 교집합 A & B print(f'Intersection: {sorted(list_set & tuple_set)}') print('Intersection:', sorted(list_set.intersection(tuple_set))) # Difference: 차집합 A - B print(f'Difference: {sorted(list_set - tuple_set)}') print('Difference:', sorted(list_set.difference(tuple_set))) # Complement: 여집합(보집합) (A | B) - A print(f'Complement: {sorted((list_set | tuple_set) - list_set)}') # Symmetric Difference: 대칭 차집합 (A | B) - (A & B) print(f'Symmetric Difference:{sorted(list_set ^ tuple_set)}') print(f'Symmetric Difference: {sorted((list_set | tuple_set) - (list_set & tuple_set))}') print("=" * 10, "Set Comprehension", "=" * 10) odd_numbers = {x for x in range(10) if x % 2} print(odd_numbers) if __name__ == '__main__': main()
edcf0635ccfabf8bf6462f59199338689ec9365c
walterkwon/CWK-Memento-Python
/ep016.py
3,712
4.1875
4
#!/usr/bin/env python3 # Wankyu Choi - Creative Works of Knowledge 2019 # https://www.youtube.com/wankyuchoi # # # Episode 016 - Data Types: List Type from statistics import mean def main(): """Entry Point""" print("=" * 10, "String Sequence vs. List", "=" * 10) name_string = 'wankyu' name_list = ['w', 'a', 'n', 'k', 'y', 'u'] print(name_string[0]) print(name_list[0]) # strings are immutable: the following would cause an error # name_string[0] = 'W' # lists are mutable name_list[0] = 'W' print(name_list) print("=" * 10, "Nested list", "=" * 10) jumble = ['a', 1, 0.1, [3, 6]] print(jumble[3][1]) print("=" * 10, "Indexing", "=" * 10) a_list = [0, 1, 2, 3, 4, 5] print(a_list) print("The first element: {}.".format(a_list[0])) print("The last element: {}.".format(a_list[-1])) print("The second element: {}.".format(a_list[1])) print("The second to last element: {}.".format(a_list[-2])) print("=" * 10, "Slicing", "=" * 10) print(a_list) print("From second to fourth elements: {}.".format(a_list[1:4])) print("From second to last elements: {}.".format(a_list[1:])) print("From first to third to last elements: {}.".format(a_list[:-2])) print("=" * 10, "Shallow vs. Deep Copy(By Reference vs. By Value", "=" * 10) another_list_shallow_copied = a_list another_list_deep_copied = a_list[:] print("-" * 5, "Before changing an element in the original list...", "-" * 5) print(another_list_shallow_copied) print(another_list_deep_copied) print("-" * 5, "After changing an element in the original list...", "-" * 5) a_list[0] = 'messed up' print(another_list_shallow_copied) print(another_list_deep_copied) print("=" * 10, "Traversing", "=" * 10) for i in another_list_deep_copied: print(i*i) print("=" * 10, "List Comprehension", "=" * 10) odd_numbers = [x for x in another_list_deep_copied if x % 2] # x % 2 == 1 even_numbers = [x for x in another_list_deep_copied if not x % 2] # x % 2 == 0 print("Odd numbers in the list: {}".format(odd_numbers)) print("Even numbers in the list: {}".format(even_numbers)) print("=" * 10, "List Operations", "=" * 10) list_a = [0, 1, 2] list_b = [3, 4, 5] print("Adding lists {} and {}: {}".format(list_a, list_b, list_a + list_b)) print("Multiplying a list {} by {}: {}".format(list_a, 3, list_a * 3)) print("=" * 10, "Useful List Methods", "=" * 10) a_list = list(range(6)) a_list.append(6) print(a_list) a_list.extend(a_list) print(a_list) unsorted_names = ['wankyu', 'james', 'brown', 'fred'] unsorted_names.sort() print(unsorted_names) unsorted_names.reverse() print(unsorted_names) # Won't work sorted_names = unsorted_names.sort() print(sorted_names) big_integers = [1123, 5232, 345, 123, 233, 253, 56344354, 67324] print("The sum of {0}: {1:,}".format(big_integers, sum(big_integers))) print("The mean of {0}: {1:,}".format(big_integers, mean(big_integers))) print("After popping the last element {}: {}".format(big_integers.pop(), big_integers)) print("After popping the second element {}: {}".format(big_integers.pop(1), big_integers)) # just trash it del big_integers[1] print(big_integers) big_integers.remove(253) print(big_integers) del big_integers[1:3] print(big_integers) big_integers.insert(1, 5555) print(big_integers) names = ['wankyu', 'james', 'brown', 'wankyu', 'fred', 'wankyu'] print("{} '{}(s)' found.".format(names.count('wankyu'), 'wankyu')) if __name__ == '__main__': main()
e98d3aa0513d9d63b915fd6b897bd5020059dd5f
mwdoyle-sfu/AI-TicTacToe
/aittt.py
5,261
3.921875
4
""" A program to play tic-tac-toe against an AI which uses pure monte-carlo-tree search (MCTS) """ import random def alternate(activePlayer): if (activePlayer == 2): activePlayer = 1 else: activePlayer = 2 return activePlayer def make_move(player_move, current_player, gameboard): gameboard[player_move] = int(current_player) return gameboard def ai_move(current_player, gameboard): # get legal moves legal_moves = [] for i in range(9): if gameboard[i] == 0: legal_moves.append(i) # create datastructure for winning moves move_win_count = {} for move in legal_moves: move_win_count[move] = 0 # make random play outs for move in legal_moves: for i in range(10000): move_win_count[move] += play_out(move, current_player, gameboard) # find and make chosen move move_choice = legal_moves[0] choiceWinCount = move_win_count[move_choice] for win in move_win_count: if move_win_count[win] >= choiceWinCount: move_choice = win choiceWinCount = move_win_count[win] gameboard = make_move(int(move_choice), current_player, gameboard) print("AI move:", move_choice) return gameboard def play_out(move, current_player, gameboard): # copy the gameboard gameboard_copy = [0, 0, 0, 0, 0, 0, 0, 0, 0] gameboard_copy = gameboard.copy() # play the game out gameboard_copy = make_move(move, current_player, gameboard_copy) while (game_active(gameboard_copy)): current_player = alternate(current_player) legal_moves = [] for i in range(9): if gameboard_copy[i] == 0: legal_moves.append(i) random_move = random.randint(0, 8) while (random_move not in legal_moves): random_move = random.randint(0, 8) gameboard_copy = make_move(random_move, current_player, gameboard_copy) # return the winning heuristics if (game_result(gameboard_copy) == 2): return 4 elif (game_result(gameboard_copy) == 1): return -2 else: return 1 def game_active(gameboard): active_game = False if game_result(gameboard) == -1: active_game = True return active_game def game_result(gameboard): # search for winner players = [1, 2] for player in players: # win at 0 3 6 if all(v == player for v in gameboard[::3]): return(player) # win at 1 4 7 if all(v == player for v in gameboard[1::3]): return(player) # win at 2 5 8 if all(v == player for v in gameboard[2::3]): return(player) # win at 0 1 2 if all(v == player for v in gameboard[:3:]): return(player) # win at 3 4 5 if all(v == player for v in gameboard[3:6:]): return(player) # win at 6 7 8 if all(v == player for v in gameboard[6::]): return(player) # win at 0 4 8 if all(v == player for v in gameboard[::4]): return(player) # win at 2 4 6 if all(v == player for v in gameboard[2:8:2]): return(player) # draw if all(v != 0 for v in gameboard): return(0) # game not over return(-1) def print_menu(): print("Choose from the following") print("0 1 2 \n3 4 5\n6 7 8") def print_board(gameboard): board = ['- ', '- ', '- ', '- ', '- ', '- ', '- ', '- ', '- '] display_board = '' for i in range(len(gameboard)): if gameboard[i] == 1: board[i] = 'X ' if gameboard[i] == 2: board[i] = 'O ' if i == 2 or i == 5: display_board += (board[i] + '\n') else: display_board += board[i] print(display_board) def print_game_over(gameboard, in_game): if (game_result(gameboard) == 0): print("** Draw Game **") in_game = False if (game_result(gameboard) == 1): print("** Player Wins **") in_game = False if (game_result(gameboard) == 2): print("** AI Wins **") in_game = False return in_game def play_a_new_game(): print("Starting the game...") gameboard = [0, 0, 0, 0, 0, 0, 0, 0, 0] current_player = 1 in_game = True player_move = '' # ask player or AI first choice = input('Would you like to go first(y/n)? : ') if choice.upper() == 'N': current_player = alternate(current_player) # start game while in_game == True: if current_player == 1: print_menu() player_move = input('Player move: ') gameboard = make_move(int(player_move), current_player, gameboard) print_board(gameboard) else: print("AI is thinking...") gameboard = ai_move(current_player, gameboard) print_board(gameboard) current_player = alternate(current_player) in_game = print_game_over(gameboard, in_game) if __name__ == '__main__': play_a_new_game()
107f1f505647137a18f6346a240b45fa9241ff2b
otakutyrant/Data-Structures-and-Algorithms
/balance_tree.py
794
3.71875
4
class Tree(): def __init__(self, value, left, right): self.value = value self.left = left self.right = right def partial(list_, n): if n == 0: return None else: if (n - 1) % 2 == 1: middle = n // 2 + 1 else: middle = n // 2 return Tree( list_[middle], partial(list_[0: middle], middle), partial(list_[middle + 1:], (n - middle)), ) def tree_to_list(tree): if tree_to_list is None: return [] else: return ( tree_to_list(tree.left) + [tree.val] + tree_to_list(tree.right) ) def balance(tree): list_ = tree_to_list(tree) return partial(list_, len(list_))
b80126ea90b1d7a89adad6d2865a322ed0201dd5
larsbuntemeyer/sandbox
/python/plot_example.py
614
3.640625
4
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt mu, sigma = 0, 1 # mean and standard deviation f = np.random.normal(mu, sigma, 1000) # generate feature-vector with normal distribution # plot the histogram - check the distribution count, bins, ignored = plt.hist(f, 30, normed=True) plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r') plt.xlabel('Values') plt.ylabel('Probability') plt.title('Histogram') plt.text(60, .025, r'$\mu=0,\ \sigma=1$') plt.axis([-0.4, 0.3, 0, 5]) plt.grid(True) plt.show()
37e1f2da3bfed6decb9b04f53de749fe2d403de3
bendog/shecodes_RonakReyhani_shecodes-week-6-task-1
/section.py
2,391
3.640625
4
from question import Question class Section: def __init__(self, sec_title, sec_description, question_list, qualifying_question): self.sec_title = sec_title self.sec_description = sec_description self.qualifying_question = qualifying_question self.question_list = question_list # self.first_question = first_question # @bendog - i've removed first question as it seems to make less sense def ask_qualify_question(self): # @bendog - i moved this method here, because it seemed to make sense to keep it as part of the data object it was using # isqualify = [] if self.qualifying_question: self.qualifying_question.ask_question() # ask if these two will work when ask_question() and get_user_answer() are methods in Question # isqualify.append(self.qualifying_question.get_user_answer()) # @bendog - this might not be doing what you want it to be doing return self.qualifying_question.user_answer # run method for each section def run_section(self): print(f'============================ {self.sec_title} ============================\n') print(f'{self.sec_description}\n') for question in self.question_list: question.ask_question() # question.get_user_answer() # @bendog - this was already being asked in the ask_question() question.print_user_answer() # self.user_answers = question.keep_answers() # @bendog - is this meant to be part of section? # for key, value in self.user_answers.items(): # print(f'your answer for {key} is {value}') # @bendog - since you are storing your answers in the question, you can list over the questions to get answers for question in self.question_list: print(f'your answer for {question.question_text} is [{question.user_answer}] {question.user_answer_text}') print('Print Thank you messgae: Thanks for your time.bala bala bala....') # exit() # how to add exit comand search for this pass # @bendog - using exit() will quit the entire app, you might not want this. # a method (or function) will just end when it runs out of code to process # ALSO be very mindful of your indentation, most of your problems are probably because the methods weren't indented correctly.
87c0c53f6d3d6d82f8528e0bbac329dee0038ddb
natal20-meet/meetyl1201819
/lab7.py
1,228
3.84375
4
from turtle import * import random import turtle import math turtle.tracer(0) class Ball(Turtle): def __init__(self,radius,color,dx,dy): Turtle.__init__(self) self.shape("circle") self.shapesize(radius/10) self.radius = radius self.dx = random.randint(-350,350)/300 self.dy = random.randint(-350,350)/300 self.color(color) def move_ball(self,height,width): old_x = self.xcor() old_y = self.ycor() new_x = old_x + self.dx new_y = old_y + self.dy if new_x >= width or new_x <= -width: self.dx = -self.dx new_x = old_x + self.dx if new_y >= height or new_y <= -height: self.dy = -self.dy new_y = old_y + self.dy self.goto(new_x,new_y) #check_collision(ball1,ball2) ball1 = Ball(20,"Red",1,1) ball2 = Ball(40,"Blue",1,1) def check_collision(ball1,ball2): x2 = ball1.xcor() x1 = ball2.ycor() y2 = ball1.xcor() y1 = ball2.ycor() D = math.sqrt(math.pow((x2-x1),2) + math.pow((y2-y1),2)) if ball1.radius + ball2.radius>=D: return True else: return False while True: ball1.penup() ball1.move_ball(450,450) ball2.penup() ball2.move_ball(450,450) if check_collision(ball1,ball2): print("we have a collision") turtle.update() #turtle.mainloop()
41d7af3fc16aa836fdf68c2edf21cee7cd1353bd
AbhayKumar8093/pythonprogram
/even.py
332
4.09375
4
""" ist method................................. n=int(input("enter the number")) i=1 while(i<=n): if i%2==0: print(i) i = i + 1 """ # 2nd method....of sum of even number...................................... n=int(input("enter the number")) i=2 sum=0 while(i<=n): sum=sum+i i = i + 2 print(sum)
1cc6489406d02438a4dc653ab44bb1b4405c48ab
AbhayKumar8093/pythonprogram
/num.py
200
3.890625
4
"""print("hello world 7" ,end=" ") print("abhay")""" print("enter your number1") num1=input() print("enter your number2") num2=input() num=int(num1)+int(num2) print("sum of two num",num)
5450e10e71bf1590d28bdb09c6fbd21f867b655e
Sahana1269/python-
/xo.py
834
3.875
4
#printing the game tic-tac toe a=["1","2","3","4","5","6","7","8","9"] def printBoard(): print(a[0],"|",a[1],"|",a[2]) print("---------") print(a[3],"|",a[4],"|",a[5]) print("---------") print(a[6],"|",a[7],"|",a[8]) playerOneturn=True while True: printBoard() p=input("select a place :") if(p in a): if(a[int(p)-1]=='X' or [int(p)-1]=='O'): print("place already taken,select other a place") continue else: if playerOneturn: print("player1>>") a[int(p)-1]='X' playerOneturn=not playerOneturn else: print("player2>>") a[int(p)-1]='O' playerOneturn=not playerOneturn for i in(0,3,6): if(a[i]==a[i+1] and a[i]==a[i+2]): print("Game Over") exit() for i in range(3): if(a[i]==a[i+3] and a[i]==a[i+6]): print("Game Over") exit() else: continue
d95b1bfa19fa52013079f7d63f7794d1c6736d84
hectorzaragoza/python
/functions.py
1,985
4.1875
4
#functions allow us to put something into it, does something to it, and gives a different output. #We start with def to define the function, then we name it, VarName() #def function(input1, input2, input3,...): # code # more code # return value #result = functionName(In1, In2, In3,...) #result = value def addOne(x): #this line of code simply gives your function a name and inside the parenthesis, the inputs y = x + 1 #this line of code determines the actual function/manipulation/calculation that you are trying to do. #Line 12 cont. i.e. what you want to do to your inputs and assign that to a new variable which will then be returned return y #this line of code returns the output of your function def addTogether(in1, testin2): inter = in1 + testin2 return inter testValue = 2 #this is going to be the variable we put into our addOne function, whose result is assigned in result result = addOne(testValue) #y = testValue + 1 -> 2+1 -> 3 print(result) secondTwo = addTogether(testValue, result) #secondTwo is a variable that will store the result of inputting testValue #and result into the addTogether function defined in line 16. print(secondTwo) print(addTogether("Hello"," World!")) print(addTogether("Hello",str(1))) #exercise #Write a function that takes two inputs and returns their sum def SumFunction(VarOne, Vartwo): varthree = VarOne + Vartwo return varthree open = 1 close = 2 EndProduct = SumFunction(open, close) print(EndProduct) #Write a function that takes an input and checks how many times the input is divisible by 3 and by 5. It then returns #those two values def aFunction(InputA): DivByThree = int(InputA/3) #You can have multiple things done to an input within a single function and return #multiple results for tall those things as in this example. DivByFive = int(InputA/5) return DivByThree, DivByFive Divisible = aFunction(489) print(Divisible) print(163*3, 97*5) #testing result
a8e03319d3486f64f85634781420ee3e8e29b765
hectorzaragoza/python
/globalVars.py
466
3.859375
4
#global Variables def addOne(): global y,x #this will make the y variable a global variable #x here is defined as a global variable so x in line 9 is able to be imported and used in this function. y = x + 1 #y inside this function is a local variable return y #a variable inside a function is only defined for that function. x = 3 test = addOne() print(test) print(y)#causes error because y is not defined globally, only locally within a function.
872505bf037defde6b3cbd7d20a3113bd7056106
gnavneetg/python-challenge
/ExtraContents/PyParagraph/PyParagraph.py
1,518
3.546875
4
import os import string inputfile = os.path.join("..", "resources","paragraph.txt") with open(inputfile, 'r') as txtfile: readfile = txtfile.read() #sentence count using dot, question mark & exclaimation marks [ ., ? , !] sen_count = readfile.count('.') + readfile.count('?') + readfile.count('!') #List of words paragraph_list = readfile.split(" ") #counts all of the letters in list paragraph for word in paragraph_list: letter_total += len(word) #word count word_count = len(paragraph_list) #Average word length avg_word_length = letter_total/word_count # Calculating words per sentence words_per_sentence = word_count/sen_count #outputfile output_file = os.path.join("..", "resources","paragraph_analysis.txt") # Writing in output file with open(output_file, 'w') as txtfile: txtfile.write('Paragraph Analysis\n-----------------\nApproximate Word Count: ' + str(word_count)+ '\nApproximate Sentence Count: '+ str(sen_count) + '\nAverage Letter Count: ' + str(round(avg_word_length,2)) + '\nAverage Sentence Length: ' + str(words_per_sentence)) # Printing to terminal print('Paragraph Analysis\n-----------------\nApproximate Word Count: ' + str(word_count)+ '\nApproximate Sentence Count: '+ str(sen_count) + '\nAverage Letter Count: ' + str(round(avg_word_length,2)) + '\nAverage Sentence Length: ' + str(words_per_sentence))
fab672eb471ab131a88a39895233624e22634bce
saintjeremy/PyBasics
/samples/polynomial.py
2,783
3.953125
4
# # This module contains operations to manipulate polynomials. # # Need some string services, and some standard system services. import string, sys # # Function to evaluate a polynomial at x. The polynomial is given # as a list of coefficients, from the greatest to the least. It returns # the value of the polynomial at x. def eval(x, poly): '''Evaluate at x the polynomial with coefficients given in poly. The value p(x) is returned.''' sum = 0 while 1: sum = sum + poly[0] # Add the next coef. poly = poly[1:] # Done with that one. if not poly: break # If no more, done entirely. sum = sum * x # Mult by x (each coef gets x right num times) return sum # # Function to read a line containing a list of integers and return # them as a list of integers. If the string conversion fails, it # returns the empty list. The input 'quit' is special. If that is # this input, this value is returned. The input comes from the file # if given, otherwise from standard input. If the prompt is given, it # is printed first. If reading reaches EOF, or the input line quit, # the call throws EOFError. If the conversion fails, it throws # ValueError. def read(prompt = '', file = sys.stdin): '''Read a line of integers and return the list of integers.''' # Read a line if prompt: line = input(prompt) if line == 'quit': raise EOFError('Input quit on attempt to read polynomial.') # Go through each item on the line, converting each one and adding it # to retval. retval = [ ]; for val in str.split(line): retval.append(int(val)) return retval # # Create a string of the polynomial in sort-of-readable form. def srep(p): '''Print the coefficient list as a polynomial.''' # Get the exponent of first coefficient, plus 1. exp = len(p) # Go through the coefs and turn them into terms. retval = '' while p: # Adjust exponent. Done here so continue will run it. exp = exp - 1 # Strip first coefficient coef = p[0] p = p[1:] # If zero, leave it out. if coef == 0: continue # If adding, need a + or -. if retval: if coef >= 0: retval = retval + ' + ' else: coef = -coef retval = retval + ' - ' # Add the coefficient, if needed. if coef != 1 or exp == 0: retval = retval + str(coef) if exp != 0: retval = retval + '*' # Put the x, if we need it. if exp != 0: retval = retval + 'x' if exp != 1: retval = retval + '^' + str(exp) # For zero, say that. if not retval: retval = '0' return retval
c1974345ee64a2206facd6e52514fedf717c89a1
Andreivilla/POO
/ExtrasPython/extra2/main.py
471
3.90625
4
from setor import Setor from produto import Produto def addProduto(): produto = Produto() print("IdProduto: ") produto.setIdProduto(input()) print("Nome: ") produto.setNome(input()) print("Preco: ") produto.setPreco(input()) return produto setor = Setor() setor.setIdSetor(input()) for i in range(3): setor.addProduto(addProduto()) print("\nPrintar lista de produtos\n") for produto in setor.getListaProduto(): print(produto)
1eeea1f0dbaf41d96394c048186e18f45f9593a4
carlos398/curso_profesional_de_python
/decoradores.py
950
3.578125
4
from datetime import date, datetime # def mayusculas(func): # def envoltura(texto): # return func(texto).upper() # return envoltura # @mayusculas # def mensaje(nombre): # return f'{nombre}, recibiste un mensaje' # print(mensaje('cesar')) #ejercicio decoradores: def execution_time(func): def wrapper(*args, **kwargs): #recibe toda la cantidad de argunmentos necesarios de lo contrario no funcionaria initial_time = datetime.now() func(*args, **kwargs) #recibe toda la cantidad de argunmentos necesarios final_time = datetime.now() time_elapsed = final_time - initial_time print('pasaron {time} segundos'.format( time=time_elapsed.total_seconds() )) return wrapper @execution_time def random_func(): for _ in range(1, 100000000): pass @execution_time def suma(a: int, b: int) -> int: return a + b if __name__ == '__main__': suma(5,5)
e6d9d55773b9ff675f22ae2a2c2642b1ab5f0102
codyhui8/Pocket-Cube-Learning-Alg
/RunProgram.py
3,274
3.734375
4
''' Cody Hui 1338250 CSE 415, Spring 2016, University of Washington RunProgram.py Instructor: S. Tanimoto. Implementation of the code transparency functions. ''' import PocketCube def run(): NUM_SIDE = input("Please enter the size of the side. For example, 3 for a 3x3 and 2 for a 2x2. \n>>> ") NUM_COLORS = input("\nPlease enter the number of colors that you want for the cube. There can be 2, 3, or 6 colors.\n" ">>> ") NUM_EPISODES = input("\nPlease enter the number of episodes that you would like to run the program for.\n" "For a 2x2, it is recommended that you do 10,000 and for a 3x3, it is recommended that you do 1,000,000.\n" ">>> ") ACTIONS = input("\nPlease enter the actions to test. The action should be a number between -5 to 5, " "not include +-2, +-3, and 0.\n" "These values should be values separated by a space, for example: 1 4 5 -1 -4 -5\n" ">>> ") ACTIONS = list(ACTIONS.split(" ")) ACTIONS = map(int, ACTIONS) ACTION_POLICY = input("\nPlease enter the action policy method. Enter one of the following:" " epsilon-greedy or epsilon-soft.\n" ">>> ") EPSILON = input("\nPlease enter the epsilon value. This number can be any number between 0 and 1. The default is 0.2.\n" ">>> ") MAX_MOVES = input("\nPlease enter the maximum number of moves that you would like to have for the solution.\n" "The default number is 500.\n" ">>> ") SHOW_STATE = input("\nHow often do you want to show the state and action pairs and their corresponding Q-Values?\n" "These can be any whole numbers. The default number is 50.\n" ">>> ") LOAD_NOLOAD = input("\nPlease specify if you would like to load a known_states file or not.\n" "Enter a Y as a Yes and a N as a No.\n" ">>> ") LOAD_FILE_NAME = '' SAVE_FILE_NAME = '' save_to_file = False load_from_file = False if LOAD_NOLOAD == 'Y': load_from_file = True LOAD_FILE_NAME = input("\nPlease input the file name. For example, 'known_states.csv' without the quotation marks.\n" ">>> ") else: save_value = input("\nPlease specify if you would like to save the known states to a file.\n" "Enter a Y as a Yes and a N as a No.\n" ">>> ") if save_value == 'Y': save_to_file = True SAVE_FILE_NAME = input("\nPlease input the file name. For example, 'known_states.csv' without the quotation marks.\n" ">>> ") cube = PocketCube.PocketCube() cube.init_numside(int(NUM_SIDE)) cube.init_numcolor(int(NUM_COLORS)) cube.init_numepisodes(int(NUM_EPISODES)) cube.init_actions(list(ACTIONS)) cube.init_epsilon(float(EPSILON)) cube.init_action_policy(ACTION_POLICY) cube.init_max_moves(int(MAX_MOVES)) cube.init_show_state(int(SHOW_STATE)) cube.run(load_from_file, save_to_file, LOAD_FILE_NAME, SAVE_FILE_NAME) run()
50386a3dfac4a1d08f2068c22be44411c5a8aa65
mdakram09/NPTEL_Joy_of_Computing_using_Python
/Programming_Assignment_wk-05_01_cab and walk.py
228
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 13 09:15:35 2019 @author: Rajesh D Borate """ a,b1,b2=map(int,(input().split())) cab=(2*a)/b2 walk=(1.414*a)/b1 if walk<cab: print("Walk",end="") else: print("Cab",end="")
90bee1e5f9008daec378fc3ed954ace587186c71
mdakram09/NPTEL_Joy_of_Computing_using_Python
/Programming_Assignment_wk-11_02_String Sort.py
171
3.796875
4
# -*- coding: utf-8 -*- """ Created on Thu May 2 09:32:24 2019 @author: Rajesh D Borate """ items=[x for x in input().split(',')] items.sort() print (','.join(items))
349d2ba0c89dc2d93b98c708d58d07f22017b7c6
jiani556/Deep-Learning
/RNN_LSTM_Seq2Seq_and_Transformers/models/naive/RNN.py
1,854
3.984375
4
import numpy as np import torch import torch.nn as nn class VanillaRNN(nn.Module): """ An implementation of vanilla RNN using Pytorch Linear layers and activations. You will need to complete the class init function, forward function and hidden layer initialization. """ def __init__(self, input_size, hidden_size, output_size): """ Init function for VanillaRNN class Args: input_size (int): the number of features in the inputs. hidden_size (int): the size of the hidden layer output_size (int): the size of the output layer Returns: None """ super(VanillaRNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.ih = nn.Linear(input_size + hidden_size, hidden_size) self.ho = nn.Linear(input_size + hidden_size, output_size) self.act_hidden = nn.Tanh() self.act_output = nn.LogSoftmax(dim=-1) def forward(self, input, hidden): """ The forward function of the Vanilla RNN Args: input (tensor): a batch of data of shape (batch_size, input_size) at one time step hidden (tensor): the hidden value of previous time step of shape (batch_size, hidden_size) Returns: output (tensor): the output tensor of shape (batch_size, output_size) hidden (tensor): the hidden value of current time step of shape (batch_size, hidden_size) """ output = None cat = torch.cat((input, hidden),dim=-1) with torch.no_grad(): h = self.ih(cat) op = self.ho(cat) hidden=self.act_hidden(h) output=self.act_output(op) return output, hidden
ef58048b8b05de8a3239b61c320f601d02da1daa
manjushachava1/PythonEndeavors
/ListLessThanTen.py
498
4.21875
4
# Program 3 # Take a list and print out the numbers less than 5 # Extras: # 1. Write program in one line of code # 2. Ask the user for a number and return a list that contains elements that are smaller than that user number. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] c = [] # Extra 1 for element in a: if element < 5: b.append(element) print(b) # Extra 2 num = int(input("Enter a random number: ")) for element in a: if element < num: c.append(element) print(c)
6db8f9dab648636a7d834ebf8715703b8d755ed2
xinxin3536/leetcode
/35. Search Insert Position.py
333
3.625
4
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: if not nums: return 0 l,r = 0,len(nums)-1 while l <= r: mid = l + ((r-l)>>1) if nums[mid] >= target: r = mid - 1 else : l = mid + 1 return l
cde2aa01051fd03922314d2b7284c25a6e4b0d79
sam-ager/BBC-Game-Of-Life
/Game of Life/Template/GameOfLifeTemplate.py
1,798
3.625
4
from collections import Counter def life(world, new): #Generate new grid for generate in range(new+1): #Add grid for each for each genration display(world, generate) #Display the grid counts = Counter(new for c in world for new in offset(neighbour_cells, c)) world = {c for c in counts if counts[c] == 3 or (counts[c] == 2 and c in world)} neighbour_cells = [(-1, -1), (-1, 0), (-1, 1), #Defines where the neighbour cells should be located ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1)] def offset(cells, delta): (dx, dy) = delta return {(x+dx, y+dy) for (x, y) in cells} def display(world, generate): #Create's the grid print ' Test: {}'.format(generate) #Displays which state of generation test is i.e. Test: 1, Test: 2 Xs, Ys = zip(*world) Xrange = range(min(Xs), max(Xs)+1) #Takes the minimum of input cells to form x axis grid around it for y in range(min(Ys), max(Ys)+1): #Takes the minimum of input cells to form y axis grid around it print ' '.join('O' if (x, y) in world else '.' #Sets live cells as o's and dead cells as .'s for x in Xrange) #blinker = {(1, 0), (1, 1), (1, 2)} #block = {(0, 0), (1, 1), (0, 1), (1, 0)} #toad = {(1, 2), (0, 1), (0, 0), (0, 2), (1, 3), (1, 1)} #glider = {(0, 1), (1, 0), (0, 0), (0, 2), (2, 1)} #world = (block | offset(blinker, (5, 2)) | offset(glider, (15, 5)) | offset(toad, (25, 5)) # | {(18, 2), (19, 2), (20, 2), (21, 2)} | offset(block, (35, 7))) world = {(1, 1), (1, 2), (1, 3), (2,4), (3,4), (4,4)} #Location of live cells (defined by user) life(world, 8) #How many transitions to be visualised
44f57b812456c89c1c6aa61efd7246581fef85c3
jcurtis4207/Code-Examples
/Python/functions.py
350
3.8125
4
def main(): v1,v2 = func1() print(v1) print(v2) print(func2(4,5,6)) # function that returns multiple values def func1(): return 5,6 # function with undetermined number of parameters def func2(*vars): sum = 0 for i in vars: sum = sum + i return sum if __name__ == '__main__': main()
ea6472f204df2a16b7a4de80407d41d7f56d84be
JavaScriptBach/Project-Euler
/010.py
495
3.765625
4
""" The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ def prime_sieve(limit): a = [True] * limit # Initialize the primality list a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: for n in xrange(i*i, limit, i): # Mark factors non-prime a[n] = False return a sieve = prime_sieve(2000000) answer = 0 for num, isprime in enumerate(sieve): if isprime: answer += num print answer
7f66d0d287df330aaad8d58a3d74308a85171942
JavaScriptBach/Project-Euler
/004.py
518
4.125
4
#coding=utf-8 """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(num): string = str(num) for i in range(0, len(string) / 2): if string[i] != string[len(string) - 1 - i]: return False return True num = 0 for i in range(100, 1000): for j in range(100, 1000): if is_palindrome(i * j) and i * j > num: num = i * j print num
0271687d7b9a4ea77ac4b6364d40d7dc4ab38de0
logan-j/Practice
/examples/ProjEuler/Written.py
1,065
3.640625
4
#converts a number input into the written format def written(n): words = ['and', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] out = "" if n / 1000 > 0: out += words[n/1000] + " thousand" n = n % 1000 if n / 100 > 0: if len(out) != 0: out += " " out += words[n/100] + " hundred" n = n % 100 if len(out) > 0: if n != 0: out += " %s " % words[0] if n > 19: out += words[18 + n/10] if n % 10 != 0: out += " %s" % words[n%10] else: if n > 0: out += words[n] return out #counts total letters used to spell out each written representation def main(): total = 0 for x in xrange(1, 1001): temp = written(x).split() for word in temp: total += len(word) print total main()
592e65372e0cbbbbaaaa50e61b16a4546e6301a5
pgiardiniere/notes-WhirlwindTourOfPython
/06-scalarTypes.py
2,782
4.53125
5
### Simple Types in Python :: # --- Python Scalar Types --- # ---------------------------------------------- # Type Example Description # `````````````````````````````````````````````` # int x = 1 integers # float x = 1.0 floating point nums # complex x = 1 + 2j complex nums # bool x = True True/False # str x = 'abc' String: chars//text # NoneType x = None Null values # # ---------------------------------------------- ### Integers (ints) x = 1; print ( type(x) ) # unlike most languages, ints do NOT overflow # they are variable-precision. print ( 2 ** 200 ) # Python ints up-cast to floats when divided print ( 5 / 2 ) # PYTHON 2 ONLY -- difference between 'int' and 'long' ### Floating-Point numbers # can be defined in decimal notation OR exponential x = 0.000005 y = 5e-6 print ( x == y ) x = 1400000.00 y = 1.4e6 print ( x == y ) # as expected, cast to float as follows: float(1) # as usual, floating point comparison is wonky print ( 0.1 + 0.2 == 0.3 ) # yields False # caused by binary > decimal (base-2 > base-10) approximation print( "0.1 = {0:.17f}".format(0.1) ) print( "0.2 = {0:.17f}".format(0.2) ) print( "0.3 = {0:.17f}".format(0.3) ) # specifically, representing a 1/10 digit num requires infinite digits in base-2 # much like 1/3 requires infinite digits in base-10 ### Complex Numbers print ( complex(1, 2) ) # j used instead of i c = 3 + 4j # j is 'keyword' - denotes imag print ( c.real ) print ( c.imag ) print ( c.conjugate() ) # 3 - 4j print ( abs(c) ) # 3^2 + (4j)^2 absolute magnitude ### String Type # String created with EITHER 'single' "double" quotes message = "foobar" response = "doi" # example (useful) string funcs/methods. print ( len(message) ) # 3 print ( message.upper() ) # make all-caps print ( message.lower() ) # all-lowercase print ( message.capitalize() ) # first-cap print ( message + response ) # string concat (NO auto-spacing) print ( message[0] ) # char indexing print ( 5 * response ) # * to mult. concat. ### None Type print ( type(None) ) # None keyword denotes NoneType # commonly used like "void" returns in other langs return_value = print('abc') print ( return_value ) ### Boolean Type result = (4 < 5) print ( result ) print ( type(result) ) print(True, False) # Boolean vals CASE SENSITIVE # construct using bool() print ( bool(42) ) # numeric nonzero is True print ( bool(0) ) # numeric zero is False print ( bool(None) ) # NoneType is False print ( bool("text") ) # norm. string is True print ( bool("") ) # empty string is False print ( bool([1,2]) ) # norm. list is True print ( bool([]) ) # empty list is False
9530462986239856552d3d3d33b9149036182869
osiefat/210-Coursework
/week 3 q1.py
297
4.0625
4
def revs(a): if a=="This is awesome": #1 # the string input a.split() #1 # a = split each word up sen=" ".join(a.split()[::-1]) #1 # join and split the input print(sen) #1 else: #1 print(a) #1 revs("This is awesome") #1 # O(1) big o notation
8466865654ee96b5f63d22a93ce570b1cceb3832
MonkGirl/Python
/code/chapter1/Exercise.py
636
4.03125
4
import math import cmath import turtle from math import sqrt print("Hello, World!") print(2+2) print(1 // 2) # 取整运算 print(1/2) print(1 % 2) # 取余运算 print(10 % (-3)) print(2**3) print(-2**3) print(math.floor(32.9)) print(math.ceil(34.9)) print(sqrt(2)) print(sqrt(9)) print(cmath.sqrt(-9)) print((1+3j)*(9+4j)) turtle.forward(100) turtle.left(120) turtle.forward(100) turtle.left(120) turtle.forward(100) print(str("Hello, \nworld!")) print(repr("Hello, \nworld!")) print("Hello, world!") print(r'd:\nowhere') print(r'Let\'s go!') print('''Lit's go!''') print('''d:/app/log/hygeia_base/''') # print("\N{Dog}")
df42290656921417a5f441f8444c4ddba8986acb
tristandaly/practice_python
/1_character_input/character_input.py
370
3.875
4
import datetime now = int(datetime.datetime.now().year) name_input = input("Please enter your name: ") age_input = input("Please enter your age: ") int_age_input = int(age_input) repeat_input = input("How many times do you want to see this?: ") int_repeat_input = int(repeat_input) for i in range(int_repeat_input): print((now - int_age_input) + 100) print()
ae10f5bc870486417ae34e14d35aed9dd86f5d0c
npielawski/pytorch_tiramisu
/tiramisu/model.py
4,776
3.59375
4
"""Contains a base model for deep learning models to inherit from and have additional functionalities, such as summaries (like with Keras) and easier initialization. """ from __future__ import annotations from abc import ABC from collections.abc import Callable import os from typing import BinaryIO, IO, Tuple, Union import torch import torch.nn as nn class BaseModel(nn.Module, ABC): """Creates a base class for Deep Learning models with nice features. The class allows any inheriting model to have printed summaries, and easy initialization of certain layers. """ def __str__(self) -> str: """Returns the name of the current class.""" return type(self).__qualname__ def get_param_count(self) -> Tuple[int, int]: """Returns the number of parameters of the model. Returns (tuple): (The number of trainable params, The number of non-trainable params) """ param_count_nogrd = 0 param_count_grd = 0 for param in self.parameters(): if param.requires_grad: param_count_grd += param.size().numel() else: param_count_nogrd += param.size().numel() return param_count_grd, param_count_nogrd def summary( self, half: bool = False, printer: Callable[[str], None] = print ) -> None: """Logs some information about the neural network. Args: printer: The printing function to use. """ layers_count = len(list(self.modules())) printer(f"Model {self} has {layers_count} layers.") param_grd, param_nogrd = self.get_param_count() param_total = param_grd + param_nogrd printer(f"-> Total number of parameters: {param_total:n}") printer(f"-> Trainable parameters: {param_grd:n}") printer(f"-> Non-trainable parameters: {param_nogrd:n}") approx_size = param_total * (2.0 if half else 4.0) * 10e-7 printer(f"Uncompressed size of the weights: {approx_size:.1f}MB") def save(self, filename: Union[str, os.PathLike, BinaryIO, IO[bytes]]) -> None: """Saves the model""" torch.save(self, filename) def half(self) -> BaseModel: """Transforms all the weights of the model in half precision. Note: this function fixes an issue on BatchNorm being half precision. See: https://discuss.pytorch.org/t/training-with-half-precision/11815/2 """ super().half() for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.float() return self def initialize_kernels( self, initializer: Callable[[torch.Tensor], torch.Tensor], conv: bool = False, linear: bool = False, batchnorm: bool = False, ) -> None: """Initializes the chosen set of kernels of the model. Args: initializer: a function that will apply the weight initialization. conv: Will initialize the kernels of the convolutions. linear: Will initialize the kernels of the linear layers. batchnorm: Will initialize the kernels of the batch norm layers. """ for layer in self.modules(): if linear and isinstance(layer, nn.Linear): initializer(layer.weight) continue if conv and isinstance(layer, nn.Conv2d): initializer(layer.weight) continue if batchnorm and isinstance(layer, (nn.BatchNorm2d, nn.GroupNorm)): initializer(layer.weight) continue def initialize_biases( self, initializer: Callable[[torch.Tensor], torch.Tensor], conv: bool = False, linear: bool = False, batchnorm: bool = False, ) -> None: """Initializes the chosen set of biases of the model. Args: initializer: A function that will apply the weight initialization. conv: Will initialize the biases of the convolutions. linear: Will initialize the biases of the linear layers. batchnorm: Will initialize the biases of the batch norm layers. **kwargs: Extra arguments to pass to the initializer function. """ for layer in self.modules(): if layer.bias is None: continue if linear and isinstance(layer, nn.Linear): initializer(layer.bias) # type: ignore if conv and isinstance(layer, nn.Conv2d): initializer(layer.bias) # type: ignore if batchnorm and isinstance(layer, (nn.BatchNorm2d, nn.GroupNorm)): initializer(layer.bias) # type: ignore
206f73f8c7ef8de313e20611b6c043eb9834504b
AmmarMian/Fractals
/tests/test_nombrecomplexe.py
3,500
3.5625
4
import sys sys.path.append('../src') sys.path.append('./src') from math import sqrt from main import NombreComplexe import unittest class Test_NombreComplexe(unittest.TestCase): def test_creation(self): """Teste bonne création nombre complexe """ z = NombreComplexe(5, 7) assert z.real == 5 assert z.imag == 7 z = NombreComplexe(0, -5) assert z.real == 0 assert z.imag == -5 def test_module(self): """Teste du module du nombre complexe. """ list_numbers = [NombreComplexe(x, y) for x, y in zip(range(-50, 150, 10), range(-10,10,1))] list_numbers += [NombreComplexe(x, y) for x, y in zip(range(-10,10,1), range(-50, 150, 10))] for z in list_numbers: assert z.module() >= 0 assert z.module() == sqrt( z.real**2 + z.imag**2) def test_somme1(self): """Teste la somme de deux nombres complexes (1/2). """ z1 = NombreComplexe(5, 7) z2 = NombreComplexe(-1, 7) z = z1 + z2 assert z.real == 4 assert z.imag == 14 def test_somme2(self): """Teste la somme de deux nombres complexes (2/2). """ z1 = NombreComplexe(-5, 117) z2 = NombreComplexe(-10, 7) z = z1 + z2 assert z.real == -15 assert z.imag == 124 def test_sub1(self): """Teste la soustraction de deux nombres complexes (1/2). """ z1 = NombreComplexe(5, 7) z2 = NombreComplexe(-1, 7) z = z1 - z2 assert z.real == 6 assert z.imag == 0 def test_sub2(self): """Teste la soustraction de deux nombres complexes (2/2). """ z1 = NombreComplexe(0, 4) z2 = NombreComplexe(3, 7) z = z1 - z2 assert z.real == -3 assert z.imag == -3 def test_prod1(self): """Teste le produit de deux nombres complexes (1/2). """ z1 = NombreComplexe(0, 4) z2 = NombreComplexe(3, 7) z = z1 * z2 assert z.real == -28 assert z.imag == 12 def test_prod2(self): """Teste le produit de deux nombres complexes (2/2). """ z1 = NombreComplexe(117, 4) z2 = NombreComplexe(3, -70) z = z1 * z2 assert z.real == 631 assert z.imag == -8178 def test_power0(self): """Teste la puissance d'un nombre complexe (1/2). """ z1 = NombreComplexe(0, 4) z = z1**0 assert z.real == 1 assert z.imag == 0 def test_power2(self): """Teste la puissance d'un nombre complexe (2/2). """ z1 = NombreComplexe(117, 4) z = z1**2 assert z.real == 13673 assert z.imag == 936 def test_str0(self): """Teste si l'impression d'un nombre complexe se fait bien (1/3). """ z = NombreComplexe(1,5) assert z.__str__() == "1 + 5i" def test_str1(self): """Teste si l'impression d'un nombre complexe se fait bien (2/3). """ z = NombreComplexe(-1,-555) assert z.__str__() == "-1 - 555i" def test_str2(self): """Teste si l'impression d'un nombre complexe se fait bien (3/3). """ z = NombreComplexe(77,0) assert z.__str__() == "77" if __name__ == '__main__': import nose2 nose2.main()
52da73e98a88e854302051f9a40f82b5a91886ff
luksamuk/study
/SI/2021-1/IA/TP1/src/03.py
501
3.734375
4
from random import randint num_updates = 0 maximum = randint(1, 100) print("{}".format(maximum)) for i in range(99): new_num = randint(1, 100) if new_num > maximum: maximum = new_num num_updates += 1 print("{} (atualizado)".format(new_num)) else: print("{}".format(new_num)) print("O valor máximo encontrado foi {}".format(maximum)) print("O número máximo de vezes que o maior valor foi " "atualizado foi {} vezes." .format(num_updates))
6515f84fcf366664a70057fc2f6d0af667638ca5
kanoga/prime_numbers
/test_int.py
359
3.609375
4
import unittest from prime_number import isPrime class PrimeTests(unittest.TestCase): def test_input_must_be_a_number(self): self.assertEqual(isPrime(1),"The input must be a number only") def test_number_is_int(self): self.assertIsInstance(isPrime(int), "The input must be an integer") if __name__ == "__main__": unittest.main()
bb9e2f57068039cdda03127369bbe8ad8ac535c4
gain620/algorithms-in-python
/recursion/cal_sum_of_list.py
488
4
4
# conventional way def listSum(numList): theSum = 0 for i in numList: theSum += i return theSum # calculating the sum of list using a recursive function def listSumRecursion(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listSumRecursion(numList[1:]) print('without using recursion ->', listSum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) print('using recursion ->', listSumRecursion([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
4eba6152ec0c08020df760bc04cf854ef5927961
nathan-miller23/Backtesting_demo
/backtesting_demo/strategies/volume_weighted_moving_average.py
1,281
3.609375
4
from strategies.abstract_strategy import Abstract_strategy class Volume_weighted_moving_average(Abstract_strategy): NAME = 'Volume Weighted moving average' def __init__(self, data, ticker, days): # Call parent class constructor to set instance variables super().__init__(data, ticker, days) def apply(self): # helper function to find average def f(a, b, c): return (a + b + c) / 3 # Splice data for only days we're interested in self.data = self.data[-1*self.days:].copy() # This is to avoid all NaNs on sundays by replacing them with 0s self.data.fillna(0, inplace=True) # Create new column with the average of 'high', 'low', and 'close' called 'typical price' self.data['typical price'] = self.data[['high', 'low', 'close']].apply(lambda x : f(*x), axis=1) # Create new column called 'weighted price' that is the product of 'volume' and 'typical price' self.data['weighted price'] = self.data[['typical price', 'volume']].apply(lambda x : x[0]*x[1], axis=1) # Sum over 'volume' col to get total number transactions during period total_volume = sum(self.data['volume']) # Execute VWAP formula self.val = sum(self.data['weighted price']) / total_volume # Print with formatting print(self)
eeafa473d689cc64731695f30c912d605d46f244
mfrisby/DrQuine
/bonus/Colleen.py
814
3.546875
4
''' Comment ''' def tutu(): return def main(): bn = chr(10) bc = chr(39) tutu() ''' myComment ''' s = '%c%c%c%c Comment%c%c%c%c%cdef tutu():%c return%cdef main():%c bn = chr(10)%c bc = chr(39)%c tutu()%c' s1 = ' %c%c%c%c myComment%c %c%c%c%c s = %c%s%c%c s1 = %c%s%c%c s3 = %c%s%c%c s2 = %c%s%c%c' s3 = 'main()' s2 = ' print(s % (bc, bc, bc, bn, bn, bc, bc, bc, bn, bn, bn, bn, bn, bn, bn) + s1 % (bc, bc, bc, bn, bn, bc, bc, bc, bn, bc, s, bc, bn, bc, s1, bc, bn, bc, s3, bc, bn, bc, s2, bc, bn) + s2 + bn + s3)' print(s % (bc, bc, bc, bn, bn, bc, bc, bc, bn, bn, bn, bn, bn, bn, bn) + s1 % (bc, bc, bc, bn, bn, bc, bc, bc, bn, bc, s, bc, bn, bc, s1, bc, bn, bc, s3, bc, bn, bc, s2, bc, bn) + s2 + bn + s3) main()
f88885ed6864d33c7a7b21f983a63371e6973e49
AsadR2002/Life-Simulator
/Life Simulator Game.py
81,881
3.65625
4
''' Asad Rehman ''' import easygui as a #this program uses easygui, setting as a makes it more convenient def start(): #set game inside function to allow game to be eaisly restarted at the end age = 0 #age counter beg = ["Play", "Quit"] beg1 = a.buttonbox("Welcome to Life Simulator. This game simulates the life of a person. Throughout, you will be able to make decisions which will dictate your fate. Press play to begin.", "", beg) if beg1 == beg[0]: w = True #If play is clicked, sets w as True so program carries out else: quit() while w == True: saz = ["saz.gif"] a.msgbox("Hi! Welcome to the Life simulator.", image = saz) gend = ["Male", "Female"] gendpick = a.buttonbox("Which gender would you like to be born as?", "", gend)#Gender Choice eth = ["Black", "Indian", "Asian", "Hispanic", "White"] ethpick = a.buttonbox("Which ethnicity would you like to be born as?", "", eth) #Race Choice name = a.enterbox("Please enter your name:") #Name choice born = ["baby.gif"] #defines image a.msgbox("Hello " + name + "!") a.msgbox("You are born as a " + ethpick + " " + gendpick + ".", image = born) a.msgbox("You are currently " + str(age) + " years old.") age1 = ["Options", "Age"] pick1 = a.buttonbox("Would you like to explore your options or age 1 year?", "", age1) while pick1 == age1[0]: a.msgbox("You have no options... you were literally just born!") pick1 = a.buttonbox("Would you like to explore your options or age 1 year?", "", age1) if pick1 == age1[1]: break if pick1 == age1[1]: age += 1 a.msgbox("You are now " + str(age) + " years old.") import random dadleavechance = random.randint(1, 6) #chance of dad leaving is 50% if 1 <= dadleavechance <= 3: firstchoice = ["Play","Let him leave"] pick2 = a.buttonbox("Your dad says he is going to leave. To get him to stay, you must collect 500 shells in the Island Dice Game.", "", firstchoice) if pick2 == firstchoice[1]: a.msgbox("Your dad has left.") if pick2 == firstchoice[0]: import random q = 100 a.msgbox("Welcome to the island dice game! You start off with 100 Shells ") y = True while y: #Carries out osland dice game b = random.randint(1,6) c = random.randint(1,6) d = a.integerbox("How many shells would you like to risk?: ", upperbound = 100) e = a.enterbox("Please enter a risk level (high or low): ") f = b + c if f >= 2 and f <= 6: if e == "High" or e == "high": q -= d a.msgbox("The dice rolled is " + str(f)) a.msgbox("You now have: " + str(q) + " Shells.") else: d = d * 2 q += d a.msgbox("The dice rolled is " + str(f)) a.msgbox("You now have: " + str(q) + " Shells.") elif f >= 8 and f <= 12: if e == "High" or e == "high": d = d * 2 q += d a.msgbox("The dice rolled is " + str(f)) a.msgbox("You now have: " + str(q) + " Shells.") else: q -= d a.msgbox("The dice rolled is " + str(f)) a.msgbox("You now have: " + str(q) + " Shells.") else: q -= d a.msgbox("The dice rolled is " + str(f)) a.msgbox("You now have: " + str(q) + " Shells.") if q == 0: a.msgbox("Your dad has left.") #If 500 shells or 0 shells, game ends y = False break if q >= 500: a.msgbox("Despite your win, your dad leaves anyways.") #Plot twist else: a.msgbox("Your dad stays with you.") age2 = ["Options", "Age"] agepick2 = a.buttonbox("Would you like to explore your options or age 9 more years?", "", age2) if agepick2 == age2[0]: if 1 <= dadleavechance <= 3: #Different menu based on past a.msgbox("Your dad just left you... what options do you even have right now??") agepick2 = a.buttonbox("Would you like to explore your options or age 9 more years?", "", age2) else: a.msgbox("Your dad stayed...be happy for now.") agepick2 = a.buttonbox("Would you like to explore your options or age 9 more years?", "", age2) if agepick2 == age2[1]: ten = ["ten.gif"] a.msgbox("You are now 10 years old.", image = ten) age +=9 if 1 <= dadleavechance <= 3: #Different menu based on past anx = ["anx.gif"] a.msgbox("You have been getting bullied for the past 6 years and have now been diagnosed with anxiety.", image = anx) age3 = ["Options", "Age"] agepick3 = a.buttonbox("Would you like to explore your options or age 5 years?", "", age3) if agepick3 == age3[0]: #Menu options choice1 = ["Transfer Schools", "Drop Out of School", "Assault Your Bully", "Age 5 Years"] choicepick1 = a.choicebox("Here are your options:", "", choice1) if choicepick1 == choice1[0]: #Transfer Schools schools = ["Asad Public School", "Spencer Bundy Elementary School"] schoolpick = a.buttonbox("Please choose which school you'd like to transfer to:", "", schools) if schoolpick == schools[0]: a.msgbox("Your depression got more severe at Asad Public School.") a.msgbox("You started eating lots of candy.") a.msgbox("You have lost your life at the age of 10 from diabetes.") w = False #If they die, loop ends as look is while w is True break else: a.msgbox("Congrats! You have beat your depression.") a.msgbox("You are now 11 years old and are the most popular kid in your grade.") cand = ["candy.gif"] a.msgbox("You are offered a cool candy by an older kid who says it will make you cooler.", image = cand) candy = ["Take It", "Don't Take It"] candypick = a.buttonbox("Do you take it or not?", "", candy) if candypick == candy[0]: a.msgbox("You got addicted and started eating a lot of that candy.") a.msgbox("You have lost your life at the age of 10 from diabetes.") w = False break else: a.msgbox("Good choice!") agepick3 = age3[1] elif choicepick1 == choice1[1]: #Drop Out of School a.msgbox("You have dropped out of school.") a.msgbox("Your parents are extremely disappointed in your actions.") drop1 = ["Back to School", "No"] droppick = a.buttonbox("Do you go back to school or not?", "", drop1) if droppick == drop1[0]: agepick3 = age3[1] #age 5 years else: a.msgbox("You have been kicked out of your house.") a.msgbox("You have nowhere to live.") a.msgbox("Your life ended at 11 years old when you got hit by a car and died.") w = False break elif choicepick1 == choice1[2]: #Assault Your Bully a.msgbox("You decide to attack your bully.") a.msgbox("You are no longer being bullied.") import random getcaught = random.randint(1, 6) #chance of getting caught if 1 < getcaught < 4: a.msgbox("You get in trouble for your actions. Your parents are disappointed.") else: a.msgbox("You get away with attacking your bully. No one finds out.") if agepick3 == age3[1]: a.msgbox("You are now 15 years old.") age += 5 #add to age counter else: a.msgbox("Childhood is fun.") a.msgbox("You are now 14 years old.") age += 5 #add to age counter highs = ["hs.gif"] #image a.msgbox("Congrats you are now on your way to high school!", image = highs) hs1 = ["Horton High School", "Central Kings High School"] #Differnt outcomes based on school choice hspick1 = a.buttonbox("Which highschool would you like to attend?", "", hs1) #hs = Highschool stdy = ["study.gif"] a.msgbox("On the first day of school, you see some people from middle school hanging out together.") hs2 = ["Go Talk to Them", "Say Nothing"] hspick2 = a.buttonbox("What do you choose to do?", "", hs2) if hspick2 == hs2[0]: if hspick1 == hs1[0]: #If Horton School a.msgbox("They do not want to talk to you.") a.msgbox("You are embarrassed.") hs3 = ["Defend Yourself and Fight", "Run Away"] hspick3 = a.buttonbox("What is your reaction?: ", "", hs3) if hspick1 == hs1[1]: a.msgbox("They welcome you.") a.msgbox("You have made new friends.") if hspick2 == hs2[1]: #If you do not talk to them a.msgbox("You remain antisocial.") a.msgbox("You are now 15 years old.") age +=1 a.msgbox("There is a school event coming up.") hs4 = ["Go", "Stay Home"] hspick4 = a.buttonbox("Do you go with your friends?", "", hs4) if hspick4 == hs4[0]: if hspick2 == hs2[1]: a.msgbox("You have no friends to go with you.") hs5 = ["Yes", "No"] hspick5 = a.buttonbox("Do you try and make some friends? ", "", hs5) if hspick5 == hs5[0]: if hspick1 == hs1[1] or hspick3 == hs3[0]: #If going to Central Kings or stuck up for themsleves at Horton a.msgbox("You are able to find friends.") hspick4 = hs4[0] else: a.msgbox("You do not find friends.") else: a.msgbox("You become depressed.") else: a.msgbox("You have a mediocore time with your friends.") if hspick4 == hs4[1]: a.msgbox("You have a good time at home. Your friends are not happy.") import random friendleaves = random.randint(1, 2) #chance of leaving if friendleaves > 1: a.msgbox("Your friends leave you.") a.msgbox("You are suffering from depression.") else: a.msgbox("Your friends do not invite you next time.") if friendleaves > 1: a.msgbox("Your mom has been noticing that you have been sad. She suggests you go to the therapist with her.") hs5 = ["Go", "Not for me"] hspick5 = a.buttonbox("Do you go to the therapist? ", "", hs5) if hspick5 == hs5[0]: a.msgbox("You have been cured of your depression.") if hspick5 == hs5[1]: a.msgbox("You have died from depression.") w = False break a.msgbox("While at school, you see the popular kids waiting at a locker near you.") hs6 = ["Go talk to them", "Leave them alone"] hspick6 = a.buttonbox("Do you approach them? ", "", hs6) if hspick6 == hs6[0]: if hspick1 == hs1[0]: import random popchance = random.randint(1, 6) #chance they talk to you if 1 <= popchance <= 3: a.msgbox("They welcome you. They take out some suspicious candy.") hs7 = ["Take the Candy", "Refuse the Candy"] hspick7 = a.buttonbox("They offer you the candy and tell you to eat it: ", "", hs7) if hspick7 == hs7[0]: a.msgbox("You are now popular.") import random cdeath = random.randint(1, 6) #chance candy harms you if 1 <= cdeath <= 4: a.msgbox("The candy kills you. You have died at the age of 15.") w = False break else: a.msgbox("The candy does not harm you.") else: a.msgbox("They call you lame. You leave, ashamed.") else: a.msgbox("They do not want to talk to you.") if hspick1 == hs1[1]: a.msgbox("They are friendly. You become popular.") else: ("You remain antisocial.") notstudy = 0 #Keeps track of if player studies during highschool, dictates future job options study = 0 a.msgbox("You have a big test tommorow, but your friends want to hang out.", image = stdy) hs8 = ["Go hang out", "Stay home and study"] hspick8 = a.buttonbox("What do you choose to do? ", "", hs8) #If theys study, add to study, if not, add to notstudy if hspick8 == hs8[0]: a.msgbox("You do bad on your test.") notstudy += 1 else: a.msgbox("You do well on your test.") study += 1 a.msgbox("You start to like someone in school.") if gendpick == gend[0]: #If guy, they like female, if girl, they like guy a.msgbox("You have a crush on Carly.") if gendpick == gend[1]: a.msgbox("You have a crush of Freddie.") hs9 = ["Yes", "No"] hspick9 = a.buttonbox("Do you ask them out? ", "", hs9) if hspick9 == hs9[0]: import random datechance = random.randint(1, 6)#chane they say yes if 1 <= datechance <= 3: a.msgbox("They say yes. You are now dating.") if ethpick == eth[1]: a.msgbox("Your parents find out about your secret relationship.") a.msgbox("You are sent back to your home country. You die at the age of 16.") w = False break else: a.msgbox("Yor significant other wants to have sex, but you do not have a condom.") bb1 = ["Yes", "No"] # bb = Baby bbpick1 = a.buttonbox("Do you have sex?: ", "", bb1) if bbpick1 == bb1[0]: a.msgbox("You have unprotected sex.") import random babychance = random.randint(1, 6) if 1 <= babychance <= 5: #chance of baby a.msgbox("Uh oh, theres a baby coming.") if gendpick == gend[1]: bb2 = ["Keep it", "Abortion"] bbpick2 = a.buttonbox("What do you do? ", "", bb2) if bbpick2 == bb2[0]: a.msgbox("You die during pregnancy.") w = False break else: a.msgbox("You die during the abortion procedure.") w = False break else: ("Your girlfriends dad murders you.") w = False break else: ("You had fun.") else: a.msgbox("They break up with you.") else: a.msgbox("They reject you.") else: a.msgbox("You remian single and lonely.") a.msgbox("You have a big assignment tommorow, but your friends want to hang out.", image = stdy) #study scenerio, adds to counter hs10 = ["Go hang out", "Stay home and work"] hspick10 = a.buttonbox("What do you choose to do? ", "", hs8) if hspick10 == hs10[0]: a.msgbox("You do bad on your assignment.") notstudy += 1 else: a.msgbox("You do well on your assignment.") study += 1 a.msgbox("You have an exam tommorow, but your friends want to hang out.", image = stdy) #study scenerio, adds to counter hs11 = ["Go hang out", "Stay home and study"] hspick11 = a.buttonbox("What do you choose to do? ", "", hs8) if hspick11 == hs11[0]: a.msgbox("You do bad on your exam.") notstudy += 1 else: a.msgbox("You do well on your exam.") study += 1 age += 2 grad = ["grad.gif"] a.msgbox("You are now 18 years old. You graduate highschool.", image = grad) choices2 = ["Workplace", "Community College", "University",] #Different choices in future choicepicks2 = a.choicebox("Here are your options moving forward:", "", choices2) age = 18 if choicepicks2 == choices2[2]: #If they did not study, notstudy will be greater than study and they cannot go to University if study < notstudy: a.msgbox("Your grades are not high enough for Univeristy.") choicepicks2 = a.choicebox("Here are your options moving forward:", "", choices2) else: choices3 = ["Engineering", "Business", "Computer Science", "Arts"] #choices in University, dictates future jobs choicepicks3 = a.choicebox("Select your major:", "", choices3) a.msgbox("You are now enrolled in University.") age += 4 #University is four year program a.msgbox("You have graduated from University with a degree.") if choicepicks2 == choices2[1]: a.msgbox("You are enrolled in Community College.") age += 2 #Community college is two year program a.msgbox("You have graduated from Community College.") if choicepicks2 == choices2[0]: a.msgbox("You do not pursue further education.") work = ["work.gif"] a.msgbox("Welcome to the workplace. You are " + str(age) + ".", image = work) #age varies based on choice job = 0 #new counters keep track of employment and living status move = 0 while age <= 28: #This menu set is active until 28, then is replaced lf1 = ["Options", "Age"] lfpick1 = a.buttonbox("Would you like to explore your options or age 1 year?", "", lf1) if lfpick1 == lf1[0]: lfchoice1 = ["Get a Job", "Move Out"] lfchoice = a.choicebox("Here are your options:", "", lfchoice1) if lfchoice == lfchoice1[1]: if job > 2: #job status determines eligibilty to move out if move > 5: #If they have moved out, counter will keep track and inform a.msgbox("You do not live with your parents.") else: a.msgbox("You move out from your parents house.") move += 10 #adds to counter first time they move out else: a.msgbox("You do not have a job. You cannot move out.") if lfchoice == lfchoice1[0]: if job > 2: #if they already have a job when clicking job option jbchoice1 = ["YES", "NO"] jbpick1 = a.buttonbox("You already have a job. Do you want to leave it?", "", jbchoice1) #choice to leave job if jbpick1 == jbchoice1[0]: job = 0 #if leave job, set counter to zero jobchoice1 = a.choicebox("Here are possible job options: ", "", jobchoice) #job menu if jobchoice1 == jobchoice[0]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[0]: #qualification check: will not let user get job unless they have necessary education a.msgbox("Welcome to your new position.") job += 15 #specific value will dictate aspects later on else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[1]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[2]: #qualification check a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[2]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[1]: #qualification check a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[3] or jobchoice1 == jobchoice[4]: #qualifcation check if choicepicks2 != choices2[0]: a.msgbox("Welcome to your new position.") job += 10 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[5] or jobchoice1 == jobchoice[6]: a.msgbox("Welcome to your new position.") job += 5 if jbpick1 == jbchoice1[1]: a.msgbox("You stay with your current job.") else: #if they do not already have job, goes straight into job menu jobchoice = ["Junior Engineer", "Game Developer", "Financial Analyst", "Teacher", "Marketing Agent", "Fast Food Worker", "Taxi Driver"] jobchoice1 = a.choicebox("Here are possible job options: ", "", jobchoice) if jobchoice1 == jobchoice[0]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[0]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[1]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[2]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[2]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[1]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[3] or jobchoice1 == jobchoice[4]: if choicepicks2 != choices2[0]: a.msgbox("Welcome to your new position.") job += 10 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[5] or jobchoice1 == jobchoice[6]: a.msgbox("Welcome to your new position.") job += 5 if lfpick1 == lf1[1]: age += 1 #adds 1 to age if they click age one year a.msgbox("You are now " + str(age) + "." ) import random #chance of cancer in youth cancerchance = random.randint(1, 15) if cancerchance == 10: can = ["canc.gif"] a.msgbox("You have been diagnosed with cancer.", image = can) import random survchance = random.randint(1, 10)#chance of beating cancer if 1 < survchance < 5: a.msgbox("You have died from cancer.") w = False break else: a.msgbox("You have beat cancer.") savings = 0 #counter keeps track of savings, dictates what they can buy date = 0 #keep track of relationship status while 29 <= age < 65: #new menu for thse ages fe1 = ["Options", "Age"] #f = final (final menu) fepick1 = a.buttonbox("Would you like to explore your options or age 1 year?", "", fe1) if fepick1 == fe1[0]: fchoice1 = ["Job Change", "Buy a House", "Buy a Car", "Play Lottery", "Relationships"] #choices fpick1 = a.choicebox("Here are your options:", "", fchoice1) if fpick1 == fchoice1[0]: if job > 2: #checks job status jbchoice1 = ["YES", "NO"] jbpick1 = a.buttonbox("You already have a job. Do you want to leave it?", "", jbchoice1) if jbpick1 == jbchoice1[0]: #job choices job = 0 jobchoice1 = a.choicebox("Here are possible job options: ", "", jobchoice) if jobchoice1 == jobchoice[0]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[0]: #qualification check(same as above) a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[1]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[2]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[2]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[1]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[3] or jobchoice1 == jobchoice[4]: if choicepicks2 != choices2[0]: a.msgbox("Welcome to your new position.") job += 10 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[5] or jobchoice1 == jobchoice[6]: a.msgbox("Welcome to your new position.") job += 5 if jbpick1 == jbchoice1[1]: a.msgbox("You stay with your current job.") else: jobchoice = ["Senior Engineer", "Senior Game Developer", "Senior Financial Analyst", "Head Teacher", "Senior Marketing Agent", "Fast Food Manager", "Taxi Driver"] jobchoice1 = a.choicebox("Here are possible job options: ", "", jobchoice) if jobchoice1 == jobchoice[0]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[0]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[1]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[2]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[2]: if choicepicks2 == choices2[2] and choicepicks3 == choices3[1]: a.msgbox("Welcome to your new position.") job += 15 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[3] or jobchoice1 == jobchoice[4]: if choicepicks2 != choices2[0]: a.msgbox("Welcome to your new position.") job += 10 else: a.msgbox("You are unable to get this job.") if jobchoice1 == jobchoice[5] or jobchoice1 == jobchoice[6]: a.msgbox("Welcome to your new position.") job += 5 if fpick1 == fchoice1[1]: #house choices hchoice1 = ["Condo: 60,000 Dollars", "Small 2 Bedroom House: 100,000 Dollars", "4 Bedroom House: 300,000 Dollars", "Large 6 Bedroom House: 600,000 Dollars", "Mansion: 10,000,000 Dollars"] hpick1 = a.choicebox("Here are the available houses:", "", hchoice1) # h = house if hpick1 == hchoice1[0]: if savings >= 60000: #savings check: counter (amount of money) dictates which house user can buy con = ["cond.gif"] a.msgbox("You have purchased a condo.", image = con) savings -= 60000 #if they buy, subtracts cost from savings else: a.msgbox("You do not have enough money to buy this house.") if hpick1 == hchoice1[1]: if savings >= 100000: #savings check smhouse = ["smhouse.gif"] a.msgbox("You have purchased a Small 2 Bedroom House.", image = smhouse) savings -= 100000 #subtract from counter else: a.msgbox("You do not have enough money to buy this house.") if hpick1 == hchoice1[2]: if savings >= 300000: midhouse = ["midhouse.gif"] a.msgbox("You have purchased a 4 Bedroom House.", image = midhouse) savings -= 300000 else: a.msgbox("You do not have enough money to buy this house.") if hpick1 == hchoice1[3]: if savings >= 600000: bighouse = ["bighouse.gif"] a.msgbox("You have purchased a Large 6 Bedroom House.", image = bighouse) savings -= 600000 else: a.msgbox("You do not have enough money to buy this house.") if hpick1 == hchoice1[4]: if savings >= 10000000: mansion = ["mansion.gif"] a.msgbox("You have purchased the Mansion.", image = mansion) savings -= 10000000 else: a.msgbox("You do not have enough money to buy this house.") if fpick1 == fchoice1[2]: #car choices cchoice1 = ["Honda Civic: 10,000 Dollars", "Toyota Rav4: 15,000 Dollars", "BMW M5: 25,000 Dollars", "Range Rover: 40,000 Dollars", "Mercedes Benz S Class: 100,000 Dollars", "Bugatti Chiron: 1,000,000 Dollars"] cpick1 = a.choicebox("Here are the available cars:", "", cchoice1) # c = car if cpick1 == cchoice1[0]: if savings >= 10000: #savings check: checks if user has enough money to buy car honda = ["bad_car.gif"] a.msgbox("You have purchased a Honda Civic.", image = honda) savings -= 10000 #subtracts purchase value from savings counter else: a.msgbox("You do not have enough money to buy this car.") if cpick1 == cchoice1[1]: if savings >= 15000: toyota = ["rav4.gif"] a.msgbox("You have purchased a Toyota Rav4.", image = toyota) savings -= 15000 else: a.msgbox("You do not have enough money to buy this car.") if cpick1 == cchoice1[2]: if savings >= 25000: bmw = ["m5.gif"] a.msgbox("You have purchased a BMW M5.", image = bmw) savings -= 25000 else: a.msgbox("You do not have enough money to buy this car.") if cpick1 == cchoice1[3]: if savings >= 40000: rover = ["range.gif"] a.msgbox("You have purchased a Range Rover.", image = rover) savings -= 40000 else: a.msgbox("You do not have enough money to buy this car.") if cpick1 == cchoice1[4]: if savings >= 100000: benz = ["benz.gif"] a.msgbox("You have purchased the Mercedes Benz S-Class.", image = benz) savings -= 100000 else: a.msgbox("You do not have enough money to buy this car.") if cpick1 == cchoice1[5]: if savings >= 1000000: chiron = ["chiron.gif"] a.msgbox("You have purchased the Bugatti Chiron.", image = chiron) savings -= 1000000 else: a.msgbox("You do not have enough money to buy this car.") if fpick1 == fchoice1[3]: #play lottery a.msgbox("You buy a lottery ticket.") saving -= 500 #costs money, user cannot keep playing import random #random chance of winning lottery lotchance = random.randint(1, 1000) if lotchance == 69 or lotchance == 666: #low chance a.msgbox("You have won the lottery!!!!") savings += 15000000 #adds money if they win else: a.msgbox("You do not win the lottery.") if fpick1 == fchoice1[4]: #relationships rchoice1 = ["Hang out with friends", "Find a Date", "Breakup with your Significant Other"] rpick1 = a.choicebox("Here are the options:", "", rchoice1) # r = relationship if rpick1 == rchoice1[0]: import random friendact = random.randint(1, 5) #chooses between different possible activities if friendact == 1: a.msgbox("You go bowling with your friends.") if friendact == 2: a.msgbox("You have drinks with your friends.") if friendact == 3: a.msgbox("You eat dinner with your friends.") if friendact == 4: a.msgbox("You go clubbing with your friends.") else: a.msgbox("You watch a movie with your friends.") if rpick1 == rchoice1[1]: if date > 1: #if looking for date, if counter is above 1 it means they are already dating, and must break up a.msgbox("You are already dating someone.") else: #if not dating anyone if gendpick == gend[1]: #if user is female import random guy = random.randint(1, 5) #different scenerios to find a date if guy == 1: a.msgbox("You meet Mark while at the mall. You guys have a lot in common.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask him out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) #chance of saying yes if yeschance == 1: a.msgbox("He says yes. You are now dating.") date += 3 #if you start dating, counter increases in order to keep track else: a.msgbox("He rejects you.") else: a.msgbox("You do not ask him out.") if guy == 2: a.msgbox("You meet a guy named Rohan while walking through the park. You guys hit it off.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask him out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("He says yes. You are now dating.") date += 3 else: a.msgbox("He rejects you.") else: a.msgbox("You do not ask him out.") if guy == 3: a.msgbox("You meet Jamal while at a resturant. You guys text for a bit and become good friends.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask him out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("He says yes. You are now dating.") date += 3 else: a.msgbox("He rejects you.") else: a.msgbox("You do not ask him out.") if girl == 4: a.msgbox("You meet Wu while jogging. You go on a run together and have a good time.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask him out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("He says yes. You are now dating.") date += 3 else: a.msgbox("He rejects you.") else: a.msgbox("You do not ask him out.") if girl == 5: a.msgbox("Jacob is your friends ex-boyfriend. You two run into each other at a club and take a liking to one another.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask him out?", "", gchoice1 ) if gpick1 == gchoice1[0]: a.msgbox("He says yes. You are now dating.") date += 3 a.msgbox("Your friend is mad at you. She no longer talks to you.") else: a.msgbox("You do not ask him out.") if gendpick == gend[0]: #if user is male import random girl = random.randint(1, 5) if girl == 1: a.msgbox("You meet Ashley while at the mall. You guys have a lot in comman.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask her out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("She says yes. You are now dating.") date += 3 else: a.msgbox("She rejects you.") else: a.msgbox("You do not ask her out.") if girl == 2: a.msgbox("You meet a girl name Cathy while walking through the park. You guys hit it off.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask her out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("She says yes. You are now dating.") date += 3 else: a.msgbox("She rejects you.") else: a.msgbox("You do not ask her out.") if girl == 3: a.msgbox("You meet Requisha while at a resturant. You guys text for a bit and become good friends.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask her out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("She says yes. You are now dating.") date += 3 else: a.msgbox("She rejects you.") else: a.msgbox("You do not ask her out.") if girl == 4: a.msgbox("You meet Simran while jogging. You go on a run together and have a good time.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask her out?", "", gchoice1 ) if gpick1 == gchoice1[0]: import random yeschance = random.randint(1, 2) if yeschance == 1: a.msgbox("She says yes. You are now dating.") date += 3 else: a.msgbox("She rejects you.") else: a.msgbox("You do not ask her out.") if girl == 5: a.msgbox("Susan is your friends ex-girlfriend. You two run into each other at a club and take a liking to one another.") gchoice1 = ["Yes", "No"] gpick1 = a.buttonbox("Do you ask her out?", "", gchoice1 ) if gpick1 == gchoice1[0]: a.msgbox("She says yes. You are now dating.") date += 3 a.msgbox("Your friend is mad at you. He no longer talks to you.") else: a.msgbox("You do not ask her out.") if rpick1 == rchoice1[2]: #breakup with significant other if date > 1: #if counter is greater than 1, it means you are dating someone a.msgbox("You break up with your significant other.") date -= 3 #sets counter to zero so program knows you are single import random killc = random.randint(1, 10) #chance regarding how significant other takes it if killc == 10: a.msgbox("They attack you. You escape and sue them. You get 10,000 dollars.") savings += 10000 #adds the money to savings else: a.msgbox("You part peacefully.") else: #if not dating someone a.msgbox("You are not dating someone. Go find a date.") if fepick1 == fe1[1]: #choose to age 1 year if job == 15: #adds yearly savings to counter, varies based on job level.This is why certain jobs added different amounts to counter savings += 30000 #if High paying job (ex: Engineer) if job == 10: savings += 20000 #medium paying job if job == 5: savings += 10000 #low paying job (ex: Fast Food Worker) age += 1 #adds to age counter a.msgbox("You are now " + str(age) + ". You have " + str(savings) + " dollars.") #tells user their age and amount of money they have #at certain ages, different events will take place, these are programmed below if age == 30: a.msgbox("You meet up with some old highschool friends. You have a good time.") if age == 32: a.msgbox("While at a baseball game, Someone throws their drink at you.") mchoice1 = ["Assault them", "Forgive and Forget"] # m = miscellaneous mpick1 = a.buttonbox("What do you do?", "", mchoice1 ) if mpick1 == mchoice1[0]: a.msgbox("You punched them in the head. You got kicked out of the game.") if mpick1 == mchoice1[1]: a.msgbox("You forgave them. You made a new friend in the end.") if age == 34: a.msgbox("You get the flu.") import random flud = random.randint(1, 10) #chance of death if flud== 10: a.msgbox("You have died from the flu.") w = False break else: a.msgbox("You have made a full recovery.") if age == 36: a.msgbox("While walking around, You find someones wallet.") mchoice2 = ["Take it", "Return to Owner"] mpick2 = a.buttonbox("What do you do?", "", mchoice2 ) if mpick2 == mchoice2[0]: a.msgbox("You decide to take the money.") if mpick2 == mchoice2[1]: a.msgbox("You return the wallet to the owner.") if age == 38: a.msgbox("You get promoted at your job.") savings += 10000 #bonus if age == 40: import random teamw = random.randint(1, 2) #in honour of the raptors if teamw == 1: a.msgbox("Your favourite basketball team wins the national championship.") else: a.msgbox("Your favourite basketball team loses in the final of the national championship.") if age == 42: a.msgbox("While on your way to the airport, some random guy tells you that he will give you 100 000 dollars to take a strange package with you.") mchoice3 = ["Take it", "Refuse"] mpick3 = a.buttonbox("What do you do?", "", mchoice3 ) if mpick3 == mchoice3[0]: a.msgbox("You agree to take the package.") a.msgbox("You are busted with 10 pounds of candy at the airport.") a.msgbox("You are sentencd to 10 years in prison.") a.msgbox("You die in prison during a fight.") w = False break if mpick3 == mchoice3[1]: a.msgbox("You leave the package.") if age == 44: a.msgbox("Your mom invites you to brunch.") mchoice4 = ["Go", "Say you are busy"] mpick4 = a.buttonbox("Do you go?", "", mchoice4 ) if mpick4== mchoice4[0]: a.msgbox("You have a good time with your mom.") if mpick4 == mchoice4[1]: a.msgbox("Your mom is sad. Your mom dies from depression.") if age == 46: a.msgbox("Your idol basketball player, Kawhi Leonard, stays with your team.") #in honour of the MVP, please stay if age == 48: a.msgbox("You are suffering from the gout.") if age == 50: a.msgbox("You get promoted at your job.") savings += 10000 #bonus if age == 52: a.msgbox("You see a homeless man breaking the law.") mchoice5 = ["Report them", "Ignore it"] mpick5 = a.buttonbox("What do you do?", "", mchoice5 ) if mpick5 == mchoice5[0]: a.msgbox("You report the homeless man. He assualts you.") if mpick5 == mchoice5[1]: a.msgbox("You ignore the law breaker.") if age == 54: import random cancerchance = random.randint(1, 15)#chance of death if cancerchance == 10: a.msgbox("You have been diagnosed with cancer.") import random survchance = random.randint(1, 10) if 1 < survchance < 5: a.msgbox("You have died from cancer.") w = False break else: a.msgbox("You have beat cancer.") if age == 56: a.msgbox("You and your siblings have a good time hanging out at the lake.") if age == 58: a.msgbox("Your newphew graduates from highschool.") if age == 60: a.msgbox("You get promoted at your job.") savings += 10000 #bonus if age == 62: import random cancerchance = random.randint(1, 15) if cancerchance == 10: a.msgbox("You have been diagnosed with hepatitis A.") import random survchance = random.randint(1, 10) #chance of death if 1 < survchance < 5: a.msgbox("You have died from hepatitis A.") w = False break else: a.msgbox("You have beat hepatitis A.") if age == 64: a.msgbox("You find a mysterious bag of candy.") mchoice6 = ["Consume it", "Leave it alone"] mpick6 = a.buttonbox("What do you do?", "", mchoice6 ) if mpick6 == mchoice6[0]: a.msgbox("You eat all of the candy.") a.msgbox("You die from diabetes.") w = False break if mpick6 == mchoice6[1]: a.msgbox("You walk away from the bag.") if age >= 65: #at 65 a.msgbox("Wow, you made it to 65! You retire peacefully. Time to enjoy life.") a.msgbox("Wait, you didn't start a retirement savings fund, did you?") #end twist w = False break while w == False: #after person dies a.msgbox("Thank you for playing Life simulator.") a.msgbox('''This game is designed by Asad Rehman. Thank you for playing.''') endgame = ["Play Again", "Quit"] final = a.buttonbox("What would you like to do?", "", endgame) if final == endgame[0]: start() #if play again, restarts function if final == endgame[1]: quit() start() #starts function when code is first launched
033b6f57df286452a6651896a410d54d3cd45021
AniketPant02/voronoi-generation
/voronois.py
2,800
3.53125
4
from PIL import Image import random import math import seaborn as sns from PIL import ImageColor from tqdm import tqdm def generate_voronoi_diagram(width, height, num_cells, mean_x, stdv_x, mean_y, stdv_y, colorMap1, colorMap2): """Creates Voronio diagram and saves it. Each site is randomly drawn from a 2D Gaussian distribution. The color for each site alternates between the color maps. Parameters ---------- width: int Width of image in pixels. height: int Height of image in pixels. # num_cells: int The number of sites to create in the diagram. # mean_x: int The mean value to center the x-Gaussian distribution. # stdv_x: int The standard deviation of the x-Gaussian distribution, # mean_y: int The mean value to center the y-Gaussian distribution # stdv_y: int The standard deviation of the y-Gaussian distribution colorMap1: str, Label for seaborn color map. colorMap2: str, Label for seaborn color map. Returns ---------- None """ # Create variable instances image = Image.new("RGB", (width, height)) putpixel = image.putpixel imgx, imgy = image.size nx = [] ny = [] nr = [] ng = [] nb = [] # Define color palettes colors1 = sns.color_palette(colorMap1, 256) colors2 = sns.color_palette(colorMap2, 256) # Define sites and colors for each site for i in tqdm(range(num_cells)): nx.append(int(random.gauss(mean_x, stdv_x))) ny.append(int(random.gauss(mean_y, stdv_y))) if i % 2 == 0: temp_color = colors1[random.randrange(256)] else: temp_color = colors2[random.randrange(256)] nr.append(int(temp_color[0]*256)) ng.append(int(temp_color[1]*256)) nb.append(int(temp_color[2]*256)) # Create diagram for y in tqdm(range(imgy)): for x in range(imgx): dmin = math.hypot(imgx-1, imgy-1) j = -1 for i in range(num_cells): d = math.hypot(nx[i]-x, ny[i]-y) if d < dmin: dmin = d j = i putpixel((x, y), (nr[j], ng[j], nb[j])) # Save image image.save(f"Voronoi Diagram for Alayna.png", "PNG") # Define diagram parameters width = 2280 height = 1080 num_cells = 512 mean_x = 1280 stdv_x = 640 mean_y = 960 stdv_y = 480 colorMap1 = 'RdBu' colorMap2 = 'YlOrRd' # Make diagram generate_voronoi_diagram(width=width, height=height, num_cells=num_cells, mean_x=mean_x, stdv_x=stdv_x, mean_y=mean_y, stdv_y=stdv_y, colorMap1=colorMap1, colorMap2=colorMap2)
215ebe04fbe172062407fe9a69c2c22653c21520
pastra98/2d_evolution_sim
/pygame_pymunk_ver/genes.py
1,520
3.890625
4
from translators import Translator # Holds DNA and performs all relevant actions class Genome: """class that holds the dna with all it's genes. Also contains a Transcriptor object that is required for expressing gene functions. """ def __init__(self): """initializes dna and transcriptor used for reading and expressing genes. """ self.dna = [] def append_genes(self, genes): """appends multiple genes to the dna. """ for gene in genes: self.dna.append(gene) def transcript_genome(self): """Reads a gene, determines if it should be expressed and assigns it to a list, based on its type. This list represents the data of all genes of a given type. All gene types are then added to a dictionary. The transcriptor is then fed this dict. """ self.to_transcribe = {} for gene in self.dna: if gene.is_expressed: if gene.type in self.to_transcribe: self.to_transcribe[gene.type].append(gene) else: self.to_transcribe[gene.type] = [gene] self.translator = Translator(self.to_transcribe) # Describes a single gene class Gene: """class that describes a single gene """ def __init__(self, g_type, g_data): """initializes a gene of given type with given data """ self.type = g_type self.data = g_data self.is_expressed = True
6adcd05dc22f8c201be79f4e9f4caa26bcf2b7cc
scott-p-lane/Advent-of-Code-2019
/aoc_helpers/GridCoordinates.py
5,824
3.9375
4
''' Created on Feb 8, 2020 @author: scott-p-lane ''' from enum import Enum class GridOrientation(Enum): left = 0 up = 1 right = 2 down = 3 class TurnDirection(Enum): left = 0 right = 1 class GridCoordinates (object): """ Dictionary based implementation that represents grid coordinates and state for each coordinate. For certain types of grid related problems, this can be more optimal than a large, multi-dimensaional grid. Also useful in situations where grid sizes are not known up front. """ def __init__(self, defaultVal=0): """ Parameters ---------- defaultVal: optional Default value of any coordinate in the grid that was not explicitly assigned a value. (default is 0) """ self.grid = {} self.defaultVal = defaultVal #orientation is used to specify the direction we are facing/moving within the grid self.orientation = [GridOrientation.left, GridOrientation.up, GridOrientation.right,GridOrientation.down] self.currentOrientation = GridOrientation.up self.currentRow = 0 self.currentCol = 0 self.maxRow = 0 self.minRow = 0 self.maxCol = 0 self.minCol = 0 def changeOrientation(self,turnDirection: TurnDirection) -> GridOrientation: """ Changes orientation by accepting a direction (l or r) and turning "1 step" in that direction. Parameters: ------------ turnDirection : str Values are "l" (left), or "r" (right) """ orientationIndex = self.currentOrientation.value if turnDirection == TurnDirection.left: orientationIndex -= 1 else: orientationIndex += 1 if (orientationIndex > len(self.orientation) - 1): orientationIndex = 0 if (orientationIndex < 0): orientationIndex = len(self.orientation) - 1 self.currentOrientation = self.orientation[orientationIndex] return self.currentOrientation def __createkey__(self): """ Constructs a key for a coordinate using currentCol and currentRow values. """ return str(self.currentCol) + "," + str(self.currentRow) def createKey(self,colIndex,rowIndex): return str(colIndex) + "," + str(rowIndex) def processedCoordinate(self): """ Returns tuple in the form of (col,row,processed:bool) Which establishes the current coordinate and whether or not we have processed it before. Processing indicates that we explicitly performed an operation on it (like setting a value). """ vals = self.getCoordinate() vals[-1] = False gridkey = self.__createkey__() if gridkey in self.grid.keys(): vals[-1] = True return vals def setCoordinateValue(self,coordVal): """ Sets the current coordinate to the specified value. Returns coordinate value (see getCoordinate) """ gridkey = self.__createkey__() self.grid[gridkey] = coordVal return self.getCoordinate() def advance(self,distance = 1): """ Advances specified distance in current orientation (default distance is 1) and returns coordinate value (see getCoordinate) """ colOffset = 0 rowOffset = 0 if self.currentOrientation == GridOrientation.left: colOffset = -1 * distance if self.currentOrientation == GridOrientation.right: colOffset = distance if self.currentOrientation == GridOrientation.down: rowOffset = -1 * distance if self.currentOrientation == GridOrientation.up: rowOffset = distance self.currentCol += colOffset self.currentRow += rowOffset #See if we've expanded the grid if self.currentCol > self.maxCol: self.maxCol = self.currentCol if self.currentCol < self.minCol: self.minCol = self.currentCol if self.currentRow > self.maxRow: self.maxRow = self.currentRow if self.currentRow < self.minRow: self.minRow = self.currentRow return self.getCoordinate() def getCoordinate(self): return self.getCoordinateAt(self.currentCol,self.currentRow) def getCoordinateAt(self,colIndex,rowIndex): """ Returns tuple in the form of (col,row,val) """ gridval = self.grid.get(self.createKey(colIndex,rowIndex),self.defaultVal) retvals = [self.currentCol,self.currentRow,gridval] return retvals def rowCount(self): """ Returns absolute number of rows in the grid. """ return abs(self.minRow) + abs(self.maxRow) def columnCount(self): """ Returns absolute number of columns in the grid. """ return abs(self.minCol) + abs(self.maxCol) def renderGridRow(self,rowIndex,whitespaceSet=[]): """ Renders the specified row of a grid (first row is 0). Uses "whitespace set" such that any value at that coordinate in the whitespace set will simply be outputted as a space. """ rowstr = "" internalRowIndex = self.minRow + rowIndex for c in range(self.minCol,self.maxCol,1): gridval = self.grid.get(self.createKey(c,internalRowIndex),self.defaultVal) if gridval not in whitespaceSet: rowstr += str(gridval) else: rowstr += " " return rowstr
6b43604d2d995874639262c7995a22dde3bd5b41
eshulok/2.-Variables
/main.py
604
4.53125
5
#Variables are like nicknames for values #You can assign a value to a variable temperature = 75 #And then use the variable name in your code print(temperature) #You can change the value of the variable temperature = 100 print(temperature) #You can use variables for operations temp_today = 85 temp_yesterday = 79 #How much warmer is it today than yesterday? print(temp_today - temp_yesterday) #Tomorrow will be 10 degrees warmer than today print(temp_today + 10) #Or if you want to save the value for tomorrow's temperature, create a new variable temp_tomorrow = temp_today + 10 print(temp_tomorrow)
153ae3409ccd310cc3e426144aa7b47c22530615
sdcityrobotics/zoidberg_software
/OpenCV/practice/min_enclosingCircle/encloseCircle.py
805
3.515625
4
import numpy as np import cv2 # not finding center accurately in 3D-images img = cv2.imread('2d-circle.png', 0) og = cv2.imread('2d-circle.png', 0) cv2.imshow('original', og) # use threshold, findContours and moment functions ret, thresh = cv2.threshold(img, 127, 255, 0) im2, contours, hierarchy = cv2.findContours(thresh, 1, 2) cont = contours[0] # use data to edit center and radius moment = cv2.moments(cont) print(moment) # find center using minEnclosingCircle (x, y), radius = cv2.minEnclosingCircle(cont) # for printing/drawing center = (int(x), int(y)) radius = int(radius) cv2.circle(img, center, radius, (0, 255, 0), 10) # for reference print ("center = " + str(center)) print("radius = (" + str(x) + ", " + str(y) + ")") cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()
37499520285d5a5b5b8746d02a4fc06854627f13
riyaasenthilkumar/riya19
/factorial.py
270
4.125
4
num=7 num=int(input("Enter a number:")) factorial=1 if num<0: print("factorial does not exist for negative number") elif num==0: print("the factorial of0 is 1") else: for i in range (1,num+1): factorial=factorial*i print("the factorial of",num,"is",factorial)
972c5a7959d352a50d54e049b5d847610a62beab
pamsalesr/trybe-exercises
/EXERCISES/CS/BLOCO_33/DIA_1/fixacao.py
4,099
4.09375
4
import statistics # Exercicio 1 - Crie uma função que receba dois números e retorne o maior deles def biggest_number(a, b): if b > a: return b return a # Exercicio 2 - Calcule a média aritmética dos valores contidos em uma lista. def list_average(list): return statistics.mean(list) # Outra maneira: def average(numbers): total = 0 for number in numbers: total += number return total/len(numbers) # Exercicio 3 - Faça um programa que, dado um valor n qualquer, tal que n > 1 , imprima na tela um quadrado feito de asteriscos de lado de tamanho n . def print_square(size): for row in range(size): print(size*'*') # Exercicio 4 - Crie uma função que receba uma lista de nomes e retorne o nome com a maior quantidade de caracteres. def biggest_name(names): biggest = names[0] for name in names: if len(name) > len(biggest): biggest = name return biggest # Exercicio 5 - Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. # Crie uma função que retorne dois valores em uma tupla contendo a quantidade de latas de tinta a serem compradas e o preço total a partir do tamanho de uma parede(em m²). def cans_and_price(area): area_per_can = 54 can_price = 80 necessary_cans = area_per_can / area price = necessary_cans * can_price return f"Necessary cans: {necessary_cans} | Price: {price}" # Exercicio 6 - Crie uma função que receba os três lado de um triângulo e informe qual o tipo de triângulo formado ou "não é triangulo" , caso não seja possível formar um triângulo. def triangle_type(s1, s2, s3): is_triangle = ( s1 + s2 > s3 and s2 + s3 > s1 and s1 + s3 > s2 ) if not is_triangle: return 'não é triângulo' elif s1 == s2 == s3: return 'Triângulo Equilátero' elif s1 == s2 or s2 == s3 or s1 == s3: return 'Triângulo Isósceles' return 'Triângulo Escaleno' # BONUS # Exercicio 1 - Dada uma lista, descubra o menor elemento. Por exemplo, [5, 9, 3, 19, 70, 8, 100, 2, 35, 27] deve retornar 2 . def smallest_number(list): smallest = list[0] for number in list: if number < smallest: smallest = number return smallest # Exercicio 2 - Faça um programa que, dado um valor n qualquer, tal que n > 1 , imprima na tela um triângulo retângulo com n asteriscos de base. def print_triangle(size): for row in range(size): print((row + 1)*'*') # Exercicio 3 - Crie uma função que receba um número inteiro N e retorne o somatório de todos os números de 1 até N . def somatory_of(number): somatory = 0 for index in range(number): somatory += index + 1 return somatory # Exercicio 4 - Um posto está vendendo combustíveis com a seguinte tabela de descontos: # Álcool: # - Até 20 litros, desconto de 3% por litro; # - Acima de 20 litros, desconto de 5% por litro. # Gasolina: # - Até 20 litros, desconto de 4% por litro; # - Acima de 20 litros, desconto de 6% por litro. # # Escreva uma função que receba o número de litros vendidos, o tipo de combustível (codificado da seguinte forma: A - álcool, G - gasolina), # e retorne o valor a ser pago pelo cliente, sabendo-se que o preço do litro da gasolina é R$ 2,50, e o preço do litro do álcool é R$ 1,90. def gas_total_price(quantity, type): gasoline_price = 2.5 gasoline_4_descount = gasoline_price * 0.96 gasoline_6_descount = gasoline_price * 0.94 alcohol_price = 1.9 alcohol_3_descount = alcohol_price * 0.97 alcohol_5_descount = alcohol_price * 0.95 total = 0 if type == 'G': if quantity < 20: total = quantity * gasoline_4_descount else: total = quantity * gasoline_6_descount elif type == 'A': if quantity < 20: total = quantity * alcohol_3_descount else: total = quantity * alcohol_5_descount return total
1b871489089ef44c5e684c1227e9698a276f0d06
PhilippeCarphin/env-tools
/libexec/env-tools/envtool.py
6,095
4.0625
4
#!/usr/bin/env python3 ''' This class takes the environment and represents it in a way that can be specified by the user. If no specification is given, the representation will be equivalent to the os.environ dictionary. The user ''' import os import sys import json import subprocess from pprint import pprint def make_decorator(dictionary): ''' Creates a decorator that adds the function to a dictionary under the keys listed in args ''' class env_decorator: def __init__(self, args): self.args = args def __call__(self, f): for var in self.args: dictionary[var] = f return f return env_decorator # Functions taking string values and returning string, lists or dictionaries # Decorating a function with this decorator with argument list_of_vars # will register that function as the parser for the values of the variables in # the list list_of_vars parsers = {} parses = make_decorator(parsers) # Functions taking variable name and value and returning string stringizers= {} stringizes = make_decorator(stringizers) # Functions taking variable name and value and returning string pretty_stringizers = {} pretty_stringizes = make_decorator(pretty_stringizers) ''' Dictionnary of comparison functions ''' # Functions taking object before and object after and returning a string comparers = {} compares = make_decorator(comparers) updaters = {} updates = make_decorator(updaters) class EnvWrapper: ''' Class that encapsulates a dictionnary of environment variables The keys are variable names and the values are the parsed string values of the environment variables as defined by the 'processor' functions ''' def __init__(self, d=None, representation=None): ''' Create an instance from an already made dictionary or from the environment dictionary from os.environ. ''' if representation: self.env=representation elif d: self.env=self.decode_environment_dict(d) else: self.env = self.decode_environment_dict(os.environ) def __getitem__(self, key): return self.env[key] def __iter__(self): return iter(sorted(self.env)) def __str__(self): return str(self.env) def get_str(self, key): '''Returns a string representing the environment variable. This string may or may not be equal to the string value of the variable using function registered as the 'stringizer' for that vaiable ''' if key in self.env: if key in stringizers: return key + '=' + stringizers[key](self.env[key]) else: return key + '=' + str(self.env[key]) else: return key + ' is not in environment' def get_pretty_str(self, key): ''' Get a pretty representation of the variable ''' if key in self.env: if key in pretty_stringizers: return key + '=\n' + pretty_stringizers[key](self.env[key]) else: return key + '=' + str(self.env[key]) else: return key + ' is not in environment' def json_dumps(self): ''' Dump the dictionary of variabl and their parsed values ''' return json.dumps(self.env) def pretty(self): ''' Return a string formed by all the pretty printed variables ''' return '\n'.join(self.get_pretty_str(key) for key in self) def to_file(self, filename): with open(filename, 'w') as f: json_dump(f, self.env, indent=4) @staticmethod def decode_environment_dict(d): ''' Transform the os.environ dictionary to the format that I use: Each variable can have a function that parsed the string value into a list or dictionary or what ever else you want. ''' representation = {} for var, value in d.items(): if var in parsers.keys(): representation[var] = parsers[var](value) else: representation[var] = d[var] return representation @classmethod def from_environment_dict(cls, d=None): if not d: d = os.environ return cls(representation=cls.decode_environment_dict(d)) @classmethod def from_file(cls, filename): with open(filename, 'r') as f: representation = json.load(f) return cls(representation=representation) def get_declaration(self, var): real_value = self.get_str if var in stringizers: real_value = stringizers[var](self.env[var]) else: real_value = str(self.env[var]) return f'{var}="{real_value}"' def get_unsetting(self, var): return f'unset {var}' def get_change(self, var, before, after): if isinstance(before, list): if after: new_elements = set(after) - set(before) return f"{var}=\"${var}:{':'.join(new_elements)}\"" else: return f'{var}=""' elif var in stringizers: return f'{var}="{stringizers[var](after)}"' else: return f'{var}="{after}"' ''' ================================================================================ Definitions of the processing and string functions For any variable, you can define a function that parses it (taking a string to any type of object) For any variable, you can define a function that will take a variable name and a ivalue and return a string. Same thing for the pretty_stringizes ================================================================================ ''' ''' Dictionaries with accompanying decorators used to register the functions that process variables from string values and puts them back as strings in a pretty way or in a normal way''' def get_command(args): env = EnvWrapper.from_environment_dict() if args.posargs: for var in args.posargs: print(env.get_pretty_str(var)) else: print(env.pretty())
79ee4de72e1b5b309fba075c3256a246519730d5
sshantel/running
/pace_converter.py
1,168
3.71875
4
import re import math def km_to_mi(km): miles = km / 1.609 return miles def time_to_seconds(run_time): components = run_time.split(":") hours = int(components[0]) minutes = int(components[1]) seconds = int(components[2]) total_s = seconds + (minutes*60) + (hours*3600) return total_s def clean_distance_to_mi(dist): clean = re.sub('[^0-9]', '', dist) clean = km_to_mi(int(clean)) return clean def min_float_to_pace(mins): remainder = mins - (mins//1) return remainder*60 def km_to_mi_per_min(): run1 = "00:47:44" run2 = "00:56:28" run1dist = "10k" run2dist = "10K" run1dist = clean_distance_to_mi(run1dist) run2dist = clean_distance_to_mi(run2dist) run1_s = time_to_seconds(run1) run2_s = time_to_seconds(run2) sec_per_mi = run1_s / run1dist print(sec_per_mi) min_per_mi = sec_per_mi /60.0 print(min_per_mi) min_per_mi_sliced = str(min_per_mi) minutes = min_per_mi_sliced.split('.')[0] seconds=(min_float_to_pace(min_per_mi)) km_to_mi(10) return(f'your average pace was {minutes}:{seconds} a mile') print(km_to_mi_per_min())
021a7b285b13f08e7f68188fd414d75681a5458b
triplingual/mypythonthehardway
/ex33_mod1.py
736
3.953125
4
import random def looper( param0, param1 ): """Loops""" i = 0 numbers = [] while i < param0: if ( i < ( 2 * param1 ) ): print "At the top i is %d" % i numbers.append( i ) i = i + param1 if ( i < ( 2 * param1 + 1 ) ): print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers numbers = looper( 6, 1 ) print "The numbers: " for num in numbers: print num limit = 1000 increment = 10 numbers = looper( limit, increment ) # one way to deal with a large set print "The numbers: " for num in numbers: slash = random.choice( '/\\\|' ) if num > ( limit - ( 2 * increment ) ) or num < 2 * increment : print num elif num == ( limit - ( 2 * increment ) ): print slash else: print slash,
96888266eb13cc5801d717298e39dfc24d0eb0c1
Amritha-Venkat/Exercises
/majority.py
293
3.703125
4
def majority(nums): freq = {} for item in nums: if (item in freq): freq[item] += 1 else: freq[item] = 1 # print(freq) inverse = [(value, key) for key, value in freq.items()] return max(inverse)[1] print(majority([3,2,3]))
8eb394b7719ee9f31c69697e82283ab1e643d7c2
Amritha-Venkat/Exercises
/donuts.py
224
3.59375
4
def donuts(count): # +++your code here+++ if count > 10: return "Number of donuts: many" else: return "Number of donuts: ", count if __name__=='__main__': print (donuts(5)) print (donuts(23))
bb11827268e6075e102b96fc62c012da067538d8
Amritha-Venkat/Exercises
/PalindromeLeetCode.py
745
3.84375
4
# def isPalindrome(x): # """ # :type x: int # :rtype: bool # """ # y = str(x) # rev = "" # for i in y: # rev = i + rev # if rev == str(x): # return True # else: # return False # print(isPalindrome(-121)) def isPalindromesigned(x): ans = "" ans1 = "-" a = 0 a1 = 0 if x >= 0: while x > 0: rem = x % 10 x = x // 10 ans = ans + str(rem) a += int(ans) return a elif x < 0: while abs(x) > 0: rem = abs(x) % 10 x = abs(x) // 10 ans1 = ans1 + str(rem) a1 += int(ans1) return a1 print(isPalindromesigned(-123))
72be40266fe7adf123de0b20fbbed9bb66dab7f1
Amritha-Venkat/Exercises
/TwoSum.py
1,003
3.5625
4
# indexes = [] # def twoSum(nums, target,partial = []): # """ # :type nums: List[int] # :type target: int # :rtype: List[int] # """ # # total = 0 # for i in range(len(partial)): # total = total + partial[i] # # total = sum(partial) # if total == target: # for index in range(len(partial)): # indexes.append(index) # # print(indexes) # # return indexes # if total >= target: # return 0 # for i in range(len(nums)): # n = nums[i] # remaining = nums[i+1:] # twoSum(remaining,target,partial + [n]) # # return indexes # print(twoSum([2,7,11,14],9)) def twoSum( nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i print(twoSum([2,7,11,14],13))
d4db08e217687102d113da64f1ec64ae201b810a
YoungLeeNENU/Online-Judge
/leetcode/algorithms/easy/other-1.py
332
3.546875
4
# -*- coding: utf-8 -*- #!/usr/bin/python class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ bin_str = bin(n)[2:] return len(''.join(bin_str.split('0'))) if __name__ == '__main__': solution = Solution() print solution.hammingWeight(11)
c00908936aa61fb0d76ec4677a2eb0f57d497c99
YoungLeeNENU/Online-Judge
/leetcode/algorithms/easy/math-1.py
565
3.734375
4
# -*- coding: utf-8 -*- #!/usr/bin/python class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ result = [] for i, x in enumerate(n * "1"): fizzBuzz = "" if (i + 1) % 3 == 0: fizzBuzz += "Fizz" if (i + 1) % 5 == 0: fizzBuzz += "Buzz" if len(fizzBuzz) > 0: result.append(fizzBuzz) else: result.append(str(i + 1)) return result if __name__ == '__main__': solution = Solution() print solution.fizzBuzz(16)
152ff555d31467febe3612547edf0518408f1b5d
oun1982/gitrepo
/test2.py
1,109
3.53125
4
__author__ = 'oun1982' ''' import time start_time = time.time() number = int(input("enter your number : ")) for i in range(1,1000001): print("%d * %d = %d" %(number,i,(number * i))) print("---%s seconds ---"%(time.time() - start_time)) tup1 = (12,13,14,15.6) tup2 = ('Asterisk','linux',1982) print (tup1) print (tup2) dict1={'oun1982':'1','pongsakon':'2'} print (dict1) ''' ''' var = 100 if var < 200: print ("Expression value is less than 200" ) if var == 150: print ("which is 150") elif var == 100: print ("which is 100") elif var == 50: print ("which is 50") elif var < 50: print ("Expression value is less than less than 50" ) else: print ("Could not find true expression") print ('Good Bye') strr = 'Pongsakon Tongsook' for name in strr: print (name) for row in range(1,10): for col in range(1,10): prod = row * col if prod < 10: print (' ',end = '') print(row * col,' ',end =' ') print() ''' combs = [] for x in [1,2,3]: for y in [7,8,9]: if x != y: combs.append((x,y)) print(combs)
cb2aee32edfaf7cc00c8d4fa18ff4f6b6684d16f
oun1982/gitrepo
/TryExcept.py
646
3.953125
4
__author__ = 'oun1982' ''' try: fh = open("myfile", "w") fh.write("This is my file exception handling!!!") except IOError: print("Error : Can\'t find file ore read data") else: print("Write content in the file successfully") fh.close() while True: try: n = int(input("Please enter an interger :")) break except ValueError: print("No valid value! Please try again...") print("Great ,you sucessfully enter an integer!") ''' def temp_convert(var): try: return int(var) except ValueError as Args: print("Argument doesn't contain number\n", Args.args) temp_convert("xyz")
1ca788b5d83a3da61df5ec82a13dc7b6c187b177
JH-Lam/deep-learning-gluon
/1.gradient_decend.py
712
3.515625
4
import numpy as np import matplotlib.pyplot as plt x = np.random.random((100, 2)) init_w = np.array([[1.4], [0.9]]) init_b = 0.2 y = np.dot(x, init_w) + init_b # y = wx + b w = np.random.randn(2, 1) b = 0 # loss = ((wx + b) - y) ** 2 # d(loss)/dw = 2(wx + b - y) * x # d(loss)/db = 2(wx + b - y) # w = w - lr * loss_gradient learning_rate = 0.01 epochs = 100 a = [] for e in range(epochs): w = w - learning_rate * 2 * np.dot(x.T, (np.dot(x, w) + b - y)) b = b - learning_rate * 2 * (np.dot(x, w) + b - y).sum() a.append(((np.dot(x, w) + b - y) ** 2).sum()) print(w, b, a[-1]) plt.plot(np.arange(epochs), a) plt.xlabel('epoch') plt.ylabel('loss') plt.show()
ccf67c2b2625e3ae6d1acc1e7cca475f8b3e5f67
Xtreme-89/Python-projects
/main.py
1,424
4.1875
4
<<<<<<< HEAD is_male = True is_tall = False if is_male and is_tall: print("You are a tall male") elif is_male and not is_tall: print("You are a short male") elif not is_male and is_tall: print("You are a tall female") else: print("You are a short female") #comparisons def max_num(num1, num2, num3): if num1 >= num2 and num2 >= num3: return num1 if num2 >= num1 and num2 >= num3: return num2 if num3 >= num1 and num3 >= num2: return num3 else: print("WTF u siked my programme") num1 = int(input("Type your first number ")) num2 = int(input("Type your second number ")) num3 = int(input("Type your third number ")) print(str(max_num(num1, num2, num3)) + " is the highest number") #Guessing Game secret_word = "Giraffe" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input("Guess the secret word: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print("Out of guesses - you have no access") else: print("Well done, you now have full access to the high order of variables.") #For loops friends = ["Jim", "Karen", "Emma", "Alexandria", "Liz", "Ellie"] for friend in friends: print (friend) ======= print(3 +4.5) >>>>>>> ab1d0e7820f4a8f97b5b83024948417c6bbadd0b
3f372fc00793c1f2134c4fd0d50ff1a8e38aaf3a
senmelda/PG1926
/problemSet_1.py
390
3.9375
4
def fizzbuzz(n) : result = [] for x in range(1,n+1): if x % 3 == 0 and x % 5 == 0 : result.append("fizz buzz") elif x % 3 == 0 : result.append("fizz") elif x % 5 == 0 : result.append("buzz") else : result.append(str(x)) return result def main() : print(','.join(fizzbuzz(100))) main()
d7f3433ac5bda1d9eaae98463d9154741a02ef86
OlegFedotkin/python
/task6.py
1,159
3.796875
4
#6) Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который результат спортсмена составит не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. dist_in_first_day = int(input('Введите дистанцию первого дня тренировок ')) dist_in_last_day = int(input('Введите дистанцию последнего дня тренировок ')) day_count = 1 while dist_in_first_day < dist_in_last_day: dist_in_first_day *= 1.1 day_count += 1 print(f'На {day_count}-й день спортсмен достиг результата — не менее {dist_in_last_day} км')
909eb38479db65819a09f19f15a7053e3ad5450e
derrick20/AI-Projects
/1-Searches/BFS, DFS, DLS/word_ladder_bfs_liang_d.py
3,160
3.9375
4
import collections def main(): try: file = open('words.txt', 'r') words = set([line.strip() for line in file]) graph = {} for word in words: graph[word] = Node(word) for adjacent in generate_adj(word): if adjacent in words: graph[word].add_neighbor(adjacent) # add this new neighbor (a string) #print(graph) start = input('Starting 6-letter word: ') goal = input('Goal word: ') if len(start) != 6 or len(goal) != 6:# or start not in graph or goal not in graph: print('Word(s) are invalid') exit() BFS(start, goal, graph)#''' except FileNotFoundError: print('words.txt was not found') exit() def BFS(start, goal, g): explored = set([start]) # MUST HAVE INITIAL!!!! frontier = collections.deque([start]) graph = g while len(frontier) > 0: current = frontier.popleft() # current is just a string if current == goal: print_path(current, graph) return # we use the graph to give us more strings for future 'currents' for state in graph[current].get_neighbors(): # we cannot do a for each because that doesn't modify the graph if state not in explored: graph[state].set_pred(current) #print(graph) #print (state.get_pred()) explored.add(state) frontier.append(state) # added as a string, because this makes it more convenient here. print('No Solution') # later we for print path we will have to use graph[state_name] a bunch however def print_path(name, graph): # repeatedly gets pred and prints path = collections.deque() node = graph[name] while node.get_pred() != '': #print(node) path.appendleft(node.get_value()) node = graph[node.get_pred()] path.appendleft(node.get_value()) # need one more because the start's pred is '' but it didn't get printed print('The shortest path: ' + ', '.join(path)) print('The number of steps: ' + str(len(path))) class Node: def __init__(self, key): # the key and predecessors are strings, since the graph dict is a look up table self.value = key self.neighbors = [] self.predecessor = '' def __repr__(self): return self.value + ': ' + self.predecessor def add_neighbor(self, neighbor): self.neighbors.append(neighbor) def get_neighbors(self): return self.neighbors def set_pred(self, pred): # set predecessor self.predecessor = pred def get_pred(self): return self.predecessor def get_value(self): return self.value def generate_adj(word): l = len(word) adj = [] for i in range(l): # O(25 * 6) = O(150) for c in 'abcdefghijklmnopqrstuvwxyz': if c != word[i]: # so that you don't put in the own word adj.append(word[:i] + c + word[i + 1:]) return adj if __name__ == '__main__': main()
214ea4ae4b8cc40769a224af589a5b077edbe490
derrick20/AI-Projects
/0-Python Tasks/eleven_liang_d.py
170
3.546875
4
def eleven(): a,b = [int(x) for x in input().split()] list = [] for i in range(a, b + 1): list.append(i**2 - 3*i + 2) print(list) eleven() exit()
c02b328003add7fe7ac4c0b9c0719a58b4c1f0a4
derrick20/AI-Projects
/0-Python Tasks/three_liang_d.py
153
3.84375
4
def three(): str = input() ret = '' for i in range(len(str)): if i % 2 == 0: ret += str[i] print(ret) three() exit()
742f27d0c4a7d0542829a6f58942a5a6b611302c
derrick20/AI-Projects
/0-Python Tasks/two_liang_d.py
220
3.8125
4
def two(): n = int(input()) fib = [] fib.append(1) for i in range(1, n): if i <= 3: fib.append(i) else: fib.append(fib[i-1] + fib[i-2]) print(fib) two() exit()
026da2eb5046eedf726f209933d258b6dc74d293
derrick20/AI-Projects
/0-Python Tasks/twenty_liang_d.py
316
3.6875
4
def twenty(): str = input() ret = True for c in str: if c not in '01': ret = False print(int(str, 2)) '''value = 0 current = 0 if ret: for c in str[::-1]: value += (2**current) * int(c) current += 1''' # unnecessary way twenty() exit()
b387c6daa15dc9ad3c696b2ff2bbe115c03472f6
webclinic017/TFS
/tfs/utils/charts.py
6,699
3.59375
4
import matplotlib.pyplot as plt import seaborn as sns from matplotlib.ticker import FuncFormatter import pdb class Chart(object): pass class BulletGraph(Chart): """Charts a bullet graph. For examples see: http://pbpython.com/bullet-graph.html """ def draw_graph(self, data=None, labels=None, axis_label=None, title=None, size=(5, 3), formatter=None, target_color="gray", bar_color="black", label_color="gray"): """ Build out a bullet graph image Args: data = List of labels, measures and targets limits = list of range valules labels = list of descriptions of the limit ranges axis_label = string describing x axis title = string title of plot size = tuple for plot size palette = a seaborn palette formatter = matplotlib formatter object for x axis target_color = color string for the target line bar_color = color string for the small bar label_color = color string for the limit label text Returns: a matplotlib figure """ # Must be able to handle one or many data sets via multiple subplots if len(data) == 1: fig, ax = plt.subplots(figsize=size, sharex=True) else: fig, axarr = plt.subplots(len(data), figsize=size, sharex=True) # Add each bullet graph bar to a subplot index = -1 for idx, item in data.iterrows(): index += 1 ticker = item['ticker'] # set limits graph_data, prices = self._normalize_data(item) # Determine the max value for adjusting the bar height # Dividing by 10 seems to work pretty well h = graph_data[-1] / 10 # Reds_r / Blues_r palette = sns.color_palette("Blues_r", len(graph_data) + 2) # Get the axis from the array of axes returned # when the plot is created if len(data) > 1: ax = axarr[index] # Formatting to get rid of extra marking clutter ax.set_aspect('equal') ax.set_yticklabels([ticker]) ax.set_yticks([1]) ax.spines['bottom'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=False) prev_limit = 0 n_items = len(graph_data) corr_factor = len(graph_data) / 2 for idx2, lim in enumerate(graph_data): color_index = int(abs( abs(n_items - corr_factor - idx2) - corr_factor)) # Draw the bar ax.barh([1], lim - prev_limit, left=prev_limit, height=h, color=palette[color_index]) prev_limit = lim rects = ax.patches """ prev_limit = limits[0] n_items = len(limits) corr_factor = len(limits) / 2 for idx2, lim in enumerate(limits): color_index = int(abs( abs(n_items - corr_factor - idx2) - corr_factor)) # Draw the bar # pdb.set_trace() ax.barh([1], lim - prev_limit, left=prev_limit, height=h, color=palette[color_index + 2]) # pdb.set_trace() prev_limit = lim rects = ax.patches """ # The last item in the list is the value we're measuring # Draw the value we're measuring # ax.barh([1], item['close'], height=(h / 3), color=bar_color) # Need the ymin and max in order to make sure the target marker # fits ymin, ymax = ax.get_ylim() ax.vlines( prices['close'], ymin * .9, ymax * .9, linewidth=1.5, color=target_color) # Now make some labels if labels is not None: for rect, label in zip(rects, labels): height = rect.get_height() ax.text( rect.get_x() + rect.get_width() / 2, -height * .4, label, ha='center', va='bottom', color=label_color) if formatter: ax.xaxis.set_major_formatter(formatter) if axis_label: ax.set_xlabel(axis_label) if title: fig.suptitle(title, fontsize=14) fig.subplots_adjust(hspace=0) # plt.show() return fig def _normalize_data(self, data): """Normalize data. Scale all data between 0 and 1 and multiply by a fixed value to make sure the graph looks great. :param data: the data that needs to be normalized :return: normalized indicators and prices """ bandwith = 0.1 mult_factor = 100 # normalize indicators graph_data = [data['55DayLow'], data['20DayLow'], data['20DayHigh'], data['55DayHigh']] extra_bandwith = data['55DayHigh'] * bandwith graph_data.insert(0, data['55DayLow'] - extra_bandwith) graph_data.insert( len(graph_data), graph_data[len(graph_data) - 1] + extra_bandwith) scaled_data = [] max_distance = max(graph_data) - graph_data[0] scaled_data.append(0) # numbers = graph_data[1 - len(graph_data):] sum_scaled_values = 0 for i, d in enumerate(graph_data[1:]): sum_scaled_values += (graph_data[i + 1] - graph_data[i]) / max_distance scaled_data.append(sum_scaled_values) scaled_data = [i * mult_factor for i in scaled_data] # normalize prices prices = {} close_price = data['close'] scaled_close_price = (close_price - min(graph_data)) / \ (max(graph_data) - min(graph_data)) prices['close'] = scaled_close_price * mult_factor return scaled_data, prices
b2624f634c7f35d888bc6bca0f7638fe34c74e90
vishalsodani/aoc2019
/day1/part2.py
245
3.640625
4
total = 0 with open('input.txt') as fp: for input in fp: total += (int(input) / 3) - 2 next_input = (int(input) / 3) - 2 while next_input > 0: next_input = (next_input / 3) - 2 if next_input > 0: total += next_input print(total)
da5b4d85ab8ca08a4d0b4a38a3afcb80159d42b9
segunfamisa/algorithms
/hackerrank/warmup/compare_the_triplets.py
384
3.796875
4
''' Compare the triplets https://www.hackerrank.com/challenges/compare-the-triplets ''' def Solution(): A = map(int, raw_input().split()) B = map(int, raw_input().split()) scoreA = 0 scoreB = 0 for i in range(len(A)): if A[i] > B[i]: scoreA += 1 elif A[i] < B[i]: scoreB += 1 print scoreA, scoreB Solution()
746a785edf8a8d9c205e389fd02ab93ac1b237a4
sobriquette/python-gmaps-tsp
/TSP/PrimMST.py
2,917
3.6875
4
from TSP.Vertex import Vertex from TSP.Graph import Graph def print_mst(parent, graph, places): """ Prints the constructed MST along with labels of our destinations """ num_vertices = graph.num_vertices adj_matrix = graph.adjacency_matrix print("Edge \tWeight \tPlace") for i in range(1, num_vertices): print( parent[i], "-", i, "\t", adj_matrix[i][parent[i]], " ", \ places[i - 1], "to ", places[i] ) def find_min_key(keys, mstSet, num_vertices): """ Finds vertex with minimum distance value given the set of vertices not included in the MST """ # Initialize min value min_key = float('inf') for vertex in range(num_vertices): if keys[vertex] < min_key and vertex not in mstSet: min_key = keys[vertex] min_index = vertex return min_index def prim_mst(graph): """ Builds a minimum spanning tree using Prim's Algorithm using a graph represented as an adjacency matrix. Time complexity: O(V^2) Space: O(V^2) """ num_vertices = graph.num_vertices adj_matrix = graph.adjacency_matrix keys = [float('inf')] * num_vertices # Stored key values to pick minimum weight edge in cut parent = [None] * num_vertices # This will store the constructed MST keys[0] = 0 # This will be picked as the first vertex mstSet = set() parent[0] = -1 # First node is root for cout in range(num_vertices): # Pick the minimum distance vertex from vertices not yet processed curr_source = find_min_key(keys, mstSet, num_vertices) # Put the minimum distance vertex in the MST mstSet.add(curr_source) # Update distance value of adjacent vertices of chosen vertex... # only if the new distance is less than the current distance, # and teh vertex is not already in the MST for neighbor in range(num_vertices): # adj_matrix[curr_source][neighbor] is non-zero only for adjacent vertices of m # mstSet[neighbor] is False for vertices not yet in the MST # Update the key only if adj_matrix[curr_source][neighbor] is smaller than keys[neighbor] if adj_matrix[curr_source][neighbor] > 0 and neighbor not in mstSet and \ keys[neighbor] > adj_matrix[curr_source][neighbor]: keys[neighbor] = adj_matrix[curr_source][neighbor] parent[neighbor] = curr_source return parent def dfs_mst(mst): """ Performs depth-first traversal on the minimum spanning tree. But since the MST is represented as a list, we turn it back into a graph first. """ g = Graph() for i in range(1, len(mst)): g.add_edge(mst[i], i) neighbors = [g.vertex_dict[0]] # stack that holds all adjacent nodes of a vertex visited = set() # tracks which vertices we've seen visited.add(0) # start with source vertex result = [0] while len(neighbors) > 0: adjacent_vertices_for_v = neighbors.pop() for v in adjacent_vertices_for_v: if v not in visited: neighbors.append(g.vertex_dict[v]) visited.add(v) result.append(v) return result
4675dd3b798295d4a5ab3d1a0a8d6021cc7a169c
zacharytower/continued_fraction
/root_period.py
929
3.890625
4
import math def root_period(n, b = 0, d = 1, original = 0, counter = 0, period_list = []): ''' Returns the period of sqrt(n). -- in the form [a0, a1, a2, ... an] i.e. root_period(7) = [2,1,1,1,4], as sqrt(7) = [2;(1,1,1,4)] b is what is added to n, and d is the denominator for both n and b. This recursive function is awkwardly written, but it works and is fairly fast. ''' current_val = (math.sqrt(n) + b) / d a = math.floor(current_val) period_list.append(int(a)) if current_val == original: return period_list if original == 0: original = math.sqrt(n) + a if counter != 0: # we now have to take the reciprocal of the fraction: return root_period(n = n, b = d * a - b, d = (n - (b - d * a) ** 2) / d, original = original, counter = counter + 1, period_list = period_list) return root_period(n = n, b = a, d = n - a ** 2, original = original, counter = counter + 1, period_list = period_list)
1c552223e3c23ccbbb496e402b7d49ab11f63650
hailinlwang/Sorting-Algorithms
/complex.py
1,214
4.09375
4
class complex: def __init__(self,real,imag): #__init__ is special and must be spelled this way #it allows us to say "x=complex(0,1)" to create a complex number self.re=real self.im=imag # note: no return value (rare exception to our rule!) def setRe(self,X): self.re=x return True def setIm(self,x): self.im=x return True def setDesc(self,x): self.desc=x return True def getRe(self): return self.re def getIm(self): return self.im def getDesc(self): return self.desc def dispStr(self): return str(self.re)+"i "+str(self.im) def __add__(self,other): # __add__ is special syntax that lets us use the + operator # for our class; this is called "OVERLOADING" the + operator return complex(self.re+other.re,self.im+other.im) def __mul__(self,other): return complex(self.re*other.re,self.im*other.im) def main(): a = complex(1,1) b = complex(2,2,) print((a+b).dispStr()) a.setDesc("this is a complex number representing something important") b.setDesc("this is irrelevant") print(b.getDesc()) print((a*b).dispStr()) return True main()
afd7d15a6a033f8dfd23391391e0eca08be65ec6
HanqingXue/Leetcode
/samsung/stack.py
532
3.875
4
class Stack(object): def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): if self.stack == []: raise IndexError('pop from empty stack') else: del self.stack[-1] def top(self): return self.stack[-1] def peek(self): return self.stack[-1] def size(self): return self.stack.__len__() def isEmpty(self): return True if self.stack == [] else False
3b6c35f55899dbc8819e048fdbdebb065cd01db1
brunomatt/ProjectEulerNum4
/ProjectEulerNum4.py
734
4.28125
4
#A palindromic number reads the same both ways. #The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. products = [] palindromes = [] three_digit_nums = range(100,1000) for k in three_digit_nums: for j in three_digit_nums: products.append(k*j) def check_palindrome(stringcheck): #only works for 6 digit numbers which is all we need for this exercise if str(stringcheck)[0] == str(stringcheck)[-1] and str(stringcheck)[1] == str(stringcheck)[-2] and str(stringcheck)[2] == str(stringcheck)[-3]: palindromes.append(stringcheck) for num in products: check_palindrome(num) print(max(palindromes))
dc0890ecd390a3379156a55201832cb81ad0c1e2
AlexDikelsky/cellular-automata
/langton_ant/__main__.py
1,010
3.75
4
import ant import grid import time size = int(input("How large a grid do you want? : ")) print("Do you want to step through the positions, or just see a specific position?") step_through = int(input("Type 1 to step, or 0 to jump to a point: ")) if step_through == 0: steps = int(input("How many steps? : ")) i = 0 else: print("Press enter repeatedly to continue, or type 'q' to exit") steps = -1 i = 0 traveler = ant.Ant() plot = grid.Grid(size) done = False while not done: x = traveler.get_x() y = traveler.get_y() #print(x, y, traveler.get_direction()) if plot.get_color(x, y) is 0: traveler.right() else: traveler.left() plot.change_color(x, y) traveler.forward() if step_through == 1: if input() == "q": done = True else: print(plot) else: if i > steps: done = True i += 1 #print(x, y, traveler.get_direction()) #time.sleep(0.075) print(plot)