blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0f9ea06acf0bedd8551ac0107c30784b8f424efc
zejacobi/ProjectEuler
/Solutions/0038.py
2,309
4.1875
4
""" # Problem #38: Pandigital Multiples Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ..., n) where n > 1? """ from Lib.Helpers import contains_all_numbers # One key thing to note is that we actually only care about numbers that start with 9... # Anything else, and it _MUST_ be smaller than the example 918273645, which I know for a fact # isn't the answer (I guessed it) # This cuts down our solution space by a factor of 10. We also know it can't contain zero # (because the multplication by one, which cuts things down even further. Also, it cannot contain # more than one nine, or actually, more than any number once. This further cuts things down. # There's something like 80 possible numbers below 987 and 800 below 9876 # There's one last thing; as our main number gets bigger, the amount of factors we can try # gets smaller. There's no way we'll succeed with a number greater than 4 digits, given that # n MUST be greater than 1 numbers = [] def recursively_find_allowable_bases(current): if current not in numbers: numbers.append(int(current)) if len(current) < 4: for i in range(1, 9): str_i = str(i) if str_i not in current: recursively_find_allowable_bases(current + str_i) recursively_find_allowable_bases('9') # 401 numbers at this point; that's very reasonable. factors = [1, 2] highest = 918273645 # I honestly don't see much point in being clever here. We're doing 8 * 401 operations. while len(factors) < 9: for n in numbers: pan = ''.join([str(n * f) for f in factors]) if contains_all_numbers(pan, [1, 2, 3, 4, 5, 6, 7, 8, 9]) and int(pan) > highest: highest = int(pan) factors.append(factors[-1] + 1) print(highest) # yeah that took basically no time
6b434b661d84c4503318c5cda497bff6a51555c8
AnthonyLzq/Python_course
/class_05/agenda.py
2,362
3.828125
4
class Agenda(): def __init__(self): self.__conctacts = { 'Anthony': ['Luzquiños', '936962826', '[email protected]'], 'Rubén': ['Ricapa', '987654321', '[email protected]'] } def show_conctacts(self): print('\nContact list:') for position, key in enumerate(self.__conctacts): print(position + 1, key, self.__conctacts[key]) print() def delete_contact(self): name = input('Type a name to delete the contact: ') self.__conctacts.pop(name) self.show_conctacts() def search_contact(self): name = input('Type a name to search: ') if name in self.__conctacts: print('\nContact found:') print(name, self.__conctacts[name]) else: print('The searched contact does not exist') print() def add_contact(self): name = input('Type a name: ') lastname = input('Lastname: ') cell = self.__verify() mail = input('Email: ') self.__conctacts[name] = [lastname, cell, mail] self.show_conctacts() def __verify(self): while True: try: number = int(input('Type a cellphone number: ')) except ValueError: print('That\'s not a valid cellphone number.') else: code_validation = self.__nine_numbers(number) if code_validation == 1: return number elif code_validation == 2: print('Error! The cellphone must begin with nine') elif code_validation == 3: print('Error! The number must have 9 digits.') else: print('Error! The number you\'ve just typed neither has 9 ' + 'digits nor begin with nine.') def __nine_numbers(self, number): # Codes # 1 -> valid number # 2 -> it doesn't begin with 9, but it has 9 numbers # 3 -> it begins with 9, but it doesn't have 9 numbers number = str(number) if len(number) == 9 and number[0] == '9': return 1 # accepted elif len(number) == 9 and number[0] != '9': return 2 elif len(number) != 9 and number[0] == '9': return 3 else: return 4
aae9d80c602849170188e1d18f0bc3cc9c0ded59
amiralimoghadamzadeh/pythonn
/2-4.py
217
3.625
4
a = int(input("number of the students in the class")) S = 0 L = [] for i in range(a): score = int(input("enter the score")) L.append(score) S += score print(max(L)) print(min(L)) print(float(S/a))
61c5751ed2815fbbf28de27d166e258c0b06d7ee
Svagtlys/PythonExercises
/PasswordGenerator.py
2,542
4.21875
4
import random import string # Write a password generator in Python. Be creative with how you # generate passwords - strong passwords have a mix of lowercase # letters, uppercase letters, numbers, and symbols. The passwords # should be random, generating a new password every time the user # asks for a new password. Include your run-time code in a main method. # Extra: # Ask the user how strong they want their password to be. # For weak passwords, pick a word or two from a list. def weak(): #pick from word list return random.choice(['strange','disgusting','chivalrous','decide','loud','vivacious','love','toothpaste','steal','defeated','wood','claim']) def passgen(strength): #generator ''' Takes in strength as an int defining how many characters to generate for the password. Returns a result containing the defined number of psuedo-randomly generated characters. ''' password = '' max = 2 for i in range(strength): chartype = random.randint(0,max) #0 = num, 1 = letter, 2 = specialchar if chartype == 0: password += random.choice(string.digits) #this was randint(0,9), but when I was looking for the letters and punctuation, I found this, so elif chartype == 1: password += random.choice(string.ascii_letters) else: password += random.choice(string.punctuation) max = 1 #I got tired of all special chars return password # apparently this is a python main function if __name__ == '__main__': # I looked it up, apparently __name__ is a variable # the file has set to its name, until it's executed, # then its name is '__main__', so this here is asking # if the file is being executed, essentially. Smart stronglength = 16 mediumlength = 8 #first, ask for strength #Two methods, weak and other: # weak will pick from word list # other has random gen, which picks length depending on med or strong strength = input("What strength do you want your password to be? (S)trong, (M)edium, (W)eak\n").lower() while(strength != "s" and strength != "m" and strength != "w"): strength = input("Please type s for strong, m for medium, or w for weak.\n").lower() if(strength == "w"): print("Your weak password is: " + weak()) elif(strength == "m"): print("Your medium password is: " + passgen(mediumlength)) else: print("Your strong password is: " + passgen(stronglength))
70374def1e4562e7b1baa0b5c0923ebb9b0eac9f
ExQA/WebAcademyPython
/include/calcul.py
432
3.953125
4
first = float(input('first number >>> ')) operation = input('operation >>> ') second = float(input('second number >>> ')) pattern_output = '{} {} {} = {}' res = None if operation == '+': res = first + second elif operation == '-': res = first - second elif operation == '*': res = first - second else: print('invalide operation') if res is not None: print(pattern_output.format(first, operation, second, res))
badecfa9c71115b80abf3e050435c642425724ee
FrancisJaGlez/Mision_02
/cuenta.py
335
3.65625
4
#Francisco Javier González Molina A01748636 #Algoritmo que calcula el costo total de la comida subtotal= int (input("Inserte el precio total de los platillos: $")) propina=subtotal*.13 iva=subtotal*.16 totalapagar=subtotal+iva+propina print ("""Costo de la comida: $%.2f Propina: $%.2f IVA: $%.2f Total a pagar: $%.2f"""% (subtotal,propina,iva,totalapagar))
adf2ab2ea686c67e413e3f1637d719a674a6ac6c
cognizant1503/Assignments
/PF/day2/Assignment16.py
938
3.9375
4
#PF-Assgn-16 def make_amount(rupees_to_make,no_of_five,no_of_one): five_needed=0 one_needed=0 money=0 five=rupees_to_make//5 if(five>=no_of_five): money = no_of_five * 5 ones = rupees_to_make - money if(ones<=no_of_one): five_needed = no_of_five one_needed = ones print("No. of Five needed :", five_needed) print("No. of One needed :", one_needed) else: print("-1") elif(five<=no_of_five): money=five * 5 ones=rupees_to_make-money if(ones<=no_of_one): five_needed = five one_needed = ones print("No. of Five needed :", five_needed) print("No. of One needed :", one_needed) else: print("-1") else: print('-1') make_amount(105,19,3)
b04dc5da47fed82aa85caf6b7b5078f39f71d90c
green-fox-academy/Komaxor
/week3/thu/8_list_introduction_2.py
1,051
4.21875
4
''' Create a list ('List A') which contains the following values Apple, Avocado, Blueberries, Durian, Lychee Create a new list ('List B') with the values of List A Print out whether List A contains Durian or not Remove Durian from List B Add Kiwifruit to List A after the 4th element Compare the size of List A and List B Get the index of Avocado from List A Get the index of Durian from List B Add Passion Fruit and Pomelo to List B in a single statement Print out the 3rd element from List A ''' list_A = ['Apple', 'Avocado', 'Blueberries', 'Durian', 'Lychee'] list_B = list_A[::] if "Durian" in list_A: print("Yes") else: print("No") list_B.remove("Durian") list_A.insert(3, "Kiwifruit") if len(list_A) > len(list_B): print("A is longer") elif len(list_B) > len(list_A): print("B is longer") else: print("They are equally long") print(list_A.index("Avocado")) if "Durian" in list_B: print(list_B.index("Durian")) else: print("Nope") list_B.extend(("Passion Fruit", "Pomelo")) print(list_A[2]) print(list_A, list_B)
1b6f5f01d7b96fa5c4c96691415e695b2813b18c
eunic/bootcamp-final-files
/bank_account.py
3,047
4.28125
4
""" prompts customer to choose bank account form which he or she wishes to deposit, withdraw or view balance """ class BankAccount(object): def __init__(self,balance): self.balance = balance class SavingsAccount(BankAccount): def __init__(self): self.balance = 500 def deposit(self): cash_deposited = input("Please enter Amount to Deposit") if cash_deposited < 0: print("Invalid deposit amount") else: self.balance += cash_deposited print("You have deposited %d and your balance is %d"%(cash_deposited, self.balance)) def withdraw(self): amount = input("Please enter Amount to withdraw") if amount < 0: print("Invalid withdraw amount") elif amount > self.balance: print("Cannot withdraw beyond the current account balance") else: self.balance -= amount if self.balance < 500: print("Cannot withdraw beyond the minimum account balance 500") else: print("You have deposited %d and your balance is %d"%(cash_deposited, self.balance)) def getBalance(self): print("your balance is now %d"%(self.balance)) class CurrentAccount(BankAccount): def __init__(self): self.balance = 0 def deposit(self): amount = input("Please enter Amount to Deposit") if amount < 0: print("Invalid deposit amount") else: self.balance += amount print("You have deposited %d and your balance is %d"%(amount, self.balance)) def withdraw(self): withdrawamount = input("Please enter Amount to withdraw") if withdrawamount < 0: print("Invalid withdraw amount") elif withdrawamount > self.balance: print("Cannot withdraw beyond the current account balance") else: self.balance -= withdrawamount print("You have deposited %d and your balance is %d"%(amount, self.balance)) def getBalance(self): print("your balance is %d"%(self.balance)) if __name__ == '__main__': account = input("please choose 1 for SavingsAccount and 2 for CurrentAccount") if account == 1: s = SavingsAccount() choose = input("please choose 1 for deposit and 2 for withdraw and 3 for balance Inquiry") if choose == 1: s.deposit() elif choose == 2: s.withdraw() elif choose == 3: s.getBalance() else: print("Incorrect Entry") elif account == 2: c= CurrentAccount() choose = input("please choose 1 for deposit and 2 for withdraw and 3 for balance Inquiry") if choose == 1: c.deposit() elif choose == 2: c.withdraw() elif choose == 3: c.getBalance() else: print("Incorrect Entry") else: print("Incorrect Entry")
ffc77fedbdcc36734ed9e3dbcc2c394c0c8b061c
Zhansayaas/webdev
/week10/Инфоматрикс/c.циклы/while/d)e.py
55
3.5
4
k=int(input()) x=0 while(2**x<k): x+=1 print(x)
776958cebfb4db688d3f63ebffcff4e3b8575644
JakubKazimierski/PythonPortfolio
/Coderbyte_algorithms/Medium/StringZigzag/StringZigzag.py
1,385
4.59375
5
''' String Zigzag from Coderbyte December 2020 Jakub Kazimierski ''' def StringZigzag(strArr): ''' Have the function StringZigzag(strArr) read the array of strings stored in strArr, which will contain two elements, the first some sort of string and the second element will be a number ranging from 1 to 6. The number represents how many rows to print the string on so that it forms a zig-zag pattern. For example: if strArr is ["coderbyte", "3"] then this word will look like the following if you print it in a zig-zag pattern with 3 rows: c r e o e b t d y Your program should return the word formed by combining the characters as you iterate through each row, so for this example your program should return the string creoebtdy. ''' rows = int(strArr[1]) word = strArr[0] output = ['']*rows row = 0 increment_row = False for char in word: output[row] += char # at borders of rows change direction of incrementing # for decrementing or from decrementing to incrementing (zig zag) if row == 0 or row == rows-1: increment_row = not increment_row if rows>1: row += 1 if increment_row else -1 return ''.join(output)
3ef60e1eaf5f6ad658da5eb4ec7e1f37b3b72a0b
Lightman-EL/Python-by-Example---Nikola-Lacey
/N5_For_Loop/042.py
238
4.125
4
total = 0 for i in range(1, 6): number = int(input("Enter a number: ")) includ = input("Do you want that number included? (y/n)\n") if includ.lower() == "y": total = total + number print("The total is ", total)
d7dc7171eea792d0d42225f25c5d2d8d1ededa07
Remboooo/adventofcode
/2019/21-1.py
1,055
3.6875
4
from argparse import ArgumentParser from intvm import IntVM def main(): argparse = ArgumentParser() argparse.add_argument("file", type=str, nargs="?", default="21-input.txt") args = argparse.parse_args() with open(args.file, "r") as f: program = [int(c) for c in f.read().split(',')] instructions = [ord(c) for c in "".join(l+"\n" for l in ( "NOT A J", # jump if we're about to walk into a hole # if a hole is at distance two and there is ground at distance four, # jump now because maybe distance five is a hole "NOT B T", "AND D T", "OR T J", # if a hole is at distance three and there is ground at distance four, # jump now because maybe distance five is a hole "NOT C T", "AND D T", "OR T J", "WALK" ))] vm = IntVM( program, inputs=instructions, output_func=lambda s: print(chr(s), end='', flush=True) if s < 127 else print(s) ) vm.run() if __name__ == '__main__': main()
e431a06eed951490db45ea56c7d54ae39939e501
lalosuarez/machine-learning-projects
/users-leave-bank/users-leave-bank-ann/ann.py
6,030
3.609375
4
# Artificial Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Part 2 - Now let's make the ANN! # Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense #from keras.layers import Dropout # Initialising the ANN classifier = Sequential() # Adding the input layer and the first hidden layer # TIP: for output_dim you can take the avg between number of the input node # and output node, in this case 11 inputs + 1 output classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) # classifier.add(Dropout(p = 0.1)) # Adding the second hidden layer classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) # classifier.add(Dropout(p = 0.1)) # Adding the output layer # units = 1 because we only have only one output node # for activation param you'll need to change to softmax if output node has more than 2 categories. classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) # Compiling the ANN # There are multiple types of stochastic gradient descend algorithms a very efficient one is 'adam' #classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) classifier.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training set #classifier.fit(X_train, y_train, batch_size = 10, epochs = 100) classifier.fit(X_train, y_train, batch_size = 25, epochs = 500) # Saving model classifier.save('users_leave_bank_optimized_model.h5') # Part 3 - Making predictions and evaluating the model # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Predicting a single new observation """Predict if the customer with the following informations will leave the bank: Geography: France Credit Score: 600 Gender: Male Age: 40 Tenure: 3 Balance: 60000 Number of Products: 2 Has Credit Card: Yes Is Active Member: Yes Estimated Salary: 50000""" new_prediction = classifier.predict(sc.transform(np.array([[0.0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]]))) new_prediction = (new_prediction > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Accuracy = number of correct predictions / total predictions # fin this case (1512+210)/2000 # Part 4 - Evaluating, Improving and Tuning the ANN # Evaluating the ANN # To run execute first Part 1 - Data Preprocessing and then this from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from keras.models import Sequential from keras.layers import Dense def build_classifier(): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100) # IMPORTANT: n_jobs = -1 throws and error accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = 1) mean = accuracies.mean() variance = accuracies.std() # Improving the ANN # Dropout Regularization to reduce overfitting if needed # Tuning the ANN # To run execute first Part 1 - Data Preprocessing and then this from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense def build_classifier(optimizer): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier) parameters = {'batch_size': [25, 32], 'epochs': [100, 500], 'optimizer': ['adam', 'rmsprop']} grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 10) grid_search = grid_search.fit(X_train, y_train) # Best params according to the video are: # batch_size = 25 # nb_epoc = 500 # optimizer = rmsprop best_parameters = grid_search.best_params_ best_accuracy = grid_search.best_score_
153dd38c0c6bd0a127a9e3837db884e6b6e1f5fb
morningred88/data-structure-algorithms-in-python
/Array/q4-anagram.py
979
3.859375
4
""" Question 4: Anagram checking Construct an algorith to check whether two words (or phrases) are anagrams or not "An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once" """ def isAnagram(str1, str2): # If the length of the strings differs - they are not anagrams if len(str1) != len(str2): return False # Sort the characters of the strings and then compare the characters with the same index # This is the bottleneck because it O(nlogn) str1 = sorted(str1) str2 = sorted(str2) # after that we have to check the charactors with the same indexes # O(n) running time for i in range(len(str1)): if str1[i] != str2[i]: return False return True # Overall running time is O(nlogn) + O(n) = O(nlogn) if __name__ == '__main__': print(isAnagram('fluster', 'restful')) print(isAnagram('follow', 'pillow'))
9f4baa32416c8d02dcdd2afa4ef8b44230a6eb61
stjordanis/Fin6470
/Spring2021/Module1/Notebooks/Chapter 2 (Hull)/.ipynb_checkpoints/m2m-checkpoint.py
1,857
3.5625
4
class MarginAccount(object): def __init__(self, spot_price, init_margin, var_margin, num_contracts, units): self.__ref_price = spot_price self.__init_margin = init_margin self.__var_margin = var_margin self.__num_contracts = num_contracts self.__units = units self.__equity = init_margin self.__capital = init_margin self.__profit = 0.0 self.__cum_profit = 0.0 self.__margin_call = 0.0 def show(self): print("Settlement Price: \t{0:.2f}".format(self.__ref_price)) print("Profit: \t\t{0:.2f}".format(self.__profit)) print("Cumulative Profit: \t{0:.2f}".format(self.__cum_profit)) print("Capital: \t\t{0:.2f}".format(self.__capital)) print("Equity: \t\t{0:.2f}".format(self.__equity)) print("Margin Call: \t\t{0:.2f}".format(self.__margin_call)) print("\n") def update(self, spot_price): self.__profit = (spot_price - self.__ref_price) * (self.__num_contracts * self.__units) self.__cum_profit += self.__profit self.__equity = self.__capital + self.__cum_profit if self.__equity <= self.__var_margin: self.__margin_call = self.__init_margin - self.__equity else: self.__margin_call = 0.0 self.__capital += self.__margin_call self.__ref_price = spot_price def main(): spot0 = 2.75 spot_t = [2.76, 2.73, 2.68, 2.67, 2.69, 2.64, 2.62, 2.63, 2.67] units = 5000 num_contracts = 1 init_margin = 2000.0 var_margin = 1750.0 acc = MarginAccount(spot0, init_margin, var_margin, num_contracts, units) for i, spot in enumerate(spot_t): acc.update(spot) print("Day t={0:d}".format(i+1)) print("--------") acc.show() if __name__ == "__main__": main()
1bf55e7f33486c345beb2f7b9b06b8ff2aaf7ebe
hussain-abbas-06228/DS2-Project-Scrabble
/new pagoda.py
4,064
3.9375
4
class Node1: def __init__(self, val: str, dat: str) -> None: self._left = None self._right = None self._value = val self._data = dat class Pagoda1: def __init__(self): self._root:Node1 = None def is_empty(self): if self._root == None: return True return False def clear(self): self._root = None def Merge(self, root: Node1, newnode: Node1): if root == None: return newnode elif newnode == None: return root else: bottomroot: Node1 = root._right root._right = None bottomnew: Node1 = newnode._left newnode._left = None r:Node1 = None temp:Node1 = None while (bottomroot != None and bottomnew != None): if bottomroot._value < bottomnew._value: temp = bottomroot._right if r == None: bottomroot._right = bottomroot else: bottomroot._right = r._right r._right = bottomroot r = bottomroot bottomroot = temp else: temp = bottomnew._left if r == None: bottomnew._left = bottomnew else: bottomnew._left = r._left r._left = bottomnew r = bottomnew bottomnew = temp if bottomnew == None: root._right = r._right r._right = bottomroot return root else: newnode._left = r._left r._left = bottomnew return newnode def print_root(self): return ((self._root._value, self._root._data)) # a:Node = self._root._right # b:Node = self._root._left # print("right ",a._value, a._data) # print("left ",b._value, b._data) def insert_2(self, n: Node1, root: Node1): n._left = n n._right = n return self.Merge(root, n) def insert_1(self, val, dat): n = Node1(val, dat) self._root = self.insert_2(n, self._root) def delete_1(self): self._root = self.delete_2(self._root) def delete_2(self, root :Node1): L : Node1 = None R : Node1 = None if root == None: print("is empty:((") return None else: if root._left == root: L = None else: L = root._left while L._left != root: L = L._left L._left = root._left if root._right == root: R = None else: R = root._right while R._right != root: R = R._right R._right = root._right return self.Merge(L,R) def sort_dic(self, inpt): lst = [] dic = {} for x,y in inpt.items(): self.insert_1(y,x) while self.is_empty() == False: temp = self.print_root() self.delete_1() lst.append((temp[1],temp[0])) for x,y in lst[::-1]: dic[x] = y return dic test = {'!': 13, 'm': 2, 'o': 2, 'n': 1, 'a': 2, 'p': 3, 'l': 1, 'e': 1} p = Pagoda1() print(p.make_dic(test)) # for x,y in test.items(): # print(x,y) # p.insert_1(y,x) # p.print_root() # lst = [] # new = {} # while p.is_empty() == False: # temp = p.print_root() # p.delete_1() # lst.append((temp[1],temp[0])) # #new[temp[1]] = temp[0] # print(lst) # lst = lst[::-1] # for x,y in lst: # new[x] = y # print(new) # p.insert_1('zoo') # p.print_root() # p.insert_1('banana') # p.print_root() # p.delete_1() # p.print_root() # p.delete_1() # p.print_root() # print(p.is_empty()) # p.delete_1() # print(p.is_empty()) # p.clear() # print(p.is_empty())
901701f7d13eea2ba035eeab304b4b03373930e5
wangtao090620/LeetCode
/wangtao/leetcode/0501.py
1,372
3.75
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Author : wangtao # @Contact : [email protected] # @Time : 2020-03-02 18:42 """ 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树 例如: 给定 BST [1,null,2,2], 1 \ 2 / 2 返回[2]. 提示:如果众数超过1个,不需考虑输出顺序 进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内) """ # Definition for a binary tree node. from typing import List import collections class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findMode(self, root: TreeNode) -> List[int]: self.counter = collections.Counter() self.dfs(root) max_count = max(self.counter.values()) return [k for k, v in self.counter.items() if v == max_count] def dfs(self, root): if root: self.counter[root.val] += 1 self.dfs(root.left) self.dfs(root.right) if __name__ == '__main__': pass
d43b9fc35c4d135e0789004cf43c5c0b21f45db8
ManishaHingne/PythonML
/Code/feb_22/page1.py
187
3.984375
4
numbers = list(range(0, 10)) print(numbers) # for index in numbers: # numbers.pop() # print(numbers) # numbers.pop(-1) print(numbers) number = '10.5' print(number.isdecimal())
d3b76ae9f47a338716342decdf4689529cdc55a3
tristanwinstanley/Networks
/grid_object.py
15,967
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 19 22:52:22 2018 @author: matth """ import numpy as np import T_grid from random import randint as rnd labels = {'empty':0,'obstacle':1,'start':2,'radar':2.5,'end':4.5,'path':3.5} directions = [[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1]] def p2_dist(a,b): ''' Calculates the euclidean distance between two points 'a' and 'b'. This is used as the distance measure when calculating the heuristics of states. ''' return np.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2) class grid: ''' 'grid' objects will have a set value for 'vision_range', which will be used to define the maximum boundaries of a drones field of vision. 'directions' simply stores vectors for horizontal, vertical and diagonal movements. ''' __vision_range = 3 __goals = [] ##__directions = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]] __seen = [] __scanned = [] def __init__(self,size,obstacles,capacity=0): ''' 'size' is a vector that defines the dimensions of the grid. 'obstacles' is a list of coordinate locations for permanent obstacles in the grid. ''' self.__width = size[0] self.__height = size[1] self.__area = self.__width*self.__height self.__sense_range = self.__width+self.__height self.__states = np.zeros((self.__width,self.__height)) self.__colour = np.zeros((self.__width,self.__height)) # int is used because states will contain discrete classifications. self.__states = self.__states.astype(int) ##self.__start=start ##self.__end=end ##self.__colour[start[0]][start[1]] = labels['start'] ##self.__colour[end[0]][end[1]] = labels['end'] for ob in obstacles: self.__states[ob[0]][ob[1]] = labels['obstacle'] self.__colour[ob[0]][ob[1]] = labels['obstacle'] self.__total_obs = len(obstacles) self.__capacity = max([self.__total_obs,capacity]) self.__risk = np.zeros((self.__width,self.__height)) self.update_risk() self.__heuristic = np.zeros((self.__width,self.__height)) def get_width(self): ''' Returns the number of columns in the grid. ''' return self.__width def get_height(self): ''' Returns the number of rows in the grid. ''' return self.__height def update_state(self,coord,value): ''' Updates the state of a specified grid square. ''' if self.__states[coord[0]][coord[1]]!=value: self.__states[coord[0]][coord[1]] = value if value==labels['empty']: self.__total_obs-=1 elif value==labels['obstacle']: self.__total_obs+=1 def get_state(self,coord=[]): ''' Returns the state of a specified grid square. ''' if len(coord)==0: return self.__states else : return self.__states[coord[0]][coord[1]] def is_in_grid(self,coord): ''' Checks whether an input coordinate is within the boundaries of the grid. ''' if 0<=coord[0]<self.__width and 0<=coord[1]<self.__height: return True return False def vision_field(self,coord): ''' Calculates a list of grid squares that are visible from a given input coordinate. MATT-TODO:This function could be made neater... ''' visible = [] for d in directions: # first deal with horizontal and vertical lines of sight. if d[0]*d[1]==0: # iterate through a maximum of three steps. for inc in range(1,self.__vision_range+1): square = [coord[0]+inc*d[0],coord[1]+inc*d[1]] included = False # if 'square' is in the grid... if self.is_in_grid(square): # ... flag as visible visible.append(square) included = True # if 'square' was not included or is not empty... if (not included or self.__states[square[0]][square[1]]!=labels['empty']): # ... do not continue in current direction. break # secondly, deal with diagonal lines of sight. else : blocked_x = False blocked_y = False # with diagonal lines of sight, iterate once fewer. for inc in range(1,self.__vision_range): square = [coord[0]+inc*d[0],coord[1]+inc*d[1]] # if 'square' is in the grid and not blocked... included = False if (self.is_in_grid(square)): # check if off-diagonals are obstructed. blocked_x = (self.__states[square[0]-d[0]][square[1]]== labels['obstacle'] or blocked_x) blocked_y = (self.__states[square[0]][square[1]-d[1]]== labels['obstacle'] or blocked_y) if not blocked_x or not blocked_y: # ... flag as visible visible.append(square) included = True # if 'square' was not included or is not empty... if (not included or self.__states[square[0]][square[1]]!=labels['empty']): # ... do not continue in current direction. break # vectors to check the grid squares missed by above directions. knight_moves = [[1,2],[-1,2],[1,-2],[-1,-2], [2,1],[-2,1],[2,-1],[-2,-1]] for d in knight_moves: square = [coord[0]+d[0],coord[1]+d[1]] # define intermidiate moves between 'coord' and 'square'. s1 = [int(d[0]/abs(d[0])),int(d[1]/abs(d[1]))] s2 = [int(d[0]-s1[0]),int(d[1]-s1[1])] if (self.is_in_grid(square) and self.__states[square[0]-s1[0]][square[1]-s1[1]]== labels['empty'] and self.__states[square[0]-s2[0]][square[1]-s2[1]]== labels['empty']): visible.append(square) else : continue return visible def update_risk(self,coord_list=[]): ''' Updates the knowledge risk values of an optional selection of grid squares; by default, all values are updated. Risk due to knowledge is defined as the the likelihood of finding an unexpected obstacle in a grid square multiplied by the number of known neighbouring obstacles. ''' aware = self.get_coords(labels['obstacle']) for s in self.__seen: if not s in aware: aware.append(s) if len(coord_list)==0: for x in range(0,self.__width): for y in range(0,self.__height): surrounding_obstacles = 0 for d in directions: square = [x+d[0],y+d[1]] if (self.is_in_grid(square) and self.__states[square[0]][square[1]]== labels['obstacle']): surrounding_obstacles+=1 unknown = ((self.__capacity-self.__total_obs)/ (self.__area-len(aware))) self.__risk[x][y] = unknown*surrounding_obstacles else : for i in range(0,len(coord_list)): coord = coord_list[i] surrounding_obstacles = 0 for d in directions: square = [coord[0]+d[0],coord[1]+d[1]] if (self.is_in_grid(square) and self.__states[square[0]][square[1]]== labels['obstacle']): surrounding_obstacles+=1 unknown = ((self.__capacity-self.__total_obs)/ (self.__area-len(aware))) self.__risk[coord[0]][coord[1]] = unknown*surrounding_obstacles def get_risk(self,coord=[]): ''' Return the risk value for a given grid square or, by default, the entire array. ''' if len(coord)==0: return self.__risk else : return self.__risk[coord[0]][coord[1]] def update_heuristic(self,goal): ''' Stores the values of the heuristic for each grid square, calculated as the euclidean distance between grid squares and a goal square. ''' for x in range(0,self.__width): for y in range(0,self.__height): if len(goal)>0: self.__heuristic[x][y] = p2_dist([x,y],goal) else : self.__heuristic[x][y] = 0 def get_heuristic(self,coord=[]): ''' Return the heuristic value for a given grid square or, by default, the entire array. ''' if len(coord)==0: return self.__heuristic else : return self.__heuristic[coord[0]][coord[1]] def neighbours(self,coord,value=-1): ''' Return a list of grid squares neighbouring a given coordinate with a specified state value. ''' neighbs = [] for d in directions: square = [coord[0]+d[0],coord[1]+d[1]] if (self.is_in_grid(square) and (self.__states[square[0]][square[1]]==value or value==-1)): neighbs.append(square) return neighbs def update_path_colour(self,coord_list,start,goals): ''' Updates the colour of the path taken from start to end. ''' for step in coord_list: if step==start: self.__colour[step[0]][step[1]] = labels['start'] elif step in goals: self.__colour[step[0]][step[1]] = labels['end'] else : self.__colour[step[0]][step[1]] = labels['path'] def show_me(self): ''' Displays grid in command window. ''' T_grid.draw_grid(self.__colour) def get_colour(self,coord=[]): ''' return colour of specific square ''' if len(coord)==0: return self.__colour else: return self.__colour[coord[0]][coord[1]] def random_obs(self,obs_number,occupied=[]): ''' Creates obs_number of obstacles randomly, anywhere that isn't in the occupied list occupied should be a list of coordinates such as: [[0,0],[5,4]]. ''' #exit if there are too many obstacles and not enough empty spaces if obs_number > self.__area - len(occupied): print('TOO MANY OBSTACLES') return None self.__total_obs+=obs_number self.__capacity+=obs_number #if occupied isn't empty if occupied != []: for i in range(0,obs_number): obs_placed=False #remains false until the obstacle is placed while obs_placed==False: #make 2 random coordinates row=rnd(0,self.__height-1) col=rnd(0,self.__width-1) #check if coordinate is not empty and not in occupied list if self.__states[row][col]==labels['empty'] and [row,col] not in occupied : self.__states[row][col]=labels['obstacle'] obs_placed=True #if occupied empty else: for i in range(0,obs_number): obs_placed=False #remains false until the obstacle is placed while obs_placed==False: #make 2 random coordinates row=rnd(0,self.__height-1) col=rnd(0,self.__width-1) if self.__states[row][col]==labels['empty']: self.__states[row][col]=labels['obstacle'] obs_placed=True def get_capacity(self): ''' Returns the maximum number of obstacles for the grid ''' return self.__capacity def increment_capacity(self,obs_number): ''' Increases the maximum number of obstacles for the grid. ''' self.__capacity+=obs_number def get_coords(self,value): coord_list = [] for x in range(0,self.__width): for y in range(0,self.__height): if self.get_state([x,y])==value: coord_list.append([x,y]) return coord_list def radar_field(self,coord,show=False): squares_list = [] for x in range(0,self.__width): for y in range(0,self.__height): if p2_dist([x,y],coord)<=self.__sense_range: squares_list.append([x,y]) if show==True: self.__colour[x][y]=labels['radar'] return squares_list def set_goals(self,goals): self.__goals = [] for g in goals: self.__goals.append(g) def get_goals(self): return self.__goals def update_sense_range(self,dist): self.__sense_range = dist self.__heuristic = dist*np.ones((self.__width,self.__height)) def get_sense_range(self): return self.__sense_range def have_seen(self,new_coords): for square in new_coords: if not square in self.__seen: self.__seen.append(square) def have_scanned(self,new_coords): for square in new_coords: if not square in self.__scanned: self.__scanned.append(square) def get_seen(self): return self.__seen def get_scanned(self): return self.__scanned def non_overlap(self,memory,coord): #coord here is position of drone sensed=self.radar_field(coord) non_overlap=[x for x in sensed if x not in memory] return non_overlap def radar_iteration(self,possible_squares,memory): new_memory = [] #1st phase #loop through all possible squares and extract the number of non overlapping squares for square in possible_squares: new_memory+=self.non_overlap(memory+new_memory,square) return len(new_memory) def construct_heuristic(self,curr,last,goal): clue = 0 if p2_dist(curr,goal)<p2_dist(last,goal): clue = 1 elif p2_dist(curr,goal)>p2_dist(last,goal): clue = -1 #update_list = self.radar_field(current) #better_square = current #worse_square = last #if clue==-1: # update_list = self.radar_field(last) # better_square = last # worse_square = current for x in range(0,self.get_width()): for y in range(0,self.get_height()): if ((clue==1 and (p2_dist([x,y],curr)>p2_dist([x,y],last) or p2_dist([x,y],curr)>self.__sense_range)) or (clue==-1 and (p2_dist([x,y],last)>p2_dist([x,y],curr) or p2_dist([x,y],last)>self.__sense_range)) or (clue==0 and (p2_dist([x,y],curr)!=p2_dist([x,y],last) or p2_dist([x,y],curr)>self.__sense_range))): self.__heuristic[x][y]+=1
edd41fd7695863768a1a79b43690e8266a42bb6d
bangalorebyte-cohort11/Control-Flow-Github-Terminal
/Control_Flow.py
1,838
3.96875
4
# Control flow via indentation if 2**2 == 4: print('Obvious!') # luckily ipython does the indentation whenever we move to a new line # but if we did the following if 2**2 ==4: print('Obviously Not!') #the interpreter tells us in this case where and how we went wrong # Iteration counter = 1 while counter <= 5: print("Hello, world") # compound condition done = True while counter <= 10 and not done: print("hello") # the value of the variable counter would need to be less than or # equal to 10 and the value of the variable done would need to be False # (not False is True) so that True and True results in True. # In[14]: z = 1 + 1j while abs(z) < 100: if z.imag == 0: break z = z**2 + 1 # THE FOR LOOP for item in [1,3,6,2,5]: print(item) # This works for any sequence (lists, tuples, and strings). for item in range(5): print(item**2) # nested for loops wordlist = ['cat','dog','rabbit'] letterlist = [ ] for aword in wordlist: for aletter in aword: letterlist.append(aletter) print(letterlist) # Example of Nested For Loop: Grading score = 65 if score >= 90: print('A') else: if score >=80: print('B') else: if score >= 70: print('C') else: if score >= 60: print('D') else: print('F') # Avoiding For Loops using elif. Elif is like the "or" statment if score >= 90: print('A') elif score >=80: print('B') elif score >= 70: print('C') elif score >= 60: print('D') else: print('F') # List Comprehension: Syntactic Sugar # Avoids looking up append attribute of the list, loaded and called as # a function, which takes time and that adds up over iterations. sqlist=[] for x in range(1,11): sqlist.append(x*x) sqlist=[x*x for x in range(1,11)]
55819062e340a7c95763276f37cf6c72aba9f5a0
peterhuyxuan/SelfOrderingFoodSystem
/src/inventory.py
3,176
3.65625
4
from src.inventory_item import inventoryItem class inventory(): def __init__(self): self._item = [] ''' Query Processing Services ''' def item_search(self, name=None): if name == None: for item in self._item: print(item) else: for item in self._item: if inventoryItem.name == name: print(item) def get_item(self, name): self._name = name error = False for item in self._item: if item.name == name: error = True return item if (error == False): raise ValueError(f"Item {self._name} is not in inventory") def add_stock (self, name, quantity): self._check_name_exists(name) item = inventoryItem(name, quantity) self._item.append(item) def refill_stock (self, id, quantity): self._check_item_exists(id) if quantity == 0: raise ValueError("Quantity input Cannot be Zero") for item in self._item: if id == item.id: item.quantity += quantity def refill_stock_name (self, name, quantity): #self._check_item_exists(name) if quantity == 0: raise ValueError("Quantity input Cannot be Zero") for item in self._item: if name == item.name: item.quantity += quantity def consume_stock (self, id, quantity): self._check_item_exists(id) if quantity == 0: raise ValueError("Quantity inupt Cannot be Zero") for item in self._item: if id == item.id: if item.quantity < quantity: raise RemovalError(item.name) item.quantity -= quantity def remove_stock(self, item_id : int): """ remove the item with item_id from the inventory """ removal_flag = False for item in self._item: if item.id == item_id: self._item.remove(item) removal_flag = True break if removal_flag == True: break if removal_flag == False: raise ItemNotFound(item_id) ''' Helper functions ''' def _check_name_exists(self, name): for item in self._item: if name == item.name: raise ValueError(f"item({item.name}) is already in the inventory") def _check_item_exists(self, id): logic = 0 for item in self._item: if id == item.id: logic = 1 break if logic == 0: raise ItemNotFound(id) @property def items(self): return self._item class ItemNotFound(Exception): def __init__(self, id): self._id = id def __str__(self): return f"item with id ({self._id}) is not found in the inventory" class RemovalError(Exception): def __init__(self, name): self._name = name def __str__(self): return f"item ({self._name}) does not have enough stock in the inventory"
f5f03bb63bd2f633efa9de079ed14e077e6ff519
pbarton666/learninglab
/kirby-course/session10/manager_one.py
909
3.84375
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 4, 2016 Modified Mon Dec 12, 2016 @author: Kirby Urner Show how entering a context triggers the __enter__ tripwire. On __exit__ you may set off the emergency buzzer (return False), or not (return True) """ class CodeCastle: def __init__(self): self.me = "I will be your guide" def __enter__(self): print("You have entered the castle") return self def __exit__(self, *oops): # 3-tuple if oops[1]: print("Arg 0:", oops[0]) print("Arg 1;", oops[1]) return False return True # all is well try: with CodeCastle() as guide: print("We're in!") print(guide.me) raise ValueError("Uh oh!") print("You have left the castle normally.") except: print("Something bad happened") print("We're done") # End of Story
3bb5f7a1df1d8a72c1c2b2cca1729a5fe6a957b5
orazioc17/python-avanzado
/operaciones_sets.py
468
3.90625
4
def run(): set1 = {1,2,3,4,5} print(f'set1: {set1}') set2 = {5,6,7,8,9} print(f'set2: {set2}') union = set1 | set2 print(f'union: {union}') intersection = set1 & set2 print(f'intersection: {intersection}') diff1 = set1 - set2 print(f'diff1: {diff1}') diff2 = set2 - set1 print(f'diff2: {diff2}') # Opposite to diff sym_diff = set1 ^ set2 print(f'sym_diff: {sym_diff}') if __name__ == '__main__': run()
8666853f4c6a9341f7a7ba80b4dfad390aa9fbff
heersaak/opdrachtenPython
/Opdrachten/Les 7/7_2.py
706
3.828125
4
##Schrijf een nieuw programma waarin de gebruiker een woord moet invoeren. Dit woord moet uit vier ##letters bestaan. Is dat niet zo, dan wordt en foutmelding getoond en moet de gebruiker opnieuw een ##woord invoeren, net zolang totdat er een woord is ingevoerd dat uit vier letters bestaat. Dan eindigt ##het programma. Gebruik in ieder geval een while-loop, gecombineerd met het break-statement! woord = input("Geef een string van vier letters: ") while len(woord) > 4 or len(woord) < 4: if True: print(woord, 'heeft', len(woord), 'letters') woord = input("Geef een string van vier letters: ") if False: break print('Inlezen van correcte string:', woord, 'is geslaagd')
b591f9905f1215a50e3aac3efebbd4399cd124e4
marjana155/basic-python-programs
/Data_Structure/dsChallenge.py
384
4.0625
4
text = input("Enter your text:") count = {c: text.count(c)for c in text} """unique = [] for t in count: if t not in unique: unique.append(t) count = unique # print(unique) count.sort(key=lambda item: item[1], reverse=True)""" count_sorted = sorted(count.items(), key=lambda item: item[1], reverse=True) print("the most used character in your text is:", count_sorted[0])
3ddd19eb2b2c7df490718be7d1bb5a8f45e6ff50
smithadam7/DepositoryPython
/Search.py
1,286
3.5625
4
# Adam Smith # Search algorithms arr = [] f = open('wordlist.txt', 'r') thefile = open('nearly-sorted.txt', 'w') for line in f.readlines(): line = line.strip('!') line = line.strip(' ') line = line.strip(' ') line = line.strip(' ') line = line.strip(' ') line = line.strip(' ') line = line.strip(',') line = line.strip('.') line = line.strip(':') line = line.strip('?') line = line.strip(';') # line = line.split() arr.append(line) larr = [x.lower() for x in arr] slarr = sorted(larr, key=str.lower) # print(sorted(slarr)) # print(arr) # print(slarr) # linear # for i in range (len(slarr)) # binary def binarySearch(slarr, litem): first = 0 last = len(slarr) -1 found = False count = 0 while first <= last and not found: midpoint = (first + last) // 2 if slarr[midpoint] == litem: found = True count += 1 else: if litem < slarr[midpoint]: last = midpoint - 1 else: first = midpoint + 1 print(count) return found for word in slarr: binarySearch(slarr, word) print(word) for item in slarr: thefile.write("%s\n" % item)
7637cd4ff54a8b3d08774de30aade7ef91a4508a
kovalbogdan95/MyPythonLearn
/SerpinskiTriangle/serpinskiTriangle.py
3,858
4.03125
4
""" Serpinski Triangle drawing function Function is implemented in Python 3. Function have three optional parametrs: - Method: 1 = Iterative or 2 = Chaos methods. (Iterative is default) - Depth of iterative method. (4 is default depth) - Shift coordinats. ([0,0] is default) """ def serpinskiTriangle (method=1, depth=4, startCrd=[0,0]): #Mode definition # ---- Iterate Mode Definition ---- def iterateMode(depth): import turtle def drawTriangle(points,myTurtle): myTurtle.up() myTurtle.goto(points[0][0],points[0][1]) myTurtle.down() myTurtle.goto(points[1][0],points[1][1]) myTurtle.goto(points[2][0],points[2][1]) myTurtle.goto(points[0][0],points[0][1]) # Find middle coordinats between two points def getMid(p1,p2): return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) # Recursive drawing function def sierpinski(points,degree,myTurtle): drawTriangle(points,myTurtle) if degree > 0: sierpinski([points[0], getMid(points[0], points[1]), getMid(points[0], points[2])], degree-1, myTurtle) sierpinski([points[1], getMid(points[0], points[1]), getMid(points[1], points[2])], degree-1, myTurtle) sierpinski([points[2], getMid(points[2], points[1]), getMid(points[0], points[2])], degree-1, myTurtle) def main(): myT = turtle.Turtle() # Set max speed of drawing myT.speed(0) myWindow = turtle.Screen() # Triangle coordinats myPoints = [[-200 + startCrd[0],-100 + startCrd[1]],[0 + startCrd[0],200 + startCrd[1]],[200 + startCrd[0],-100 + startCrd[1]]] sierpinski(myPoints,depth,myT) myWindow.exitonclick() main() # ---- END Iterate Mode Definition ---- # ---- Chaos Mode Definition ---- def chaosMode(): import random, turtle def main(): myT = turtle.Turtle() # Set max speed of drawing myT.speed(0) myT.up() myWindow = turtle.Screen() # Triangle coordinats myPoints = [[-200,-100],[0,200],[200,-100]] # Det random coordinats inside the triangle dot = [(random.randint(myPoints[0][0],myPoints[2][0])/2),(random.randint((myPoints[0][1]+myPoints[2][1])/2,myPoints[1][1]/2))] # print(dot) counter = 0 # Random choice of active attractor and make math die = [1,2,3] while (counter < 10000): counter = counter + 1 switch = random.choice(die) if switch == 1: dot[0] = (dot[0] + myPoints[0][0])/2 dot[1] = (dot[1] + myPoints[0][1])/2 if switch == 2: dot[0] = (dot[0] + myPoints[1][0])/2 dot[1] = (dot[1] + myPoints[1][1])/2 if switch == 3: dot[0] = (dot[0] + myPoints[2][0])/2 dot[1] = (dot[1] + myPoints[2][1])/2 # Go to address and draw the dot myT.goto(dot[0], dot[1]) # Here you can change size of the dot myT.dot(2, 'black') myWindow.exitonclick() main() # ---- END Chaos Mode Definition ---- #Mode switch if method == 1: iterateMode(depth) elif method == 2: chaosMode() #Lunch function serpinskiTriangle(1)
0ed370dc80d5fb3730c33d04349bd49983f65a28
duliodenis/python_master_degree
/unit_02/04_object-oriented/4-Dice_Roller/scoresheets.py
1,700
3.96875
4
# # Object-Oriented Python: Dice Roller # Python Techdegree # # Created by Dulio Denis on 12/22/18. # Copyright (c) 2018 ddApps. All rights reserved. # ------------------------------------------------ # Challenge 4: Chance Scoring # ------------------------------------------------ # Challenge Task 1 of 2 # I've set you up with all of the code you've seen # in the course. I want you to add a score_chance # method to the YatzyScoresheet. # It should take a hand argument. # Return the sum total of the dice in the hand. # For example, a Hand of [1, 2, 2, 3, 4] would return a score of 12. class YatzyScoresheet: def score_ones(self, hand): return sum(hand.ones) def _score_set(self, hand, set_size): scores = [0] for worth, count in hand._sets.items(): if count == set_size: scores.append(worth*set_size) return max(scores) def score_one_pair(self, hand): return self._score_set(hand, 2) def score_chance(self, hand): score = 0 for value in hand: score += value return score # ------------------------------------------------ # Challenge Task 2 of 2 # Great! Let's make one more scoring method! # Create a score_yatzy method. # If there are five dice with the same value, return 50. Otherwise, return 0. def score_yatzy(self, hand): # If the function self._score_set(hand,5) returns True # or any sort of Truthy data it means there are 5 of the same in the hand # therefore the if conditions returns 50. if self._score_set(hand, 5): return 50 # else return 0 else: return 0
4f9c1872b1f969b91130a5da8dddd178e2052093
jaochen/algorithm
/leetcode算法题/0066_加一.py
1,294
3.796875
4
''' 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 你可以假设除了整数 0 之外,这个整数不会以零开头。 示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。 示例 2: 输入: [4,3,2,1] 输出: [4,3,2,2] 解释: 输入数组表示数字 4321。 ''' class Solution: # 递归解法 def plusOne(self, digits: List[int]) -> List[int]: def addOne(index): nonlocal digits # 两种情况,一种是9,需要进位,另一种加就完事了 if digits[index] == 9: digits[index] = 0 if index != 0: addOne(index-1) else: digits = [1] + digits else: digits[index] += 1 addOne(len(digits)-1) return digits # 迭代解法 def plusOne2(self, digits: List[int]) -> List[int]: n = len(digits)-1 while n >= 0: digits[n] += 1 digits[n] %= 10 if digits[n] != 0: return digits n -= 1 return [1] + digits
f2e8535ddec7f764e2886c8871d55d66b4b885ca
iteachyou/homelesspup.help
/if statements.py
202
4.03125
4
name = input("What is your name?").strip().title() if name == ("Jack"): input("COPYCAT!") elif name == ("Roxy"): input("OH HAI ROXY!") else: input("Nice to meet you, " + name)
9714805e46cc579661df68d7974eb2d0d796cddd
zongninggong123/Stock-Prediction-Using-Stacked-LSTM
/WebApp.py
954
3.765625
4
import streamlit as st from PIL import Image st.write(""" # Stock Price Predictor Using LSTM: Stock values is very valuable but extremely hard to predict correctly for any human being on their own. This project seeks to solve the problem of Stock Prices Prediction by utilizes Deep Learning models, Long-Short Term Memory (LSTM) Neural Network algorithm, to predict future stock values.\n """) st.sidebar.write(""" # Stock Price Prediction: Predict Stock Price For The Next 30 Days """) option = st.sidebar.selectbox("Select Dataset",("AAPL","TATACONSUM")) prof_image = Image.open('Created By Picture.png') st.sidebar.image(prof_image) st.write(""" # Dataset Sample: Taken From Quandl\n """) import pandas as pd df=pd.read_csv('AAPL.csv') st.write(df.head()) st.write(""" # Prediction Graph: Predict Values For The Next 30 Days\n """) graph_image = Image.open('30daypredict.png') st.image(graph_image,width=500)
1bcef64337760f2c607be786ba9c8d140b1b1f91
DogsRulesAllTime/Py_tests
/classes/users.py
757
3.703125
4
class User(): """class User""" def __init__(self,name,surname,age): self.name = name self.surname = surname self.age = age self.login_atemp = 0 def user_info(self): print(self.name,' ',self.surname,' ',self.age) def great_user(self): print('Hello ',self.name) def increment_login_atemp(self): self.login_atemp+=1 def reset_login_atemp(self): self.login_atemp = 0 class Privileges(): def __init__(self,priv=['show','delete','create']): self.priv = priv def show_priv(self): for privi in self.priv: print(privi) class Admin(User): def __init__(self,name,surname,age): super().__init__(name,surname,age) self.privileges = Privileges()
98d4688a1f84c738acc68c69f5cb09b88d208fcd
shtnk/Iteration
/Python/7-continue.py
123
3.78125
4
# There is no continue label in python i = 0 while i < 10: i += 1 print("Hello") if i == 5: continue print("World")
e08b51cf03230eb50283fe5d700743d0313c79d2
thecskc/PythonTut
/tuts/conditionals.py
323
4.03125
4
a,b=5,1; if a<b: print('a {} is less than b {}'.format(a,b)); else: print('b {} is less than a {}'.format(b,a)); print("foo" if a<b else "bar"); # Testing fibonacci now... a=0 b=1 n=50 print(a) print(b) counter=1 while(counter<n): d=a+b a=b b=d print(d) counter=counter+1 print("DONE!")
40603e428e438de2118b3521cd0842e033351b4f
samadabbagh/sama-mft
/mft-twelve-section/practice_vector.py
531
3.8125
4
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): x_new = self.x + other.x y_new = self.y + other.y return Vector(x_new, y_new) def __sub__(self, other): x_sub = self.x - other.x y_sub = self.y - other.y return Vector(x_sub, y_sub) def __neg__(self): return Vector(-self.x, -self.y) v1 = Vector(3, 4) v2 = Vector(10, 1) v3 = v1 + v2 + v1 + v2 + v2 v4 = v2 - v1 print(v4.x, v4.y) print(v3.x, v3.y)
df66252879b2b0f05671b6b105eb8b5945648054
MiKueen/Data-Structures-and-Algorithms
/Leetcode/0901-0950/0912-sort-an-array.py
1,288
4.1875
4
''' Author : MiKueen Level : Medium Problem Statement : Sort an Array Given an array of integers nums, sort the array in ascending order. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] Constraints: 1 <= nums.length <= 50000 -50000 <= nums[i] <= 50000 ''' # Using Merge Sort # Time Complexity - O(nlog(n)) # Space Complexity - O(n) class Solution: def mergeArray(self, left, right, nums): l, r = len(left), len(right) i = j = k = 0 while i < l and j < r: if left[i] <= right[j]: nums[k] = left[i] i += 1 else: nums[k] = right[j] j += 1 k += 1 while i < l: nums[k] = left[i] i += 1 k += 1 while j < r: nums[k] = right[j] j += 1 k += 1 return nums def sortArray(self, nums: List[int]) -> List[int]: if len(nums) < 2: return nums n = len(nums) mid = n // 2 left, right = nums[:mid], nums[mid:] self.sortArray(left) self.sortArray(right) self.mergeArray(left, right, nums) return nums
25f45c29ccbc7dfc012d551cd54419049de4edb4
mlr0929/FluentPython
/03DictAndSet/merge_two_dict.py
471
3.765625
4
""" In Python 3.5 or greater: z = {**x, **y} >>> x = {'a': 1, 'b': 2} >>> y = {'b': 3, 'c': 4} >>> z = {**x, **y} >>> z['a'] 1 >>> z['b'] 3 >>> z['c'] 4 In Python 2, (or 3.4 or lower) write a function >>> x = {'a': 1, 'b': 2} >>> y = {'b': 3, 'c': 4} >>> z = x.copy() # make a copy >>> z.update(y) # update with y, after changing z with success, return None >>> z['a'] 1 >>> z['b'] 3 >>> z['c'] 4 """ if __name__ == "__main__": import doctest doctest.testmod()
ad6580417b74b8c8626a41a2fcbf65aa45857f16
moidshaikh/hackerranksols
/chegg/piglatin.py
1,442
4.15625
4
''' Write a program that reads lines of input from the user and converts each line into "Pig Latin."' Pig Latin is English with the initial consonant sound moved to the end of each word, followed by "ay". Words that begin with vowels simply have an "ay" appended. Your program should continuously prompt the user for sentences until they enter a blank line, at which point the program should terminate. ''' def pig_latin(sentence): # splitting sentence into list of words sentence = sentence.split() for k in range(len(sentence)): word = sentence[k] # condition 1: if word begins with a Vowel, we have to add 'ay' with the word if word[0] in ['a', 'e', 'i', 'o', 'u']: sentence[k] = word + 'ay' # condition 2: if word contains numbeers, we display it as is elif not word.isalpha(): sentence[k] = word # condition 3: if word begins with a Consonant, we move initial consonant and add 'ay' to it. else: sentence[k] = word[1:] + word[0] + 'ay' # Joining the newly created pig-latin words return ' '.join(sentence) # user_input = input() print("Enter blank line at anytime to terminate the program.") while True: input_sentence = input() # below code is to get input lines until user puts blank line to terminate program if input_sentence == "": break else: print(pig_latin(input_sentence))
ef3c2c2ad7a5f1dfa5b6cf93f5e70d65be38a94f
PatrykJurczyk/Wizualizacja_Danych
/Python Ćwiczenia 5/2.py
290
3.765625
4
class Kwadrat: def __init__(self, x=0): """Konstuktor punktu.""" self.x = x def __add__(self, point): return Kwadrat(self.x + point.x) def __str__(self): return f'Kwadrat {self.x}' p1 = Kwadrat(3) p2 = Kwadrat(2) p3 = p1 + p2 print(p3)
8fa845bf5ce0f4a3b269d6f584180218db85e0de
Nick-FF/Python-Basics
/Car.py
1,369
3.9375
4
class Car: speed = 60 color = "red" name = "DeLorean" is_police = False def go(self): print("Машина поехала") def stop(self): print("Машина остановилась") def turn(self, d): if d: print("Поворот направо") else: print("Поворот налево") def show_speed(self, spd=90): print("Превышение скорости") class TownCar(Car): def show_speed(self, spd=60): if spd > 60: print("Превышена скорость") class WorkCar(Car): def show_speed(self, spd=40): if spd > 40: print("Превышена скорость") class SoprtCar(Car): pass class PoliceCar(Car): pass a = TownCar() b = WorkCar() c = SoprtCar() d = PoliceCar() a.speed = 40 a.name = "Джин" a.color = "Yellow" a.is_police = False b.speed = 40 b.name = "Крепыш" b.color = "White" b.is_police = False c.speed = 100 c.name = "Supreme" c.color = "dark-red" c.is_police = False d.speed = 100 d.name = "Cop" d.color = "white-blue" d.is_police = True a.go() a.show_speed(a.speed) a.turn(True) a.stop() b.go() b.show_speed(b.speed) b.turn(True) b.stop() c.go() c.show_speed(c.speed) c.turn(False) c.stop() d.go() d.show_speed(d.speed) d.turn(True) d.stop()
62f04c0f44a5bb271b794b869c39e60de871d2d6
DKU-STUDY/Algorithm
/programmers/난이도별/level02.땅따먹기/Go-yj.py
1,384
3.578125
4
''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12913# 문제 : 땅따먹기 처음에는 index가 같을 때 (직전 반복에서의 두번째로 큰수+지금의 제일 큰수), (직전 반복에서의 제일 큰수+지금의 두번째로 큰 수)를 구해서 비교해서 answer에 바로바로 더하고 수정하는 방식으로 풀이하였습니다. 그러니까 풀이도 너무 복잡해지고 다 틀렸다고 나와서 다른 사람들 질문을 보고 동적 프로그래밍을 사용해야 하는 문제임을 알았습니다. index가 같을 때는 직전에서 두번째로 큰 값을, index가 다를 때는 직전에서 제일 큰 값을 land에 바로 더하여 문제를 해결하였습니다. 다른 사람들 풀이를 보니 index를 비교하지도 않고, max값과 두번째로 큰 값을 구하지도 않는 대단한 풀이가 있더라구요! ★ ω ★ [메모] land[i][j] = max(land[i-1][:j]+land[i-1][j+1:]) + land[i][j] ''' def solution(land): first, second = max(land[0]), sorted(land[0])[-2] index = land[0].index(first) for i in range(1, len(land)) : for j in range(4) : if index==j : land[i][j] += second else : land[i][j] += first first, second = max(land[i]), sorted(land[i])[-2] index = land[i].index(first) return max(land[-1])
c83b1c78f68bfd5538e0984662394ee0d98713d7
wienerjon/Futoshiki-Puzzle-Solver
/sourceCode.py
9,915
3.6875
4
def readInput(filename): # reads the input file and returns the initial board # and the inequality constraints f = open(filename, "r") initialValues = [] for x in range(5): # get the initial board line = f.readline() lineArray = line.split() lineArray = [int(y) for y in lineArray] initialValues.append(lineArray) f.readline() horizontalIneq = [] # get the horizontal inequalities constraints for x in range(5): line = f.readline() lineArray = line.split() horizontalIneq.append(lineArray) f.readline() verticalIneq = [] # get the vertical inequalities constraints for x in range(4): line = f.readline() lineArray = line.split() verticalIneq.append(lineArray) return initialValues, horizontalIneq, verticalIneq # end readInput def createDomains(values): # create the domain for each variable based off the initial board domains = {} for i in range(5): for j in range(5): if (values[i][j] != 0): # if a value is not assigned, domain is that value domains[(i, j)] = [values[i][j]] else: # else it is 1-5 domains[(i, j)] = [1, 2, 3, 4, 5] return domains # end createDomains def setUpConstraints(horizontalIneq, verticalIneq): # compiles the constraints for each variable constraints = [] for k in range(5): constraints.append([' ', ' ', ' ', ' ', ' ']) for i in range(5): # adds constrains from horizontal inequalities for j in range(4): if horizontalIneq[i][j] == '<': # < constraints[i][j] += 'ltR ' constraints[i][j+1] += 'gtL ' elif horizontalIneq[i][j] == '>': # > constraints[i][j] += 'gtR ' constraints[i][j+1] += 'ltL ' for i in range(4): # adds constrains from vartical inequalities for j in range(5): if verticalIneq[i][j] == '^': # ^ constraints[i][j] += 'ltD ' constraints[i+1][j] += 'gtU ' elif verticalIneq[i][j] == 'v': # v constraints[i][j] += 'gtD ' constraints[i+1][j] += 'ltU ' return constraints # end setUpConstraints def forwardChecking(values, domains): # applies forward checking to the initial board repeat = False # keeps track if forward checking needs to be applied again for i in range(5): for j in range(5): if len(domains[(i, j)]) == 1: # if value is assigned to variable currVal = values[i][j] # remove the value from the domain of other variables in the same row & col for k in range(5): if k != i: try: domains[(k, j)].remove(currVal) if len(domains[(k, j)]) == 0: # if a domain is empty, no solution return False elif len(domains[(k, j)]) == 1: # if domain has one value, rerun forward checking repeat = True except: pass if k != j: try: domains[(i, k)].remove(currVal) if len(domains[(i, k)]) == 0: # if a domain is empty, no solution return False elif len(domains[(i, k)]) == 1: # if domain has one value, rerun forward checking repeat = True except: pass elif len(domains[(i, j)]) == 0: # if a domain is empty, no solution return False return domains, repeat # end forwardChecking def isConsistent(var, value, values, constraints): # check is assignment is consistent with constraints (i, j) = var for k in range(5): # check if value is already assigned to a variable in the same row or col if values[k][j] == value and k != i: return False if values[i][k] == value and k != j: return False if constraints[i][j] == ' ': # if no constraint, assignment is consistent return True # check if all constrains are consistent. if they are not, return false try: # x < y if 'ltR' in constraints[i][j] and values[i][j+1] != 0 and not(value < values[i][j+1]): return False except: pass try: # x > y if 'gtR' in constraints[i][j] and values[i][j+1] != 0 and not(value > values[i][j+1]): return False except: pass try: # y > x if 'ltL' in constraints[i][j] and values[i][j-1] != 0 and not(values[i][j-1] > value): return False except: pass try: # y < x if 'gtL' in constraints[i][j] and values[i][j-1] != 0 and not(values[i][j-1] < value): return False except: pass try: # x ^ y if 'ltD' in constraints[i][j] and values[i+1][j] != 0 and not(value < values[i+1][j]): return False except: pass try: # x v y if 'gtD' in constraints[i][j] and values[i+1][j] != 0 and not(value > values[i+1][j]): return False except: pass try: # y ^ x if 'gtU' in constraints[i][j] and values[i-1][j] != 0 and not(values[i-1][j] < value): return False except: pass try: # y v x if 'ltU' in constraints[i][j] and values[i-1][j] != 0 and not(values[i-1][j] > value): return False except: pass return True # end isConsistent def isCompleted(values): # checks if board is complete for i in range(5): for j in range(5): if values[i][j] == 0: return False return True # end isCompleted def mostConstrained(values, i, j): # returns the amount that a variable is constrained domain = [1,2,3,4,5] for k in range(5): if k != i and values[k][j] != 0: try: domain.remove(values[k][j]) except: pass if k != j and values[i][k] != 0: try: domain.remove(values[i][k]) except: pass return len(domain) # returns the about of possible values # end mostConstrained def mostConstraining(values, i, j): # finds the amount of variables constrained by location (i, j) res = 0 for k in range(5): if k != i and values[k][j] == 0: res += 1 if k != j and values[i][k] == 0: res += 1 return res # end mostConstraining def getBestHeuristic(values): # finds the variable with the best heuristic # finds most constrained remaining = 6 best = ([], remaining) for i in range(5): for j in range(5): if values[i][j] == 0: amtConstrained = mostConstrained(values, i, j) if (amtConstrained == best[1]): best[0].append((i, j)) elif amtConstrained < best[1]: best = ([(i, j)], amtConstrained) #TODO # if there is no tie, return the most constrained variable if len(best[0]) == 1: return best[0][0] # else, find the most constraining variable # most constraining ties = best[0] mostConstaining = (None, -1) for location in ties: (i, j) = location currConstaints = mostConstraining(values, i, j) if currConstaints > mostConstaining[1]: mostConstaining = (location, currConstaints) return mostConstaining[0] # end getBestHeuristic def backtracking(assignments, domains, constraints): # backtracking algo if isCompleted(assignments): # check if board is complete return assignments # return solution var = getBestHeuristic(assignments) # get next variable to assign originalDomain = domains[var] # save original domain (i, j) = var for value in domains[var]: # loop through domain values for the variable if isConsistent(var, value, assignments, constraints): # check if domain value is consistent with constraints assignments[i][j] = value domains[var] = [value] result = backtracking(assignments, domains, constraints) # assign value and run backtracking again if result != False: # if the result is not a failure, return the solution return result assignments[i][j] = 0 domains[var] = originalDomain return False # return failure # end backtracking def main(inputFilename, outputFile): values, horizontalIneq, verticalIneq = readInput(inputFilename) # get values and constraints from input txt domains = createDomains(values) # get domain values try: domains, repeat = forwardChecking(values, domains) # run forward checking except: print("There is no solution") exit() while (repeat): # repeat forwardChecking if necessary try: domains, repeat = forwardChecking(values, domains) except: print("There is no solution") exit() constraints = setUpConstraints(horizontalIneq, verticalIneq) # get constraints res = backtracking(values, domains, constraints) # run backtracking out = open(outputFile, "w") # write result to output file try: for row in res: line = '' for x in row: line += str(x) line += ' ' out.write(line+'\n') except: out.write('No solution found') out.close() # end main main("input1.txt", "output1.txt")
63532875dceb1babfb82fe871b627bd0c7632b38
Vhyun/eureka-lang
/Python3/loop.py
277
4.34375
4
print("Now let's learn more about loops in python") print("Suppose we have to print numbers from 1 to 10") #for loops for number in range(1, 11): print(number) print('print even numbers upto 20') #while loop i = 1 while i<20: if i%2==0: print(i) i = i+1
f48a6ac6a0e1c4e07260655348d3c0df145533f2
jamwomsoo/Algorithm_prac
/2018 카카오 블라인드 테스트/셔틀버스.py
1,446
3.609375
4
def turn_to_hour(second): hour = second//60 second %=60 if 0<=hour<10: hour= '0'+str(hour) else: hour = str(hour) if 0<=second<10: second ='0'+str(second) else: second = str(second) return hour+':'+second def solution(n, t, m, timetable): answer = '' table = [] dic={} for time in timetable: tmp = time.split(':') a = int(tmp[0])*60+int(tmp[1]) table.append(a) table.sort() bus = [(540 +t*i,0,None) for i in range(n)] bus_index = crew_index = 0 while crew_index<len(table): crew = table[crew_index] if bus_index == len(bus): break if crew<=bus[bus_index][0] and bus[bus_index][1]<m: second,member_cnt,last = bus[bus_index] bus[bus_index] = (second,member_cnt+1,crew) crew_index+=1 else: bus_index+=1 answer = bus[-1][0] if bus[-1][2]: if bus[-1][1] == m: answer = bus[-1][2]-1 answer = turn_to_hour(answer) return answer # print(solution(1,1,5,["08:00", "08:01", "08:02", "08:03"])) # print(solution(2,10,2,["09:10", "09:09", "08:00"])) # print(solution(2,1,2,["09:00", "09:00", "09:00", "09:00"])) print(solution(1,1,1, ["23:59"])) print(solution(10,60,45,["23:59","23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59"]))
fba389b27e0a398436b61ec86627f08919fc9991
Mschikay/leetcode
/3longestsubstring.py
1,578
4.15625
4
''' append是作为一个整体追加 extend是整体且字符串会被拆分 insert是整体并且是特定位置添加 ''' #这是最长子序列???? # def solve(string): # length = 1 # i = 1 # res = [string[0]]+[""] * (len(string)-1) # while i < len(string): # res[i] = res[i-1] # if string[i] not in res[i]: # res[i] = res[i] + string[i] # else: # j = i-1 # while string[j] not in res[i]: # res[i] = string[j:i+1] # j -= 1 # i += 1 # print(res) # return def solve(string): charmap = dict() length = 1 i = 1 res = [string[0]]+[""] * (len(string)-1) flag = 0 while i < len(string): res[i] = res[i-1] # 如果这是一个没有重复出现的字母,那么这个位置的最优结果加上这个字母 if string[i] not in res[i]: res[i] = res[i] + string[i] #如果重复了,就往前找开始重复的地方 这个位置的最优结果为一个新的字符串 #比如在第3个位置就是"sw",第6个位置是ekw else: if charmap[string[i]] >= flag: flag = charmap[string[i]] + 1 res[i] = string[flag:i+1] charmap[string[i]] = i # 存最长子串的长度 if len(res[i]) >= length: length = len(res[i]) i += 1 for substring in res: if len(substring) == length: print(substring) return if __name__ == "__main__": solve("awswekwo")
31e0b564c54aac12450e149d92cba33cff7ec90a
vickyliau/CensusClassificationAPI
/test_predict.py
5,070
3.765625
4
""" Unit Tests for Income Prediction author: Yan-ting Liau date: October 16, 2021 """ import pandas as pd from app.predict import Income, incomemodel from fastapi.testclient import TestClient model = incomemodel() from app.main import app client = TestClient(app) def test_preprocessing(): """ Test whether the column exists and the data type is correct input: data: pandas dataframe output: None """ data, _ = model.preprocessing() required_columns = { "age": pd.api.types.is_integer_dtype, "fnlwgt": pd.api.types.is_integer_dtype, "education_num": pd.api.types.is_integer_dtype, "capital_gain": pd.api.types.is_integer_dtype, "capital_loss": pd.api.types.is_integer_dtype, "hours_per_week": pd.api.types.is_integer_dtype, "income": pd.api.types.is_integer_dtype, } # Check columns assert set(data.columns.values).issuperset(set(required_columns.keys())) for col_name, format_verification_funct in required_columns.items(): assert format_verification_funct( data[col_name] ), f"Column {col_name} failed test {format_verification_funct}" def test_preprocessing_classes(): """ Test whether the classes exist in the column input: data: pandas dataframe output: None """ data, _ = model.preprocessing() # Check that only the known classes are present known_classes = [1, 0] assert data["income"].isin(known_classes).all() def test_twoclasses(): """ Test whether two classes in training data input: data: pandas dataframe output: None """ data, _ = model.preprocessing() assert len(set(data["income"])) > 1 def test_preprocessing_ranges(): """ Test whether the range of the columnis correct input: data: pandas dataframe output: None """ data, _ = model.preprocessing() ranges = { "age": (15, 95), "education_num": (0, 30), "hours_per_week": (0, 100) } for col_name, (minimum, maximum) in ranges.items(): assert data[col_name].dropna().between(minimum, maximum).all() def test_trainingpred_two_classes(): """ Test whether two classes are successfully predicted in training data input: data: pandas dataframe training data model.train() output: None """ data, _ = model.preprocessing() indep_variable = data.copy() indep_variable.pop("income") classes = model.train().predict(indep_variable) assert len(set(classes)) > 1 def test_testingpred_two_classes(): """ Test whether two classes are successfully predicted in testing data input: data: pandas dataframe testing data model.test_val() output: None """ _, data = model.preprocessing() indep_variable = data.copy() indep_variable.pop("income") classes = model.test_val()[0] assert len(set(classes)) > 1 def test_read_root(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "Welcom to Income Prediction API"} def test_income_pred_api(inputincome = { "age": 30, "workclass": "State-gov", "fnlwgt": 77516, "education": "Masters", "education-num": 15, "marital-status": "Never-married", "occupation": "Prof-specialty", "relationship": "Not-in-family", "race": "White", "sex": "Female", "capital-gain": 2174, "capital-loss": 0, "hours-per-week": 40, "native-country": "United-States", "income": 1 }): response = client.post("/income_prediction", json=inputincome) assert response.status_code == 200 def test_income_pred_type(): response = client.get("/income_prediction") assert type(response.json()) == type({ "id": "idid", "name": "namename", "description": "descriptiondescription", }) def test_income_pred_value0(inputincome = { "age": 30, "workclass": "State-gov", "fnlwgt": 77516, "education": "Masters", "education-num": 15, "marital-status": "Never-married", "occupation": "Prof-specialty", "relationship": "Not-in-family", "race": "White", "sex": "Female", "capital-gain": 2174, "capital-loss": 0, "hours-per-week": 40, "native-country": "United-States", "income": 1 }): response = client.post("/income_prediction", json=inputincome) assert response.json()['prediction'] == 0 def test_income_pred_value1(inputincome = { "age": 38, "workclass": "Self-emp-inc", "fnlwgt": 99146, "education": "Bachelors", "education-num": 13, "marital-status": "Married-civ-spouse", "occupation": "Exec-managerial", "relationship": "Husband", "race": "White", "sex": "Male", "capital-gain": 15024, "capital-loss": 0, "hours-per-week": 80, "native-country": "United-States", "income": 1 }): response = client.post("/income_prediction", json=inputincome) assert response.json()['prediction'] == 1
2a5fbdcbee9c893a7f4a1c0dea7eb64df864bdac
turamant/Chess
/chess_1.py
1,700
4.0625
4
class ChessFigure: """Chess piece class""" IMG = None def __init__(self, color): self.color = color def __repr__(self): return self.IMG[self.color] class Pawn(ChessFigure): IMG = ('♙', '♟︎') class King(ChessFigure): IMG = ('♔', '♚') class Queen(ChessFigure): IMG = ('♕', '♛') class Elephant(ChessFigure): IMG = ('♗', '♝') class Horse(ChessFigure): IMG = ('♘', '♞') class Rook(ChessFigure): IMG = ('♖', '♜') class ChessBoard: """Chess board class""" def __init__(self): self.board = [['.']*8 for y in range(8)] self.placing_pawn() self.placing_figure() def placing_pawn(self): """Placement of pawns on the chessboard """ for pawn in range(0, 8): self.board[1][pawn] = Pawn(0) # color white self.board[6][pawn] = Pawn(1) # color black def placing_figure(self): """Arrangement of pieces on the chessboard """ for f in range(0, 8, 7): if f == 0: color = 0 # white color else: color = 1 # black color self.board[f][0] = Rook(color) self.board[f][1] = Horse(color) self.board[f][2] = Elephant(color) self.board[f][3] = King(color) self.board[f][4] = Queen(color) self.board[f][5] = Elephant(color) self.board[f][6] = Horse(color) self.board[f][7] = Rook(color) def __repr__(self): res = '' for i in range(8): res += ''.join(map(str, self.board[i])) + '\n' return res if __name__ == '__main__': print(ChessBoard())
1620f97ff4084b3a688b14ac61e94fb31fdf37a7
misteraekkyz/CP3-Aekkarat-Phoburana
/Assignments/Lecture53_Aekkarat_P.py
172
3.875
4
def vatCalculator(totalPrice): result = totalPrice+(totalPrice*7/100) return result Price = int(input("Enter Price : ")) print("Total is : ",vatCalculator(Price))
948c7f81b1251819eb5be208fefa6a79e7e8a091
GabrieldeBlois/matchingCourse
/src/code/multivariate_analysis/titanic/pandas_infos.py
1,063
3.671875
4
import pandas as pd # Load the data to a pandas dataframe df = pd.read_csv("./input/titanic.csv") # general info on the dataframe print('---\ngeneral info on the dataframe') print(df.info()) # print the columns of the dataframe print('---\ncolumns of the dataset') print(df.columns) # print the first 10 lines of the dataframe print('---\nfirst lines') print(df.head(10)) # print the correlation matrix of the dataset print('---\nCorrelation matrix') print(df.corr()) # print the standard deviation print('---\nStandard deviation') print(df.std()) # get specific values in the dataframe passenger_id = 25 print('---\nall info on passenger ' + str(passenger_id)) print(df.loc[passenger_id]) print('---\nage of passenger ' + str(passenger_id)) print(df.loc[passenger_id]['Age']) print(df.loc[passenger_id]['Name']) print(df.loc[passenger_id]['Sex']) print(df.loc[passenger_id]['Survived']) print(df.loc[passenger_id]['Embarked']) print(df.loc[passenger_id]['Cabin']) print(df.loc[passenger_id]['Pclass']) __import__('ipdb').set_trace() # ipdb.set_trace()
d2d84244449b3a935abc18e37d62a852399c0ca4
Manas02/Advent-of-code
/day-5/day-5-2.py
509
3.546875
4
def fun(string): a = [] for i in string: if i == 'F' or i == 'L': a.append('0') elif i == 'B' or i == 'R': a.append('1') return ''.join(a) with open('input.txt') as f: data = f.read().splitlines() b = [] for line in data: row = int(fun(line[:7]), 2) col = int(fun(line[-3:]), 2) index = row * 8 + col b.append(index) b.sort() missing = [x for x in range(b[0], b[-1]+1) if x not in b] print(missing[0])
604d34285aeb11a89fd1db4156bc6ac983109b6c
lillySingh90/heroVsMonsterGame
/main_console.py
1,216
3.578125
4
import threading import time # global variables hero_health = 40 orc_health = 7 dragon_health = 20 def thread_orc(): global hero_health global orc_health while orc_health > 0 and hero_health > 0: time.sleep(1.5) hero_health = hero_health - 1 print("Orc attacked... Hero health: ", hero_health) def thread_dragon(): global hero_health global dragon_health while dragon_health > 0 and hero_health > 0: time.sleep(2.0) hero_health = hero_health - 3 print("Dragon attacked... Hero health: ", hero_health) # making threads for orc and dragon orc = threading.Thread(target=thread_orc) dragon = threading.Thread(target=thread_dragon) # to start the thread orc.start() dragon.start() # main user loop while hero_health > 0 and orc_health > 0 and dragon_health > 0: var = input("attack ") if var == "orc": orc_health = orc_health - 2 print("Hero attack Orc ... Orc health is ", str(orc_health)) elif var == "dragon": dragon_health = dragon_health - 2 print("Hero attack dragon ... Dragon health is ", str(dragon_health)) # Wait for threads to finish orc.join() dragon.join()
b1e6d69006f60a34ce11e84ee72eae00c4f95a6f
joshfinnie/advent-of-code
/2020/day-06/part1.py
204
3.65625
4
import sys def calc(string): count = 0 for line in string.split("\n\n"): count += len(set(line) - {' ', '\n'}) return count with open(sys.argv[1]) as f: print(calc(f.read()))
3fcaa8080d2ddc63113c9187da9c4ef7be12d943
elliotjberman/algorithms
/pt2_week3/knapsack_recursive.py
566
3.65625
4
# Come back to this import time loaded_items = [] with open('knapsack_big.txt') as f: first = True for line in f: split_line = line.split() if first: knapsack_size = int(split_line[0]) else: loaded_items.append((int(split_line[0]), int(split_line[1]))) first = False print('Finished reading input') def knapsack(items, capacity, starting_index=0): weight = items[0][1] if capacity < 1: value = 0 else: value = knapsack(items, capacity-weight, starting_index + 1) return value result = knapsack(loaded_items, knapsack_size) print(result)
a69df3a8f2a55d48982db68729a929d49e482205
Crisescode/leetcode
/Python/LinkedList/141. linked_list_cycle.py
1,318
3.875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # https://leetcode-cn.com/problems/linked-list-cycle/ """ Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next Pointer. Internally, pos is used to denote the index of the node that tail's next Pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. """ from utils import ListNode class Solution: def hasCycle(self, head: ListNode) -> bool: if head is None: return False slow, fast = head, head count = 1 while fast and fast.next: fast = fast.next.next slow = slow.next print("==count", count) if fast == slow: return True count += 1 return False if __name__ == "__main__": l3 = l3_1 = ListNode(3) l3_1.next = ListNode(2) l3_1 = l3_1.next l3_1.next = ListNode(0) l3_1 = l3_1.next l3_1.next = ListNode(-4) l3_1 = l3_1.next l3_1.next = ListNode(2) # l3_1 = l3_1.next # l3_1.next = ListNode(3) print(Solution().hasCycle(l3))
f93a36c23f3410c95ad85bd074ce2707a4128d06
jxie0755/Learning_Python
/LeetCode/LC541_reverse_string_ii.py
1,894
3.734375
4
# LC541 Reverse String II # Easy # Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. # If there are less than k characters left, reverse all of them. # If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. # Restrictions: # The string consists of lower English letters only. # Length of the given string and k will in the range [1, 10000] # """ # :type s: str # :type k: int # :rtype: str # """ class Solution: def reverseStr(self, s, k): # O(n) method, while loop to move 2k length string along start = 0 result = "" while start <= len(s): result += s[start:start + k][::-1] + s[start + k: start + 2 * k] start += 2 * k return result def reverseStr(self, s, k): # still O(n) but use slice with step, simpler codes use for loop result = "" for i in range(0, len(s), 2 * k): result += s[i:i + k][::-1] + s[i + k:i + 2 * k] return result def reverseStr(self, s, k): # a recursive O(n) way. return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k) if s else "" # Don't forget the last part to prevent infinite recursion on empty string if __name__ == "__main__": assert Solution().reverseStr("abcdefg", 2) == "bacdfeg", "regular" assert Solution().reverseStr("abcdefg", 1) == "abcdefg", "k=1, do nothing" assert Solution().reverseStr("abcdefghi", 2) == "bacdfeghi", "one extra" assert Solution().reverseStr("abcdefgh", 3) == "cbadefhg", "partial reverse" assert Solution().reverseStr("abcdefgh", 2) == "bacdfegh", "double length" assert Solution().reverseStr("abcdefg", 10) == "gfedcba", "k > len(s), complete reverse" print("All passed")
c5f370b570163a20288541dc2c9aa121a8a1f64e
lroolle/CodingInPython
/leetcode/365_water_jug_problem.py
952
3.75
4
"""LeetCode 365. Water and Jug Problem > You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end. - Operations allowed: 1. Fill any of the jugs completely. 2. Empty any of the jugs. 3. Pour water from one jug into another till the other jug is completely full or the first jug itself is empty. - Example 1: (From the famous "Die Hard" example) Input: x = 3, y = 5, z = 4 Output: True - Example 2: Input: x = 2, y = 6, z = 5 Output: False """ def gcd(x, y): if x == 0: return y return gcd(y % x, x) def can_measure_water(x, y, z): if x > y: x, y = y, x g = gcd(x, y) return z % g == 0 and z <= (x + y) print(can_measure_water(3, 5, 4))
7412acf2022c4a9509ddd22859ba8f85422abf57
fobbytommy/Algorithm-Practice
/10_week_2/nth_largest.py
386
4.34375
4
# Given an array, return the Nth-largest element from python_modules import bubble_sort def nth_largest(arr, n): list_length = len(arr) if n <= 0 or list_length < n: return None sorted_arr = arr bubble_sort.bubble_sort(sorted_arr) return sorted_arr[list_length - n] arr = [23, 32, -2 , 6 ,2 ,7, 10, 3, 10, 22, 3, -1, 19, 24, 33] result = nth_largest(arr, 3) print(result)
6ae77b4b8678cac5f7a6b75d90b71cedabd41815
thomlomDEV/Ascii-Art-Generator
/Main.py
2,879
3.578125
4
from PIL import Image import os file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'Image') img = Image.open(os.path.join(file_path, 'kubrick.jpg')).convert('L') pixel = img.load() (img_width, img_height) = img.size if img_width > 700 or img_height > 700: print('This image is too large, for your own good it will not be converted') quit() img_xrange = range(0, img_width, 1) img_yrange = range(0, img_height - 1, 2) The_Matrix = [[0 for i in img_xrange] for j in img_yrange] def Average_Colour(pixel_x, pixel_y): ''' Takes the average grayscale value between two vertical pixels ''' pixel_1 = pixel[pixel_x, pixel_y] pixel_2 = pixel[pixel_x, pixel_y +1] avg_colour = (pixel_1 + pixel_2)/2 return(avg_colour) # Converts Grayscale to Ascii def Ascii(The_Matrix, img_xrange, img_yrange): ''' Converts a Matrix of grayscale values into a Matrix of Ascii characters, standerdizing the colour range in the process ''' lowest = max(max(The_Matrix)) highest = min(min(The_Matrix)) difference = lowest - highest for i in img_xrange: for j in img_yrange: if The_Matrix[int(j/2)][i] <= 1*difference/11: The_Matrix[int(j/2)][i] = ord('@') elif The_Matrix[int(j/2)][i] <= 2*difference/11: The_Matrix[int(j/2)][i] = ord('%') elif The_Matrix[int(j/2)][i] <= 3*difference/11: The_Matrix[int(j/2)][i] = ord('#') elif The_Matrix[int(j/2)][i] <= 4*difference/11: The_Matrix[int(j/2)][i] = ord('+') elif The_Matrix[int(j/2)][i] <= 5*difference/11: The_Matrix[int(j/2)][i] = ord('=') elif The_Matrix[int(j/2)][i] <= 6*difference/11: The_Matrix[int(j/2)][i] = ord('~') elif The_Matrix[int(j/2)][i] <= 7*difference/11: The_Matrix[int(j/2)][i] = ord(':') elif The_Matrix[int(j/2)][i] <= 8*difference/11: The_Matrix[int(j/2)][i] = ord('-') elif The_Matrix[int(j/2)][i] <= 9*difference/11: The_Matrix[int(j/2)][i] = ord(',') elif The_Matrix[int(j/2)][i] <= 10*difference/11: The_Matrix[int(j/2)][i] = ord('.') else: The_Matrix[int(j/2)][i] = ord(' ') return The_Matrix def print_ascii_image(matrix): """Takes a 2D matrix of ASCII values as input and prints out an image of ASCII characters based on matrix values.""" for row in matrix: for i in range(len(row)): if (i != len(row)-1): print(chr(row[i]), end='') else: print(chr(row[i])) #The Loops for i in img_xrange: for j in img_yrange: The_Matrix[int(j/2)][i] = Average_Colour(i, j) The_Matrix = Ascii(The_Matrix, img_xrange, img_yrange) print_ascii_image(The_Matrix)
8625566b08c25ec900699d671a91bd25547e3085
mongoz/Osnovy_prog_HSE
/week_1/q8.py
432
4.03125
4
"""Дано трехзначное число. Найдите сумму его цифр. Формат ввода Вводится целое положительное число. Гарантируется, что оно соответствует условию задачи. Формат вывода Выведите ответ на задачу.""" n = int(input()) total = 0 for i in str(n): total += int(i) print(total)
f04114b30ca2d3b8cbcb9f0eff405810bd90c4b1
solouniverse/Python
/B2BSWE/Patterns/Prog_Asterisk.py
245
4.28125
4
print("Enter no of rows and columns to print asterisk") rows = int(input("Enter no of rows: ")) columns = int(input("Enter no of columns: ")) for row in range(rows): for col in range(columns): print("*", end="") print(end="\n")
7ca7a538f4c565f9374b407f664d9e4512f9344d
weizhengda/Python3
/code/4.第四章/5.集合/set.py
527
3.671875
4
## 1. 集合的特性 ## 1.1 set是无序的,没有下表索引,不支持列表的所有方法 type({1,2,3,4,5,6}) ## class 'set' ## 1.2 集合是不重复的 {1,1,2,2,3,3} ## {1,2,3} ## 2. 集合的方法 1 in {1,2,3} ## true 1 not in {1,2,3} ## false ## 集合的差集 {1,2,3,4,5,6} - {3,4} ## {1,2,5,6} ## 集合的交集 {1,2,3,4,5,6} & {3,4} ## {3,4} ## 集合的合集 {1,2,3,4,5,6} | {3,4,7} ## {1,2,3,4,5,6,7} ## 空的集合 type({}) ## class 'dict' type(set()) ## class 'set' len(set()) ## 0
96888613b588ec1022a4bb52e8ba0368110174e9
Inverseit/fifteen-puzzle
/gamelogic.py
3,748
3.8125
4
import random # from pynput import keyboard import os # Provides the game core for fifteen game class GameLogic(): def __init__(self, n): self.n = n self.board = self.getInitBoard() self.goal = self.getInitBoard() self.empty = (self.n-1, self.n-1) def isGameOver(self): return self.board == self.goal def __repr__(self): out = "" for i in self.board: for j in i: l = len(str(j)) if j == 0: p = "__" else: p = " " + str(j) if l == 1 else str(j) out += p + " " out += "\n" print(out, end="\r") return "" def getInitBoard(self): board = [] sz = self.n board = [[j for j in range(i*sz+1, (i+1)*sz+1)] for i in range(sz)] board[-1][-1] = 0 # make the last element 0 (empty) return board def getBoard(self): return self.board def shuffleBoard(self): # board = self.board l = 20 moves = ["U", "R", "L", "D"] cur = random.randint(0, 3) for i in range(l): if i != 1: prev = cur cur = random.randint(0, 3) # if sum is three is opposite moves, so no point doing it while cur + prev == 3: cur = random.randint(0, 3) self.moveDirection(moves[cur]) # do strict move to make empty on right bottom corner for _ in range(3): self.moveDirection("U") for _ in range(3): self.moveDirection("L") def getShuffleSeed(self): l = 50 seed = [] moves = ["U", "R", "L", "D"] cur = random.randint(0, 3) for i in range(l): if i != 1: prev = cur cur = random.randint(0, 3) # if sum is three is opposite moves, so no point doing it while cur + prev == 3: cur = random.randint(0, 3) seed += [moves[cur]] # do strict move to make empty on right bottom corner for _ in range(3): seed += ["U"] for _ in range(3): seed += ["L"] return seed # make move by some direction def moveDirection(self, direction): vector = {"U": (1, 0), "D": (-1, 0), "L": (0, 1), "R": (0,-1)} new = self.addTuples(self.empty, vector[direction]) if 0 <= new[0] < self.n and 0 <= new[1] < self.n: self.swap(*self.empty, *new) return True return False def reInit(self): self.board = self.getInitBoard() self.empty = (self.n-1, self.n-1) def moveByBlock(self,x, y): if (x > 0 and self.empty == (x - 1,y)): self.swap(x - 1, y, x, y) return True elif (y < self.n-1 and self.empty == (x,y + 1)): self.swap(x, y + 1, x, y) return True elif (x < self.n-1 and self.empty == (x + 1,y)): self.swap(x + 1, y, x, y) return True elif (y > 0 and self.empty == (x, y - 1)): self.swap(x, y - 1, x, y) return True else: return False # Swaps the value of two cells def swap(self, x1, y1, x2, y2): self.board[x1][y1] = self.board[x2][y2] self.board[x2][y2] = 0 self.empty = (x2,y2) @staticmethod def addTuples(t1, t2): # adds tuples componentwise return tuple(map(lambda i, j: i + j, t1, t2)) if __name__ == "__main__": a = GameLogic(4) a.shuffleBoard() print(a) # a.startListening() # print(a)
605a258ba6e0b9d475179b3b0bf0f642034df6c2
AndrewWoodcock/Advent-of-Code-2020
/Advent_of_Code_9.py
1,780
3.546875
4
# Part 1 Unsolved import itertools # xmas_data = "xmas_test.txt" xmas_data = "xmas.txt" # g_preamble = 5 g_preamble = 25 def get_file_data(filename: str) -> list: with open(filename, "r") as file: return [int(line.strip()) for line in file] def check_sum(lst: list, num: int) -> bool: for x, y in itertools.combinations(lst, 2): if x + y == num: return True return False def inspect_xmas(full_list: list, preamble: int) -> int: for element in enumerate(full_list): if element[0] >= preamble: test = element[1] test_list = full_list[(element[0] - preamble):element[0]] if not check_sum(test_list, test): return element[1] def find_less_reverse(full_list: list, target: int) -> int: for element in reversed(list(enumerate(full_list))): if element[1] < target: return element[0] def encrypt_weakness(trimmed_list: list, sum_target: int) -> int: i = 0 j = 1 curr_sum = trimmed_list[i] + trimmed_list[j] while curr_sum != sum_target: while curr_sum < sum_target: j += 1 curr_sum += trimmed_list[j] while curr_sum > sum_target: curr_sum -= trimmed_list[i] i += 1 contig = sorted(trimmed_list[i:j]) return sum([contig[0], contig[-1]]) def main(): xmas_list = get_file_data(xmas_data) result_1 = inspect_xmas(xmas_list, g_preamble) print("The part 1 result is {}".format(result_1)) upper_bound = find_less_reverse(xmas_list, result_1) + 1 trimmed_xmas_list = xmas_list[:upper_bound] result_2 = encrypt_weakness(trimmed_xmas_list, result_1) print("The part 2 result is {}".format(result_2)) if __name__ == '__main__': main()
9b525f3ef49aaecc2dcb412a13f7304c8844ded1
Python51888/CCY
/求一个数的阶乘.py
523
3.828125
4
#递归函数 # def f(num): # if num <= 1: # return 1 # return f(num-1)*num # pass # if __name__ == '__main__': # print(f(5)) ''' n!=1×2×3×...×n n!=1×2×3×...×(n-1)n n的阶乘是求n与(n-1)阶乘的乘积 前提是: n>=1 ''' #非递归实现 #假如求10的阶乘 1*2*3*4*5*6*7*8*9*10 def func(num): res = 1 for item in range(1,num+1): res *= item # print(item,end=' ') #10 print(res,end=' ') pass if __name__ == '__main__': func(10) pass
4713647128033982db4c5a5e22f9c2498a760e56
nilobud/Python_Learning
/fractal_tree.py
358
3.875
4
import turtle def tree(branchLen,t): if branchLen > 5: t.forward(branchLen) t.right(20) tree(branchLen-15,t) t.left(40) tree(branchLen-15,t) t.right(20) t.backward(branchLen) t = turtle.Turtle() t.shape("turtle") t.left(90) t.speed(0) t.up() t.backward(100) t.down() t.color("green") tree(150,t)
e873d675cb9b0e5dcb08dadb143d6985503428f9
Jordanzuo/Algorithm
/doublylinkedlistwithtail.py
2,462
4.03125
4
#!/usr/bin/python3 class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def get(self, data): if self.head == None: return None, False node = self.head while node != None: if node.data == data: return node, True else: node = node.next def push(self, value): self.append(value) def pop(self): if self.tail == None: return None, False else: node = self.tail self.remove(node) return node, True def traverse(self): if self.head == None: return node = self.head while node != None: print(node.data) node = node.next def append(self, data): newNode = Node(data) if self.head == None: self.head, self.tail = newNode, newNode else: newNode.prev = self.tail self.tail.next = newNode self.tail = newNode def insertBefore(self, item, data): if self.head == None or item == None: return # Create the new node newNode = Node(data) newNode.next = item if item == self.head: self.head.prev = newNode self.head = newNode else: newNode.prev = item.prev item.prev.next = newNode item.prev = newNode def insertAfter(self, item, data): if self.tail == None or item == None: return # Create the new node newNode = Node(data) newNode.prev = item if item == self.tail: item.next = newNode self.tail = newNode else: item.next.prev = newNode newNode.next = item.next item.next = newNode def remove(self, item): if item == None: return if self.head == self.tail: self.head, self.tail = None, None elif self.head == item: item.next.prev = None self.head = item.next elif self.tail == item: item.prev.next = None self.tail = item.prev else: item.next.prev = item.prev item.prev.next = item.next del(item)
1406b5098a2a3200dfabddba97bd8ac987e5da80
Ivan1931/pcog
/pcog/messages.py
1,476
3.6875
4
from typing import List class MessageType(object): EXIT = -1 POSITION_UPDATE = 0 HEALTH_UPDATE = 1 ENTITY_WATER_SOURCE = 2 ENTITY_PREDATOR = 3 ENTITY_PREY = 4 WORLD_ENTITY = 15 NEW_PERCEIVED_AGENT = 5 REMOVE_PERCEIVED_AGENT = 6 STAMINA_UPDATE = 7 HUNGER_UPDATE = 8 THIRST_UPDATE = 9 INVENTORY_UPDATE = 10 ITEM_EDIBLE = 11 NON_EDIBLE_ITEM = 12 SOUND_HEARD = 13 DAMAGE_TAKEN = 14 FACING_DIRECTION_UPDATE = 16 REINFORCEMENT = 17 RESTART = 18 TEMPERATURE_UPDATE = 19 NOOP = 1000 # The dummy message of the super class class Message(object): def __init__(self, message_text): # type: (str) -> None """ Creates a new message from some input string :param message_text: str text of the message received """ self.message_raw = Message.parse_message(message_text) self.id = int(self.message_raw[0]) def get_id(self): return self.id def get_type(self): raise NotImplementedError("Message type for base message class not implemented") @staticmethod def parse_message(message_text): # type: (str) -> List[str] """ Parses message text into a list of strings. Also trims their output :param message_text: :return: """ parsed = [] for m in message_text.split("$"): parsed.append(m.strip()) return parsed
705a5f076bf082fed7388a117a899aac8d0ccd75
ynonp/ex11-demo-solutions
/11_1.py
204
4.09375
4
list = [] counter = 1 for num in range(10): print(counter, " from 10") number = int(input("enter number\n")) list.append(number) counter += 1 print("the max num in list is: ", max(list))
14aac63a7916522ba61f381ce44deaba082c1103
trohit920/leetcode_solution
/python/476. Number Complement.py
1,056
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): a = '{0:b}'.format(num) s = '' for i in a: if i == '1': s = s + '0' else: s = s + '1' return int(s,2) if __name__ == '__main__': s = Solution() print "the Complement of an number is : " + str(s.findComplement(1))
f41896cd4099aa04c78d9b01828448ec05ba8cef
Langesae/NEAT-Stocks
/Data/wrapper.py
1,624
3.8125
4
import stockprediction as prediction import os import csv import pandas as pd import xlrd stock = '' stocks = ['AXP', 'BAC', 'BRK.B', 'CB', 'C', 'CME', 'GS', 'JPM', 'USB', 'WFC'] buyPre = 5 sellPre = 5 percentage = 0 buy = False sell = False hold = False FileName = os.getcwd() def calc (file, buyPre, sellPre, buy , sell, hold): with open(file) as f: reader = csv.reader(f) a = list(reader) prediction = float(a[-1][-1]) actual = float(a[-1][-2]) difference = prediction - actual percentage = (difference / actual) * 100 if percentage >= buyPre: buy = True elif percentage <= (sellPre * -1): sell = True else: hold = True return percentage, buy, sell, hold while True: use = input("Do you want to run the network. Y/N? ") if use == 'Y': buyPre = int(input("What is the percentage of gain for a buy? ")) sellPre = int(input("What is the percentage of loss for a sell? ")) print("Plug in Laptop network could overload internal battery") print(stocks) stock = input("What stock above would you like to use? ") while stock not in stocks: print("Not in list. Try again. ") stock = input("What stock above would you like to use? ") prediction.main(stock) FileName += '/Results/' + stock + '_Optimizer_Initializer_CostFunction_FinalPredictions.csv' percentage, buy, sell, hold = (calc(FileName, buyPre, sellPre, buy, sell, hold)) if sell == True: print("We advise you to sell " + stock + ".") elif buy == True: print("We advise you to buy " + stock + ".") elif hold == True: print("We advise you to hold " + stock + ".") elif use == 'N': break
9d7e4f2bb0d891d66e1cebdd22b2c6545833fb0b
LiYingbogit/pythonfile
/ustc_12_高级变量.py
721
4.21875
4
# 列表的操作 name_list = ["小明", "大飞", "小红", "小红"] # 取值取索引 print(name_list[2]) print(name_list.index("大飞")) # 修改 name_list[1] = "大大飞" # 增加 name_list.append("小花") # 删除 name_list.remove("小明") # 插入 name_list.insert(1, "小梅") # 扩展 temp_list = ["dafei", "daet"] name_list.extend(temp_list) # pop默认可以把最后一个数据删除 name_list.pop() # pop可以指定索引数据删除 name_list.pop(1) # clear整个列表删除 # name_list.clear() list_len = len(name_list) print("列表中包含%d个元素" % list_len) # 统计数据的次数 count = name_list.count("小红") print("小红出现的次数%d" % count) print(name_list) # help(list)
e7a6a64817e8ff7e5f57cd9bbeb7ca9051c0634a
wahdanEw/Python-Rock-Paper-Scissors-game
/game.py
1,450
4.15625
4
print ("***********************************") print ("WELCOME TO ROCK, PAPER, SCISSORS") print ("***********************************") ans = 'yes' x = input('whats your name?:') b = input('and your name?:') print('\nHello, ' + x) print('Hello, ' + b) while (ans != 'no'): player = x stuff_in_string = "\n{}, do you want to choose rock, paper or scissors?".format(player) print(stuff_in_string) answer1 = input() if (answer1 != 'rock') and (answer1 != 'paper') and (answer1 != 'scissors'): print ("You have not entered rock, paper or scissors\n Try again!") answer1 = input() player = b stuff_in_string = "{}, do you want to choose rock, paper or scissors?".format(player) print(stuff_in_string) answer2 = input() if (answer2 != 'rock') and (answer2 != 'paper') and (answer2 != 'scissors'): print ("You have not entered rock, paper or scissors\n Try again!") answer2 = input() if(answer1 == answer2): print ("It's a tie!") if (answer1 == 'rock') and (answer2 == 'paper') or (answer2 == 'rock') and (answer1 == 'paper'): print ("paper wins!") if (answer1 == 'scissors') and (answer2 == 'paper') or (answer2 == 'scissors') and (answer1 == 'paper'): print ("Scissors win!") if (answer1 == 'scissors') and (answer2 == 'rock') or (answer2 == 'scissors') and (answer1 == 'rock'): print ("Rock win!") print('Do you want to play again?') ans = input() if(ans == 'no'): print('Bye bye') exit()
6f5a32061557d7348b6d842dfb98839d7c6b8ab7
LinyiGuo96/PythonNotes
/One Python Course Notes/course3/Chap02/hello copy.py
216
3.953125
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x=123 print('Hello, World. {}'. format(x)) #python3 print('Hello, World. %d' %x) # python2, will be removed in the future perhaps print(f'Hello. {x}')
ca8943d7e6d79d55d8259bd68627ab91c654ea74
BIDMAL/codewarsish
/HackerRank/Data Structures/Trees/Binary Search Tree Lowest Common Ancestor.py
1,464
3.609375
4
class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class BinarySearchTree: def __init__(self): self.root = None def create(self, val): if self.root == None: self.root = Node(val) else: current = self.root while True: if val < current.info: if current.left: current = current.left else: current.left = Node(val) break elif val > current.info: if current.right: current = current.right else: current.right = Node(val) break else: break def lca(root, a, b): node = root while node: if max(a, b) < node.info: node = node.left elif min(a, b) > node.info: node = node.right else: break return node inp = ['6', '4 2 3 1 7 6', '1 7'] tree = BinarySearchTree() t = int(inp[0]) arr = list(map(int, inp[1].split())) for i in range(t): tree.create(arr[i]) v = list(map(int, inp[2].split())) ans = lca(tree.root, v[0], v[1]) print (ans.info)
787bf57b8ce7d389d9ab2a02cdcaccfe12253ce4
NULLCT/LOMC
/src/data/145.py
869
3.609375
4
def PaintColor(color): if color == "r": return "b" else: return "r" import queue as q N, Q = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(N - 1): ai, bi = map(int, input().split()) G[ai - 1].append(bi - 1) G[bi - 1].append(ai - 1) q = q.Queue() color = ["w"] * N q.put(0) now_color = "r" color[0] = now_color while q.qsize(): v = q.get() now_color = PaintColor(color[v]) for vv in G[v]: if color[vv] == "w": color[vv] = now_color q.put(vv) """ for i in range(N): print("Town" + str(i+1) + ": " + color[i]) """ Query = [] for _ in range(Q): ci, di = map(int, input().split()) ci -= 1 di -= 1 Query.append([ci, di]) for i in range(Q): if color[Query[i][0]] == color[Query[i][1]]: print("Town") else: print("Road")
734f584fd9bd7dfe0dbc205e086e8ba70ab00e5e
zjh0324/python
/demo03.py
1,384
3.890625
4
# class 声明类的名字 # 类的名字首字母必须大写 # 面向对象编程 # 类里面所有的方法都必须传一个参数,叫self class Girlfriend(): def __init__(self,sex,high,weight,hair,age): self.sex = sex self.high = high self.weight = weight self.hair = hair self.age = age def caiyi(self,num): if num == 1: print('胸口碎大石') if num == 2: print('唱跳RAP篮球') if num == 3: print('单手开瓶盖') def chuyi(self): print('精通八大菜系') def work(self): print('开挖掘机!') # # 类的实例化 # zhagnsan = Girlfriend('女','163cm','60kg','黑长直','22岁') # zhagnsan.caiyi(2) # zhagnsan.work() # print(zhagnsan.high) # print(zhagnsan.sex) # ''' # class Car(): # def __init__(self,pinpai,yanse,neishi,jilun): # self.pinpai = pinpai # self.yanse = yanse # self.neishi = neishi # self.jilun = jilun # def bianxing(self): # print('车子变身位金刚葫芦娃') # def fly(self): # print('车子开始起飞') # zhagnsan = Car('凯迪拉克','红色','豪华','独轮车') # zhagnsan.bianxing() class Nvpy(Girlfriend): def work(self): print('修电脑') object zhagnsan = Nvpy('女','165','120','短发','25') zhagnsan.work()
751259a41010803fe7117e20d5ef5c69d3a69d73
reroes/ejemploSiete
/c8/demo.py
92
3.78125
4
""" Es un ejemplo de Python """ c = 100 i = 0 while i < c: print(i) i = i + 1
d77ed6bc12657ce144d3cf5db3182821474463d1
mihirkelkar/languageprojects
/StInt/mirror_image_trees/tree_mirror_images.py
1,196
3.8125
4
class Node(obejct): def __init__(self, value): self.value = value self.left = None self.right = None class BsTree(object): def __init__(self): self.root = None self.traversal_list = list() def addNode(self, value, root = None): root = self.root if root is None else root if value <= root.value: if root.left != None: self.addNode(value, root.left) else: root.left = Node(value) else: if root.right != None: self.addNode(value, root.right) else: root.right = Node(value) def inorder_traversal(self, root = None): root = self.root if root is None else root if self.root == None: return if root.left != None: self.inorder_traversal(root.left) self.traversal_list.append(root.value) if root.right != None: self.inorder_traversal(root.right) def main(): #Checking if the two trees are mirror images is to check if their #inorder traversals are mirror images of one another tree1 = BSTree() tree2 = BSTree() if tree1.traversal_list == tree2.traversal_list[::-1]: return True else: return False if __name__ == "__main__": main()
4f12899c93f8a40e31551c8f24d15cdf05ed02a1
shchoice/TIL
/Python/OOP/test.py
250
3.703125
4
characters = 'ABCDE' codes = list(filter(lambda character: character > 66, map(ord, characters))) print(codes) # 67, 68, 69] characters = 'ABCDE' codes = [ord(character) for character in characters if ord(character) > 66] print(codes) # 67, 68, 69]
838a5bc9142e3714e281399aaf1698428f0262e1
advenral/Exercise
/5.11.py
428
3.9375
4
#Ex1 word= ['a', 'b'] print(word) first= word[-2] print("The first word is "+ first+ ".\n") a= [2, 3, 4] tmp= [] for i in a: tmp.append(i) tmp[-1]= 'last' print(a, tmp) #Ex2 num= list(range(9, 15, 2)) print(num) num[0]=12 print('change the first num') print(num) add= sum(num) print('\nSum is') print(add) print('Only first num changed') #Ex3 new_num= list(range(5, 0, -1)) print(new_num) print(list(range(9, -6, -2)))
ceb9510a6489f72b41888aa08cee6b985c0bb013
tomosh22/practical-5
/page_rank.py
5,266
3.5625
4
import os import time from progress import Progress from random import choice WEB_DATA = os.path.join(os.path.dirname(__file__), 'school_web.txt') def load_graph(fd): """Load graph from text file Parameters: fd -- a file like object that contains lines of URL pairs Returns: A representation of the graph. Called for example with >>> graph = load_graph(open("web.txt")) the function parses the input file and returns a graph representation. Each line in the file contains two white space seperated URLs and denotes a directed edge (link) from the first URL to the second. """ graph = {} # Iterate through the file line by line for line in fd: # And split each line into two URLs node, target = line.split() # if graph contains an array for node, append target to it if node in graph: graph[node].append(target) # else initialise an array for node containing target else: graph[node] = [target] return graph def print_stats(graph): """Print number of nodes and edges in the given graph""" print(f"{len(graph)} nodes and {sum(len(graph[x]) for x in graph)} edges") def stochastic_page_rank(graph, n_iter=1_000_000, n_steps=100): """Stochastic PageRank estimation Parameters: graph -- a graph object as returned by load_graph() n_iter (int) -- number of random walks performed n_steps (int) -- number of followed links before random walk is stopped Returns: A dict that assigns each page its hit frequency This function estimates the Page Rank by counting how frequently a random walk that starts on a random node will after n_steps end on each node of the given graph. """ hit_count = {} # initialize hit_count[node] with 0 for all nodes for x in graph: hit_count[x] = 0 # repeat n_iterations times: for x in range(n_iter): # current_node <- randomly selected node current_node = choice(list(graph)) # repeat n_steps times: for x in range(n_steps): # current_node with <- randomly chosen node among the out edges of current_node current_node = choice(graph[current_node]) # hit_count[current_node] += 1/n_iterations hit_count[current_node] += 1 / n_iter return hit_count def distribution_page_rank(graph, n_iter=100): """Probabilistic PageRank estimation Parameters: graph -- a graph object as returned by load_graph() n_iter (int) -- number of probability distribution updates Returns: A dict that assigns each page its probability to be reached This function estimates the Page Rank by iteratively calculating the probability that a random walker is currently on any node. """ node_prob = {} # initialize node_prob[node] = 1/(number of nodes) for all nodes for x in graph: node_prob[x] = 1 / len(graph) # repeat n_iterations times: for i in range(n_iter): # initialize next_prob[node] = 0 for all nodes next_prob = {} for node in graph: next_prob[node] = 0 # for each node for node in graph: # p <- node_prob[node] divided by its out degree p = node_prob[node] / len(graph[node]) # for each target among out edges of node: for target in graph[node]: next_prob[target] += p node_prob = next_prob return node_prob def main(): # Load the web structure from file web = load_graph(open(WEB_DATA)) # print information about the website print_stats(web) # The graph diameter is the length of the longest shortest path # between any two nodes. The number of random steps of walkers # should be a small multiple of the graph diameter. diameter = 3 # Measure how long it takes to estimate PageRank through random walks print("Estimate PageRank through random walks:") n_iter = len(web)**2 n_steps = 2*diameter start = time.time() ranking = stochastic_page_rank(web, n_iter, n_steps) stop = time.time() time_stochastic = stop - start # Show top 20 pages with their page rank and time it took to compute top = sorted(ranking.items(), key=lambda item: item[1], reverse=True) print('\n'.join(f'{100*v:.2f}\t{k}' for k,v in top[:20])) print(f'Calculation took {time_stochastic:.2f} seconds.\n') # Measure how long it takes to estimate PageRank through probabilities print("Estimate PageRank through probability distributions:") n_iter = 2*diameter start = time.time() ranking = distribution_page_rank(web, n_iter) stop = time.time() time_probabilistic = stop - start # Show top 20 pages with their page rank and time it took to compute top = sorted(ranking.items(), key=lambda item: item[1], reverse=True) print('\n'.join(f'{100*v:.2f}\t{k}' for k,v in top[:20])) print(f'Calculation took {time_probabilistic:.2f} seconds.\n') # Compare the compute time of the two methods speedup = time_stochastic/time_probabilistic print(f'The probabilitic method was {speedup:.0f} times faster.') if __name__ == '__main__': main()
cfb861732cb661fc8dada1bf968b8750f17af0ea
osipov-andrey/control_bot
/core/_helpers.py
424
3.546875
4
from enum import Enum class ArgType(Enum): STR = "string" INT = "integer" LIST = "list" # USER = "user" class Behavior(Enum): USER = "user" ADMIN = "admin" SERVICE = "service" # fmt: off def get_log_cover(cover_name: str) -> str: cover = ( f"\n{'#'*20} {cover_name} {'#'*20}" f"\n%s" f"\n{'#'*20} {' '*len(cover_name)} {'#'*20}" ) return cover # fmt: on
b75ffd4f6d95878ab191bc54b6a68e0d8bfc4811
rupali23-singh/list_question
/marks1.py
378
3.671875
4
student_marks=[23, 45, 67, 89, 90, 54, 34, 21, 34, 23, 19, 28, 10, 45, 86, 87, 9] index=0 less_than50=0 more_than50=0 while index<student_marks: marks=student_marks[index] if marks<50: less_than50=less_than50 + 1 else: more_than50=more_than50 + 1 index = index + 1 print("Marks more than 50 " more_than50) print("Marks less than 50 " less_than50)
4512596ae02c224d1d8dab5b62dc543ed48431d2
Aasthaengg/IBMdataset
/Python_codes/p03213/s464282704.py
1,664
3.5625
4
class PrimeFactor(): def __init__(self, n): """ エラトステネス O(N loglog N) """ self.n = n self.table = list(range(n+1)) # 最小素因数のリスト self.table[2::2] = [2]*(n//2) for p in range(3, int(n**0.5) + 2, 2): if self.table[p] == p: for q in range(p * p, n + 1, 2 * p): if self.table[q] == q: self.table[q] = p def is_prime(self, x): """ 素数判定 O(1) """ if x < 2: return False return self.table[x] == x def prime_factors(self, x): """ 素因数分解 O(logN) (試し割りだとO(sqrt(N))) """ res = [] if x < 2: return res while self.table[x] != 1: res.append(self.table[x]) x //= self.table[x] return res def prime_counter(self, x): """ 素因数分解(個数のリスト) O(logN) """ res = dict() if x < 2: return res while self.table[x] != 1: res[self.table[x]] = res.get(self.table[x], 0) + 1 x //= self.table[x] return res ################################################################# N = int(input()) P = PrimeFactor(N) Q = dict() for i in range(1,N+1): for key, value in P.prime_counter(i).items(): Q[key] = Q.get(key,0) + value a, b, c, d, e = 0, 0, 0, 0, 0 for value in Q.values(): if value >= 2: a += 1 if value >= 4: b += 1 if value >= 24: c += 1 if value >= 14: d += 1 if value >= 74: e += 1 print(b*(b-1)//2*(a-2) + c*(a-1) + d*(b-1) + e)
61927de9142a7f9c1f9d687155635e3185e71b74
dolonmandal/PySnake
/PySnake.py
1,738
3.859375
4
import random import curses from curses import textpad # initialising the screen s = curses.initscr() curses.curs_set(0) # height and the width of screen sh,sw=s.getmaxyx() # opening new window w = curses.newwin(sh,sw,0,0) w.keypad(1) w.timeout(100) # initial positions of the snake(left center) snk_x = sw/4 snk_y = sh/2 # snake body head and two lefts snake = [[snk_y, snk_x],[snk_y,snk_x-1],[snk_y, snk_x-2]] # initial position of food(center of screen) food = [sh/2, sw/2] # add food to the screen , ACS_P1 -> our food is Pi symbol w.addch(food[0], food[1], curses.ACS_PI) # the snake moves initially right and the next direction is specified by key key = curses.KEY_RIGHT while True: next_key=w.getch() key = key if next_key == -1 else next_key # check if the person has lost the game four corners or eating itself if snake[0][0] in [0,sh] or snake[0][1] in [0,sw] or snake[0] in snake[1:]: curses.endwin() quit() new_head = [snake[0][0], snake[0][1]] # direct the snake as per input arrow keys if key == curses.KEY_DOWN: new_head[0] +=1 if key == curses.KEY_UP: new_head[0] -= 1 if key == curses.KEY_LEFT: new_head[0] -=1 if key == curses.KEY_RIGHT: new_head[0] +=1 snake.insert(0, new_head) # random positioning the food if snake[0] == food: food = None while food is None: nf = [ random.randint(1, sh-1), random.randint(1, sw-1) ] food = nf if nf not in snake else None w.addch(food[0], food[1], curses.ACS_PI) else: tail = snake.pop() w.addch(tail[0],tail[1],' ') w.addch(food[0], food[1], curses.ACS_PI)
ad553e4760e84862625d497a75c09af3d6a53451
yameenjavaid/University-projects-1
/Collecto Python/final-programming-project-kelvin-collecto/Program/ball.py
482
3.515625
4
from Program.helpers.constants import Constants class Ball: def __init__(self, color): self.color = color self.neighbors = [] self.diameter = Constants.DIAMETER self.position = 0 def set_position(self, position): self.position = position def get_position(self): return self.position def set_neighbors(self, neighbors): self.neighbors = neighbors def get_neighbors(self): return self.neighbors
f87f170ec9fca8bd20380f220561f0a0beefe3ae
rookie-LeeMC/Data_Structure_and_Algorithm
/leetcode/maxSubArray.py
1,103
3.875
4
''' 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 ''' a = [0, 1, 2, 3, 4, 5] print(a[1:2]) def maxSubArray(nums): # if len(nums) == 1: # return nums[0] # # max_sub_sum = nums[0] # for i in range(0, len(nums)): # tmp = nums[i] # max_sub_sum = tmp if tmp > max_sub_sum else max_sub_sum # # for j in range(i + 1, len(nums)): # tmp += nums[j] # # max_sub_sum = tmp if tmp > max_sub_sum else max_sub_sum # # print(max_sub_sum) curr_sum, max_sum = nums[0], nums[0] for i in range(1,len(nums)): curr_sum = max(curr_sum+nums[i],nums[i]) max_sum = max(max_sum,curr_sum) # print(max_sum) return max_sum maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) maxSubArray([-2, 1])
3b5864b671ddedb503da3b9725ad37e0b0a18c17
sarahsam29/cs344
/homework1/TSP.py
2,897
3.90625
4
""" The travelling Salesman Problem solved by local searches (Hill Climbing and Simulated Annealing) @author: ss63 @date: February 23, 2019 @purpose: for CS 344 """ from search import Problem, hill_climbing, simulated_annealing, \ exp_schedule, genetic_search from random import randrange import random import math import time class TSP(Problem): def __init__(self, initial, distances): self.initial = initial self.distances = distances #returns a list containing pairs of cities def actions(self, state): actions = [] # return a pair of two cities from our path for i in range(3): pair = random.sample(range(1, len(self.initial)-1), 2) actions.append(pair) return actions # For each state, swap cities and return a new state def result(self, state, move): #create a copy of current state that will be manipulated new_state = state[:] city_1 = state[move[0]] city_2 = state[move[1]] #swap cities new_state[move[0]] = city_2 new_state[move[1]] = city_1 return new_state # returns the path cost of given states def value(self, state): total_cost = 0 for x in range(len(state) - 1): dist = [state[x], state [x +1]] dist.sort() total_cost += self.distances[tuple(dist)] total_cost = -total_cost return total_cost if __name__ == '__main__': #intialize path and distances initial_path = [0, 1, 2, 3, 4, 5, 6, 0] distances = {(0, 1): 1, (0, 2): 2, (0, 3): 3, (0, 4): 4, (0, 5): 5, (0, 6): 6, (1, 2): 7, (1, 3): 8, (1, 4): 9, (1, 5): 10, (1, 6): 11, (2, 3): 12, (2, 4): 13, (2, 5): 14, (2, 6): 15, (3, 4): 17, (3, 5): 18, (3, 6): 19, (4, 5): 20, (4, 6): 21, (5, 6): 22} # Initialize the TSP problem problem = TSP( initial_path,distances) print('Value of initial path: ' + str(problem.value(initial_path))) # Solve TSP using hill climbing hill_solution = hill_climbing(problem) print('Hill-climbing results:') print('\tThe path is: ' + str(hill_solution)) print('\tThe value of this path is: ' + str(problem.value(hill_solution))) # Solve TSP using simulated annealing. annealing_solution = simulated_annealing( problem, exp_schedule(k=20, lam=0.005, limit=10000) ) print('Simulated annealing results:') print('\tThe path is: ' + str(annealing_solution)) print('\tThe value of this path is: ' + str(problem.value(annealing_solution))) # I have noticed that, most of the time, Simulated annealing gives a better solution than hill climbing. This could be because hill-climbing is perhaps getting stuck only looking for local optimums, while simulated annealing is looking for global optimums.
98a9ce079c9b5c8602f4a95494b8e71a58e8c5ea
kottenator/code.kottenator.com
/src/project/auth/helpers.py
339
3.75
4
import types def hide_key(key, hide=lambda s: s // 2): """ Hide part of the key and return e.g. 'abc***123'. """ key_len = len(key) if isinstance(hide, types.FunctionType): hide = hide(key_len) before = (key_len - hide) // 2 + 1 after = before + hide return key[:before] + '*' * hide + key[after:]
d7e6895b6101af4dd5a1048c6d021d4631a630d8
Jiezhi/myleetcode
/src/876-MiddleOfTheLinkedList.py
1,841
4.03125
4
#!/usr/bin/env python """ CREATED AT: 2021/12/28 Des: https://leetcode.com/problems/middle-of-the-linked-list/ GITHUB: https://github.com/Jiezhi/myleetcode Difficulty: Easy Tag: See: Ref: https://leetcode.com/problems/middle-of-the-linked-list/solution/ Time Spent: min """ from typing import Optional from list_node import ListNode, buildListNode class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: """ Runtime: 32 ms, faster than 60.47% Memory Usage: 14.2 MB, less than 46.38% The number of nodes in the list is in the range [1, 100]. 1 <= Node.val <= 100 :param head: :return: """ slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow def middleNode2(self, head: Optional[ListNode]) -> Optional[ListNode]: """ Runtime: 24 ms, faster than 95.40% Memory Usage: 14.3 MB, less than 46.38% The number of nodes in the list is in the range [1, 100]. 1 <= Node.val <= 100 :param head: :return: """ length = 0 node = head while node: length += 1 node = node.next length = length // 2 node = head while length > 0: node = node.next length -= 1 return node def test(): assert Solution().middleNode(head=buildListNode([1])) == buildListNode([1]) assert Solution().middleNode(head=buildListNode([1, 2])) == buildListNode([2]) assert Solution().middleNode(head=buildListNode([1, 2, 3, 4, 5])) == buildListNode([3, 4, 5]) assert Solution().middleNode(head=buildListNode([1, 2, 3, 4, 5, 6])) == buildListNode([4, 5, 6]) if __name__ == '__main__': test()
a39336bc7c1e0fb707af3de658152a03261f9b3c
alvas-education-foundation/albinfrancis008
/coding_solutions/coding24.py
416
3.984375
4
#1) Python Program to read the number and compute the series. n=int(input("Enter a number: ")) a=[] for i in range(1,n+1): print(i,sep=" ",end=" ") if(i<n): print("+",sep=" ",end=" ") a.append(i) print("=",sum(a)) print() #2) Python program to count number of digits in it. n=int(input("Enter number:")) count=0 while(n>0): count=count+1 n=n//10 print("The number of digits in the number are:",count)
4c41c59b36be5474ffceb999e2a37d85092f5155
dharmesh-coder/Full-Coding
/Hackerrank/Anagram.py
105
3.78125
4
a=input() b=input() a=sorted(a) b=sorted(b) if(a==b): print("Anagram") else: print("NOt Anagram")
1871e5992827dbfa17966ccfbd99a9fcfd3203cf
JGhost01/Fundamento-ejecicios
/ejercicio_8.py
716
4
4
#Modificar el ejercicio #7 para obtener el número de elementos únicos en la lista de compras. Por ejemplo: Si #agrego dos veces “arroz”, solo me debería contar uno. #Para agregar un ítem a la lista solo basta agregar su nombre. #Al final solo se requiere que se muestre: #- El número total de ítems agregados a la lista de compras. #- El número de ítems únicos agregados a la lista de compras. lista_compras = [] i=0 while 1: i+=1 articulos = input("introduce los articulos:") if articulos == "parar": break else: lista_compras.append(articulos) print('Esta es nuestra cantidad de items:', len(lista_compras)) print('articulos unicos:', len(set(lista_compras)))
2c8eab55bb5bef1a37081c409e825edf878a5db5
darrylpinto/TA-Tracker
/heap.py
6,244
4.15625
4
class Heap: """ The heap consists of: :slot heap_array: The list of Student objects (list) :slot heap_size: Current Heap Size (int) """ __slots__ = ('heap_array', 'heap_size') def __init__(self): """ The constructor of Heap """ self.heap_array = [] self.heap_size = 0 def isEmpty(self): """ Method to check is heap is empty or not :return: Boolean indicating is heap is empty or not """ return self.heap_size == 0 def __leftChild(self, location): """ Helper Method to return the left child of student at position specified by location in heap_array :param location: The position of student (int) :return: position of the left child (int) """ return 2 * location + 1 def __rightChild(self, location): """ Helper Method to return the right child of student at position specified by location in heap_array :param location: The position of student (int) :return: position of the right child (int) """ return 2 * location + 2 def __parent(self, location): """ Helper Method to return the parent of student at position specified by location in heap_array :param location: The position of student (int) :return: position of the left child (int) """ return (location - 1) // 2 def __swap(self, location1, location2): """ Helper Method to swap node at location1 with node at location2 :param location1: first node's position (int) :param location2: second node's position (int) :return: None """ self.heap_array[location1], self.heap_array[location2] = \ self.heap_array[location2], self.heap_array[location1] self.heap_array[location1].position, \ self.heap_array[location2].position = \ self.heap_array[location2].position, \ self.heap_array[location1].position def __bubbleUp(self, location): """ Helper Method that handles the swapping of a node with its parent :param location: position of the node (int) :return: None """ while location > 0 and \ self.heap_array[location].confusion > \ self.heap_array[self.__parent(location)].confusion: self.__swap(location, self.__parent(location)) location = self.__parent(location) def __bubbleDown(self, location): """ Helper Method that handles the swapping of a node with its children :param location: position of the node (int) :return: None """ new_location = self.__greatest(location) while new_location != location: self.__swap(location, new_location) location = new_location new_location = self.__greatest(location) def __greatest(self, location): """ Helper method that returns the position of the greatest node among a node and its children :param location: position of the node (int) :return: the position of the greatest node (int) """ left_child = self.__leftChild(location) right_child = self.__rightChild(location) if left_child >= self.heap_size: return location if right_child >= self.heap_size: if self.heap_array[location].confusion > \ self.heap_array[left_child].confusion: return location else: return left_child if self.heap_array[left_child].confusion > \ self.heap_array[right_child].confusion: if self.heap_array[location].confusion > \ self.heap_array[left_child].confusion: return location else: return left_child else: if self.heap_array[location].confusion > \ self.heap_array[right_child].confusion: return location else: return right_child def insert(self, node): """ Method to insert node in the heap :param node: node to be inserted (Student) :return: None """ if self.heap_size < len(self.heap_array): self.heap_array[self.heap_size] = node else: self.heap_array.append(node) node.position = self.heap_size self.__bubbleUp(self.heap_size) self.heap_size += 1 def remove(self): """ Method to remove the node with most priority :return: the node with most priority (Student) """ top_heap = self.heap_array[0] self.heap_size -= 1 if self.heap_size > 0: self.heap_array[0] = self.heap_array[self.heap_size] self.heap_array[0].position = 0 self.__bubbleDown(0) return top_heap def remove_middle(self, location): """ Method to remove the node from middle of the heap :param location: position of node to be removed (int) :return: None """ self.heap_size -= 1 self.heap_array[self.heap_size].position = \ self.heap_array[location].position self.heap_array[location] = self.heap_array[self.heap_size] if self.heap_array[location].confusion > \ self.heap_array[self.__parent(location)].confusion: self.__bubbleUp(location) else: self.__bubbleDown(location) def __str__(self): """ Method to return String representation of the heap :return: String representation of the heap (String) """ string = "" for s in range(self.heap_size): string += str(self.heap_array[s].name) \ + "," + str(self.heap_array[s].confusion) + " " return string
e29cca918ffc87e1c5da845254bfc02716d59b6c
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/sttbar001/question2.py
1,059
3.859375
4
""" vector equations barak setton 20/04/2014 """ import math vectorsum = [] vectorin = input("Enter vector A: \n") # creating the vectors vectorpart = vectorin.split(" ") vectorin = input("Enter vector B: \n") vectorpart2 = vectorin.split(" ") vector = [[eval(vectorpart[0]),eval(vectorpart[1]),eval(vectorpart[2])],[eval(vectorpart2[0]),eval(vectorpart2[1]),eval(vectorpart2[2])]] for col in range(3): vectorsum.append(vector[0][col]+ vector[1][col]) # adding the vectors print ('A+B =',vectorsum) vectordot = vector[0][0]*vector[1][0] + vector[0][1]*vector[1][1] + vector[0][2]*vector[1][2] # vector dotproduct print("A.B =",vectordot) vectormagA = math.sqrt((vector[0][0])**2 + (vector[0][1])**2 + (vector[0][2])**2) # magnitude of vector A if vectormagA != 0: print("|A| =", round(vectormagA,2)) else: print("|A| = 0.00") vectormagB = math.sqrt((vector[1][0])**2 + (vector[1][1])**2 + (vector[1][2])**2) # magnitude of vector B if vectormagB != 0: print("|B| =", round(vectormagB,2)) else: print("|B| = 0.00")
b62b7af3f8c5180214d683101d6a48518052c586
sangwoo0727/Algorithm
/LeetCode🥇/LeetCode_3_Longest_Substring_Without_Repeating_Characters.py
1,095
3.640625
4
class Solution: def length_of_longest_substring(self, s: str) -> int: return binary_search(len(s), s) def binary_search(size: int, s: str) -> int: left: int = 0 right: int = size answer: int = 0 while left <= right: middle = (left + right) // 2 if check(middle, s): answer = middle left = middle + 1 else: right = middle - 1 return answer def check(length: int, s: str) -> bool: store: dict = {} left: int = 0 right: int = length - 1 for idx in range(length): if s[idx] in store: store[s[idx]] += 1 else: store[s[idx]] = 1 if len(store) == length: return True while right + 1 < len(s): if store[s[left]] == 1: del store[s[left]] else: store[s[left]] -= 1 if s[right + 1] in store: store[s[right + 1]] += 1 else: store[s[right + 1]] = 1 left += 1 right += 1 if len(store) == length: return True return False
d6ebd46e30c9bdad567373f228dfe8bb838de364
vivienyuwenchen/InteractiveProgramming
/models.py
5,017
3.875
4
import os, sys import pygame from config import * class Obstacle: """A square obstacle, defined by its top left hand coordinate, length, and color. Also takes in screen as an argument to draw the obstacle.""" def __init__(self, obs_x, obs_y, obs_len, screen, color): """Initialize the instance.""" self.obs_x = obs_x # top left hand x coordinate self.obs_y = obs_y # top left hand y coordinate self.obs_len = obs_len # side length self.screen = screen # game screen self.color = color # color of obstacle def __repr__(self): return 'Obstacle({}, {}, {}, {})'.format(self.obs_x, self.obs_y, self.obs_len, self.screen) def draw(self): """Draw osbstacle based on top left hand coordinate and length.""" pygame.draw.rect(self.screen, colors[self.color], [self.obs_x, self.obs_y, self.obs_len, self.obs_len]) def move_forward(self): """Update horizontal location of obstacle.""" self.obs_x -= 20 def is_gone(self): """Check if obstacle is completely off screen.""" return self.obs_x < -self.obs_len class Player: """A square player, defined by its top left hand coordinate and length. Also takes in screen as an argument to draw the player.""" def __init__(self, play_x, play_y, play_len, screen): """Initialize the instance.""" self.play_x = play_x # top left hand x coordinate self.play_y = play_y # top left hand y coordinate self.play_len = play_len # side length self.screen = screen # game screen self.speed = 10 # right/left speed self.jumpInProgress = False # initialize to False self.v = 7.5 # "velocity" for jump self.m = 2.5 # "mass" for jump self.floor = play_y # location of player before jump, used for comparison def draw(self): """Draw player based on top left hand coordinate and length.""" pygame.draw.rect(self.screen, colors['WHITE'], [self.play_x, self.play_y, self.play_len, self.play_len]) def move_right(self): """Update horizontal location of player after moving right.""" if self.play_x < 300: self.play_x += self.speed def move_left(self): """Update horizontal location of player after moving left.""" if self.play_x > 0: self.play_x -= self.speed def jump(self): """Set jumping status.""" self.jumpInProgress = True def update(self): """Update height of player during jump.""" if self.jumpInProgress: # change in height = "mass" times "velocity" dy = self.m * self.v # subtract height by change in height self.play_y -= dy # decrease velocity self.v -= .75 # stop jumping if player has landed if self.play_y >= self.floor: # prevent player from falling through the floor self.play_y = self.floor # no longer jumping self.jumpInProgress = False # reset velocity self.v = 7.5 def is_collide(self, obs_x, obs_y, obs_len): """Check collision of player with obstacle.""" # set coordinates for top left hand corner (0) and bottom right hand corner (1) of obstacle obs_x0 = obs_x obs_x1 = obs_x + obs_len obs_y0 = obs_y obs_y1 = obs_y + obs_len # and of player play_x0 = self.play_x play_x1 = self.play_x + self.play_len play_y0 = self.play_y play_y1 = self.play_y + self.play_len # check if player coordinates within obstacle coordinates if (obs_x0 <= play_x0 <= obs_x1 or obs_x0 <= play_x1 <= obs_x1) and (obs_y0 <= play_y0 < obs_y1 or obs_y0 < play_y1 <= obs_y1): return True class StaminaBar: """A stamina bar, defined by its starting location and color. Also takes in screen as an argument to draw the stamina bar.""" def __init__(self, screen, start, color): self.screen = screen # game screen self.start = start # starting location of stamina bar self.color = color # color of stamina bar self.bars = 100 # initialize number of health bars def draw(self): """Draw stamina bar based on color, starting location, and number of health bars.""" pygame.draw.rect(self.screen, colors[self.color], [self.start, 20, self.bars, 10]) def decrease_bar(self, num_bars): """Decrease health bar by num_bars.""" self.bars -= num_bars def increase_bar(self, speed = 1): """Increase health bar continuously if number of bars is lower than 100.""" if self.bars < 100: self.bars += 1 * speed
0395423a7152a1b959b9f46672b42dc9f71481ba
HalfMoonFatty/F
/082. Next Permutation.py
3,000
3.890625
4
''' Problem: 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. 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 ''' ''' Solution: 2 pointers Step 1. From back to front: find the first index(j) break the trend: nums[i-1] >= nums[i] 前一个比后一个大 Step 2. From back to front: find the smallest number which is larger than nums[j] (the break point)to make sure that we have the RIGHT NEXT permutation Step 3. Swap nums[j] and nums[i] Step 4. After swapping, reverse the rest of the array (nums[j+1:]) ''' class Solution(object): def nextPermutation(self, nums): if not nums: return None j = 0 # Find the first index(j) break the trend: nums[i-1] >= nums[i] 应该前一个比后一个大 for i in range(len(nums)-1, -1, -1): if nums[i-1] < nums[i]: j = i-1 break # Find the smallest number which is larger than nums[j], the break point if j >= 0: for i in range(len(nums)-1, j, -1): if nums[i] > nums[j]: # 找到第一个比 nums[j] 大的 nums[i] nums[j], nums[i] = nums[i], nums[j] # swap position break # Reverse the rest nums[j+1:] = nums[j+1:][::-1] return ''' Follow - up: Previous Permutation The idea is that find the last two adjacent number that the first one is beigger than the second one Then the question come to that find the previous permutation of the nums[first-end] Then sequence after second must be acending, so the previous permutation must comes from the number that is samller than the nums[first] at the position first with a decending sequence after it e.g. 5, 4, 1, 2, 3 previous -> 5, 3, 4, 2, 1 the num[first] = 4, nums[second] = 1, nums[smaller] = 3 ''' class Solution(object): def previousPermutation(self, nums): if not nums: return None j = 0 # Find the first index(j) break the trend: nums[i-1] <= nums[i] 应该前一个比后一个小 for i in range(len(nums)-1, -1, -1): if nums[i-1] > nums[i]: # here j = i-1 break # Find the smallest number which is larger than nums[j], the break point if j >= 0: for i in range(len(nums)-1, j, -1): if nums[i] < nums[j]: # 找到第一个比 nums[j] 小的 nums[i] nums[j], nums[i] = nums[i], nums[j] # swap position break # Reverse the rest nums[j+1:] = nums[j+1:][::-1] return
f282e4580c8095c1704409fc073e418d48d7757f
PFPCrunch/Vending-machine-thing
/Vending_Machine_Assignment/vendingMachine.py
2,993
4.0625
4
''' Objective: Make program that acts like a vending machine; have items that have individual prices, have user input float representing an amount of money, user buys a thing if they have enough money input, give change in fewest coins possible, if not enough money input, make fun of user for not having enough theoretical money. ''' q = float(0.25) d = float(0.10) n = float(0.05) p = float(0.01) #menu_list = [2.49, 1.99, 1.99, 0.69, 2.99, 3.00, 0] # coins ^ def displayMenu(): print('Place Your Order:') print('A1: Dorotos $2.49 A2: Conk $1.99 A3: Bepis $1.99') print('B1: \"Chips\" $0.69 B2: Mountain Donk $2.99 B3: Hawt Sauce $3.00') print('C: no thanks.') #displayMenu() def insertCredit(): print('Insert Credit:') credit = float(input()) print('Remaining Credit: $' + str(credit)) return credit #insertCredit() def placeOrder(): displayMenu() order = input().lower() if order == ('a1'): print('Enjoy your Dorotos.') elif order == ('a2'): print('Enjoy your Conk.') elif order == ('a3'): print('Enjoy your Bepis.') elif order == ('b1'): print('Enjoy your \"Chips\".') elif order == ('b2'): print('Enjoy your Mountain Donk.') elif order == ('b3'): print('Enjoy your Hawt Sauce?') elif order == 'c': print('Goodbye.') else: print('That item is not recognized.') return order #placeOrder(insertCredit()) def makeChange(payment, order): if order == 'a1': price = 2.49 elif order == 'a2': price = 1.99 elif order == 'a3': price = 1.99 elif order == 'b1': price = 0.69 elif order == 'b2': price = 2.99 elif order == 'b3': price = 3.00 elif payment > 0: if payment < price: print('You do not have enough credit to purchase this item.') remaining_credit = payment - price remaining_dollars = int(remaining_credit) if remaining_dollars > 0: remaining_coins = (round((remaining_credit % remaining_dollars), 2)) else: remaining_coins = remaining_credit print('Here is your change: ' + str(remaining_dollars) + ' dollars and ') quarters = q / remaining_coins while int(quarters) > 0: print('q') quarters -= 1 remaining_coins -= q dimes = d / remaining_coins while int(dimes) > 0: print('d') dimes -= 1 remaining_coins -= d nickels = n / remaining_coins while int(nickels) > 0: print('n') nickels -= 1 remaining_coins -= n pennies = p / remaining_coins while int(pennies) > 0: print('p') pennies -= 1 remaining_coins -= p makeChange(insertCredit(), placeOrder())