blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d4d04bbe83d6a734e086c30ec3f713ec934b1170
ParvathyGS/My-learnings
/Python/find-sum.py
962
4.09375
4
# list1 = int(input("Enter the numbers seperated by space \n")) # # creating sum_list function # def sumOfList(list, size): # if (size == 0): # return 0 # else: # return list[size - 1] + sumOfList(list, size - 1) # # Driver code # total = sumOfList(list1,len(list1)) # print("Sum of all elements in given list: ", total) # list = [] # n = int(input("Enter the no:of elements")) # for x in range(0,n): # ele = int(input) # list.append(ele) # def sum(numbers): # total = 0 # for x in numbers: # total += x # return total # print(sum((list))) lst = [] # number of elemetns as input n = int(input("Enter number of elements : ")) print("enter a list") # iterating till the range for i in range(0, n): ele = int(input()) lst.append(ele) # adding the element def sum(numbers): total = 0 for x in numbers: total += x return total print("The sum is ") print(sum(lst))
de3a0d193c07f77fcaf263d21a596e617b922cfc
alexryan/projectEuler
/multiplesOf3and5.py
323
3.703125
4
multiplesOf3 = set(); multiplesOf5 = set(); #multiplesOf3 = {3,6}; #multiplesOf5 = {5,10}; all = {}; sum = 0; for i in range(1000): if (i % 3 == 0): multiplesOf3.add(i) if (i % 5 == 0): multiplesOf5.add(i) all = multiplesOf3.union(multiplesOf5); for i in all: sum = sum + i; #print(i); print(sum);
1d90e0015ac878e62cfcf8541c474be04e73209e
totland/Python-Public
/Getting-Started-Class/Getting-Started-Mod2 - 2022-12-29T154730.679324Z.py
4,568
3.875
4
# Module 2: Types, Statements, and other goodies # ********************************************************* # ********************************************************* # Integers and Floats # ***************************************************** """ Multi Line Comment """ answer = 42 # Int pi = 3.141592653589793 # Float name = "Python" machine = "HAL" "Nice to meet you {0}. I am {1}".format(name, machine) f"Nice to meet you {name}. I am {machine}" # Compressed way to write #Boolean and None #True/False # ***************************************************** python_course = True # Sets Boolean var to True (First Char must be cap) java_course = False int(python_course) == 1 # Converts to Int and tests with Int int(java_course) == 0 str(python_course) == "True" # Tests Boolean with String aliens_found = None # declaired var set to null #Convert and Strings # ****************************************************** # Integers and Floats answer = 42 name = "Python" pi = 3.141592653589793 #Convert and Strings int(pi) # should convert to == 3 float(answer) # should convert to == 42.0 'Hello' == "Hello" == """Hello""" "hello".capitalize() =="Hello" "Hello".replace("e", "a") =="Hallo" "hello".isalpha() == True # Checking to see if alpha char "123".isdigit() == True # Checking to see if they are digits # If Statement # ******************************************************** number = 55 if number == 5: print("Number is 5") else: print("Number is not 5") if number: # Number has a value (therefor True) print("Number is defined and truthy") text = "Python" if text: print("Text is defined and truthy") number = 5 if number != 5: # Can use ==, !=, <=, >=, etc.. print("Number is 5") else: print("Number is not 5") number = 5 if number != 5 and aliens_found: # "and" (both must be true/false), "or" one must be true or false print("Number is 5") else: print("Number is not 5") a = 1; b = 2 # "";"" will combine commands on one line "bigger" if a > b else "smaller" # Compressed If/Else Statement # Lists Just like array but can be mixed int, string, float # *********************************************************** student_names = ["Jake", "Coby", "Kailey"] print(student_names[0]) # 0 will get the first entry print(student_names[2]) # to get the last entry, use -1 student_names.append("Todd") # appends to the end of the list "mark" in student_names # check for name in list len(student_names) del student_names[4] # deleted an element from list # List Slicing # student_names[1:-1] will skip the first and last entry # *********************************************************** x = 0 for index in range(10): #range(5, 10, 2) Start/End/add, index just looping x += 10 print("The value of X is {0}".format(x)) student_names = ["Jake", "Coby", "Kailey"] for name in student_names : print("Currently testing " + name) if name == "Todd" : print("Found him! " + name) # break/continue could get out once item is found or continue x = 0 while x < 10 : print("Count is {0}".format(x)) x +=1 # must add/subtract one to counter in while loops # Dictionaries # ************************************************************* student = { "name": "TJ", "student_id" : 21, "feedback" : None } # Curly brackets for single items, can be put on one line, need : all_student = [ {"name": "Coby", "student_id" : 21}, {"name": "Kailey", "student_id" : 22}, {"name": "Jake", "student_id" : 23} ] # notice the brackets for multiple items # Methods student.get("name") # Using the get Method to pull the student name # student.value("student_id") # Using the value Method, will return dic value del student["Name"] # Exceptions # ********************************************************** student = { "name": "TJ", "student_id" : 21, "feedback" : None } # Curly brackets for single items student["last_name"] = "Totland" # appends dic item/value try: last_name = student["last_name"] except KeyError: # Looking for key errors print("Error finding last_name") except TypeError as error: # Looking for type errors print("I cannot add these 2 together") # When adding str and int together print(error) # Will print error message except Exception: # Just about any error print("Unknown Error") print("This code executes!") # Other Data Types # ********************************************************** ''' complex # Complex numbers bytes bytearray tuple # Cannot change variable setfrozen set () '''
0989afd781a62d3d11e4bada355b457c76caf9a9
tbedford/MCDS
/webapp/test/test_bcrypt.py
651
3.84375
4
import bcrypt # hashes a plaintext password using bcrypt with bcrypt the hash # contains the salt, so no need to store separately. def hash_password (password): salt = bcrypt.gensalt() hash = bcrypt.hashpw(password, salt) return hash def check_password (password, hash): hashpw = bcrypt.hashpw(password, hash) if hashpw == hash: return True else: return False password = "secret".encode('utf-8') hash = hash_password (password) print (hash) new_pword = "secret!!!".encode('utf-8') if check_password(new_pword, hash): print ("passwords match!") else: print ("passwords DON'T match!")
b4c5dcb7316977abd57499a32c101af6614e66cb
lasernite/mitpythoniap
/nims.py
1,063
3.828125
4
# Name: Laser Nite # Kerberos: nite # nims.py def play_nims(pile, max_stones): ''' An interactive two-person game; also known as Stones. @param pile: the number of stones in the pile to start @param max_stones: the maximum number of stones you can take on one turn ''' ## Basic structure of program (feel free to alter as you please): while pile > 0: move1 = input("Player 1, how many stones do you take? ") while move1 > 5 or move1 < 1: move1 = input("Player 1, how many stones do you take, between 1 and 5? ") pile = pile - move1 print pile if pile <= 0: print "Player 1, you lose!" return move2 = input("Player 2, how many stones do you take? ") while move2 > 5 or move2 < 1: move2 = input("Player 2, how many stones do you take, between 1 and 5? ") pile = pile - move2 print pile if pile <= 0: print "Player 2, you lose!" return print "Game Over!" play_nims(100,5)
ce5d6f2bed63c001e651a3b43fc1e300a10db109
azizzouaghi/holbertonschool-higher_level_programming
/0x02-python-import_modules/2-args.py
465
3.6875
4
#!/usr/bin/python3 import sys if __name__ == "__main__": argv_len = len(sys.argv) if argv_len - 1 == 0: print("{:d} arguments.".format(argv_len - 1)) if argv_len - 1 == 1: print("{:d} argument:".format(argv_len - 1)) print("{:d}: {:s}".format(1, sys.argv[1])) elif argv_len > 1: print("{:d} arguments:".format(argv_len - 1)) for i in range(1, argv_len): print("{:d}: {:s}".format(i, sys.argv[i]))
438adb533e5192dcce6070b12902f96676e852a4
nopomi/hy-data-analysis-python-2019
/hy-data-analysis-with-python-2020/part04-e09_snow_depth/src/snow_depth.py
271
3.578125
4
#!/usr/bin/env python3 import pandas as pd def snow_depth(): wh = pd.read_csv("src/kumpula-weather-2017.csv") max = wh["Snow depth (cm)"].max() return max def main(): print("Max snow depth: " + str(snow_depth())) if __name__ == "__main__": main()
cfd2fea6d22aab97ac0b9049a71b0820d73b5105
shlomikaduri/ProjectGames
/GuessGame.py
1,423
4.15625
4
import random,Score ''' The purpose of guess game is to start a new game, cast a random number between 1 to a variable called difficulty. ''' ''' get a number variable named difficulty return a random number between 1 to difficulty. ''' def generate_number(difficulty): return(random.randint(1, int(difficulty))) ''' get a number variable named difficulty ask the user to guess a number between 1 to difficulty and return the number the user guessed. ''' def get_guess_from_user(difficulty): return(int(input("Please guess number from 1 to "+ difficulty))) ''' get 2 variables: number variable named difficulty number variable named secret_number compare the secret generated number to the one prompted by the get_guess_from_user. ''' def compare_results(difficulty): guessed_number = get_guess_from_user(difficulty) secret_number = generate_number(difficulty) print("guessed_number is: "+ str(guessed_number)) print("secret_number is: "+ str(secret_number)) if guessed_number==secret_number: print("Win") return True else: print("Lose") return False ''' get a number variable named difficulty call the functions above and play the game. return True / False if the user lost or won. ''' def play(difficulty): if compare_results(str(difficulty))==True: Score.add_score(difficulty) return True else: return False
b15ab26b135bc494b8b32e01ca7ba1b98f7edee9
sidv/Assignments
/Thanushree/Assignment/Aug_17/calc_module/quiz.py
69
3.8125
4
i=0 while i<5: print(i) i+=1 if i == 3: break else: print(0)
f06e67cc9853b5aa80d8039fd5c6437f72824f0b
githubjyotiranjan/pytraining
/data/all-pratic/VivekKumar_DCC/python_2/project1.py
1,074
3.734375
4
file = open("project.txt", "w") file.write("India, also called the Republic of India, is a country in South Asia.\n It is the seventh-largest country by area, the second-most populous country, and the most populous democracy in the world.\n It is bounded by the Indian Ocean on the south, the Arabian Sea on the southwest, and the Bay of Bengal on the southeast.\n It shares land borders with Pakistan to the west; China, Nepal, and Bhutan to the northeast; and Bangladesh and Myanmar to the east.\n In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives.\n India's Andaman and Nicobar Islands share a maritime border with Thailand and Indonesia. ") file = open("project.txt", "r") bob=file.read() dog=bob.replace(",","") dog1=dog.replace(".","") dog2=dog1.replace("'","") dog3=dog2.replace(";","") mylist=dog3.split() my_dict={} for n in mylist: if not n in my_dict: my_dict[n]=mylist.count(n) #print(my_dict[n]) #print(my_dict.items()) a = sorted(my_dict.items()) for i in a: print("{0}-------> {1}".format(i[0],i[1]))
05895db4c92a5ec055d369f070ba500aa62b06b1
saralkbhagat/leet
/Linkedlist/Reverse LL/206.reverse-linked-list.py
1,248
4.0625
4
# # @lc app=leetcode id=206 lang=python3 # # [206] Reverse Linked List # # https://leetcode.com/problems/reverse-linked-list/description/ # # algorithms # Easy (57.16%) # Total Accepted: 699.7K # Total Submissions: 1.2M # Testcase Example: '[1,2,3,4,5]' # # Reverse a singly linked list. # # Example: # # # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # # # Follow up: # # A linked list can be reversed either iteratively or recursively. Could you # implement both? # # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: prevnode=None curnode=head while(curnode!=None): temp=curnode.next curnode.next=prevnode prevnode=curnode curnode=temp print(curnode,prevnode) #None ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}} return prevnode
ae47d12c13e3564dd16cd8f7021bb672fa32bde1
ioanajoj/Artificial-Intelligence
/Subgraphs (EA)/Algorithm.py
4,359
3.625
4
import math import matplotlib.pyplot as plt from GraphProblem import GraphProblem from Population import Population class Algorithm: def __init__(self, file_name, parameters_file_name): """ self.__problem: Problem self.__population: Population """ self.__data_file_name = file_name self.__fitnesses = [] self.__problem = None self.__population = None self.__population_size = None self.__evaluations = None self.__number_of_runs = None self.__muation_probability = None self.read_paramaters(parameters_file_name) self.best_solutions = [] self.averages = [] def read_paramaters(self, file_name): """ Create problem object and call load_data on it :param file_name: String :return: void """ file = open(file_name) lines = file.read().split("\n") self.__population_size = int(lines[0].split(":")[1]) self.__evaluations = int(lines[1].split(":")[1]) self.__number_of_runs = int(lines[2].split(":")[1]) self.__muation_probability = float(lines[3].split(":")[1]) def iteration(self, probability): """ Create a new generation :return: void """ # Evaluate fitness for each individual self.__population.evaluate(self.__problem) # Select individuals individual1, individual2 = self.__population.selection() # Create offspring child1, child2 = individual1.crossover(individual2, probability) child1.fitness(self.__problem) child2.fitness(self.__problem) child1.mutate(probability) child2.mutate(probability) # Select new individuals to be inserted individuals = [individual1, individual2, child1, child2] individuals = sorted(individuals) # Insert best individuals from parents and children self.__population.addIndividual(individuals[0]) self.__population.addIndividual(individuals[1]) def run(self): """ Perform given number of runs for populations and given number of evaluations :return: void """ self.__problem = GraphProblem(self.__data_file_name) for i in range(self.__number_of_runs): print("Iteration " + str(i), end=": ") self.__population = Population(self.__population_size, self.__problem.getNumberOfNodes()) for j in range(self.__evaluations): self.iteration(self.__muation_probability) average_fitness = self.__population.getAverage() print("average fitness = " + str(average_fitness), end=", ") self.__fitnesses.append(average_fitness) best_solution = self.__population.getBest().getFitness() print("best solution = " + str(best_solution)) self.best_solutions.append(best_solution) self.plotGeneration() self.averages.append(self.__population.getAverage()) self.statistics() def statistics(self): """ Print the average and standard deviation for the best solutions found by your the algorithm after 1000 evaluations of the fitness function in 30 runs, with populations of 40 individuals :return: void """ print("Average of best solutions:", end=" ") average = float(sum(self.best_solutions)) / len(self.best_solutions) print(average) print("Standard deviation:", end=" ") sum_best = sum([pow(i - average, 2) for i in self.best_solutions]) std_deviation = math.sqrt(sum_best // (len(self.best_solutions) - 1)) print(std_deviation) self.plotAvg() def plotGeneration(self): """ Plot average fitnesses after one run :return: void """ to_plot = self.__fitnesses # plt.clf() plt.plot(to_plot, 'g^') plt.ylabel('fitness') plt.xlabel('individual') plt.show() self.__fitnesses = [] def plotAvg(self): """ Plot final average of every run :return: void """ to_plot = self.averages plt.plot(to_plot, 'g^') plt.ylabel('final average') plt.xlabel('run') plt.show()
8ce879453683219ef3da099c62a2481f1ed0bc48
linloone/code_examples
/padding-oracle/padding_oracle_server.py
4,559
3.75
4
# we'll be using the lovely pycryptodome library for our crypto functions from Crypto.Cipher import AES # for key/iv generation import random # since we're using AES for our example, this is 16 bytes BLOCK_SIZE = 16 # let's set up the 'server-side' functions. our server is going to do the following: # - generate a random key (16 bytes). this is kept hidden from the 'attacker' # - generate a random IV (16 bytes). this is known to the 'attacker'. # - pad the plaintext to prep it for encryption # - encrypt the plaintext and provide the attacker with the ciphertext # # after it has done those, the 'server' will be supplied with ciphertexts. it will # decrypt them with its known key and then validate the padding. it will then let # the 'attacker' know if the padding is valid or not. based on this information, # the 'attacker' will be able to methodically decrypt the entire plaintext, without # ever knowing what the key is class Server: def __init__( self ): self.__cipher_key = bytes( [random.randint(0,255) for i in range(16)] ) self.__cipher_iv = bytes( [random.randint(0,255) for i in range(16)] ) self.__secret_message = "hiya" def __encrypt_message( self, plaintext ): # boilerplate to set up AES from pycryptodome cipher = AES.new( self.__cipher_key, AES.MODE_CBC, iv=self.__cipher_iv ) # remember: before we encrypt, we have to make sure it's properly padded! padded_plaintext = self.__pad_plaintext( plaintext ) return cipher.encrypt( padded_plaintext ) # okay, so technically pycryptodome has a built-in padding function, but since # we're learning all of this together, i might as well illustrate how it works # with some hand-written code. def __pad_plaintext( self, plaintext ): # figure out how many padding bytes we need for our block size num_padding_bytes = BLOCK_SIZE - (len(plaintext) % BLOCK_SIZE) # remember - we add a whole block of padding if our plaintext is an even # increment of BLOCK_SIZE if num_padding_bytes == 0: num_padding_bytes = BLOCK_SIZE # then we just append that many bytes with that value to the end of our plaintext. we're also # taking the liberty of ensuring that our plaintext is encoded in utf-8 as a binary string # for easier handling with the concatenation, etc. return plaintext.encode( 'utf-8') + bytes( [num_padding_bytes for i in range(num_padding_bytes)] ) # again, technically the crypto lib we're using has a build-in padding/validation # function, but where's the fun in that? this will spit out a straight true/false on # whether padding's valid or not def __is_valid_padding( self, ciphertext, submitted_iv ): # step 1 is to decrypt the ciphertext using the known key/iv. cipher = AES.new( self.__cipher_key, AES.MODE_CBC, iv=submitted_iv ) plaintext = cipher.decrypt( ciphertext ) # since all padding bytes are the same value, we start with the last byte of the # decrypted plaintext, and go from there num_padding_bytes = plaintext[-1] # so, there are several conditions where padding is invalid: # 1. padding ranges from 0x01 bytes to BLOCK_SIZE bytes if num_padding_bytes < 0x01 or num_padding_bytes > BLOCK_SIZE: return False # 2. every padding byte must have the same value - the number of bytes padded for i in range( 1, num_padding_bytes+1 ): if plaintext[-i] is not num_padding_bytes: return False # if both of those conditions are passed, we know the padding is valid. and this # is where a normal system would then strip that padding and return the plaintext return True # now let's create some functions for the 'attacker' to use. the only things they are # going to touch are these three functions. to get the original ciphertext, the IV, and # then to submit ciphertexts to be evaluated by the oracle. the oracle will return a true/false # on whether padding is valid - and that's it. def get_original_ciphertext( self ): return self.__encrypt_message( self.__secret_message ) def submit_ciphertext( self, ciphertext, submitted_iv ): return self.__is_valid_padding( ciphertext, submitted_iv ) def get_cipher_iv( self ): return self.__cipher_iv
85a7144ce8cf1eb1cbc05993489a872ef87f28bb
raririn/LeetCodePractice
/Solution/1071_Greatest_Common_Divisor_of_Strings.py
652
3.546875
4
class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: # The same as gcd algorithm for integers. l1 = len(str1) l2 = len(str2) if l1 < l2: str1, str2 = str2, str1 if str1[:l2] != str2: return False str1 = str1[l2:] if len(str1) == 0: return str2 return self.gcdOfStrings(str1, str2) ''' Runtime: 28 ms, faster than 98.83% of Python3 online submissions for Greatest Common Divisor of Strings. Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Greatest Common Divisor of Strings. '''
0d61608c97e32364acf93be5ac28404649746a34
psavery/POSCARModules
/readPOSCAR.py
1,938
3.578125
4
# Author -- Patrick S. Avery -- 2016 # This is so we can loop through the lower case alphabet... from string import ascii_lowercase import crystal """ Reads a POSCAR and returns a Crystal object """ def readPOSCAR(fileName = str): with open(fileName, "r") as f: lines = f.readlines() title = lines[0] scalingFactor = float(lines[1]) latticeVecs = [[float(lines[2].split()[0]), float(lines[2].split()[1]), float(lines[2].split()[2])], \ [float(lines[3].split()[0]), float(lines[3].split()[1]), float(lines[3].split()[2])], \ [float(lines[4].split()[0]), float(lines[4].split()[1]), float(lines[4].split()[2])],] # If the next line is not an int, assume they are atomic symbols symbols = [] i = 5 if not lines[5].split()[0].isdigit(): symbols = lines[5].split() i += 1 numOfEachType = lines[i].split() # if symbols never got defined, we will just define them as 'a', 'b', 'c', etc... if len(symbols) == 0: # Loop through alphabet letters for c in ascii_lowercase: symbols.append(c) if len(symbols) == len(numOfEachType): break i += 1 # Convert them to integers numOfEachType = [int(j) for j in numOfEachType] cartesian = False if lines[i][0] == 'C' or lines[i][0] == 'c' or \ lines[i][0] == 'K' or lines[i][0] == 'k': cartesian = True if isinstance(lines[i].split()[0], str): i += 1 atoms = [] symbolsInd = 0 # Now iterate over the atom coordinates for numAtoms in numOfEachType: for j in range(numAtoms): vec = crystal.Vector3d(float(lines[i].split()[0]), float(lines[i].split()[1]), float(lines[i].split()[2])) atoms.append(crystal.Atom(symbols[symbolsInd], vec)) i += 1 symbolsInd += 1 # Create the crystal object crys = crystal.Crystal(title, scalingFactor, latticeVecs, cartesian, atoms) return crys
2e4b6204741846f2eff45d08bd7e526f5895ad17
zackdallen/Learning
/classes.py
1,366
4.21875
4
# Classes and objects class Person: __name = '' __email = '' def __init__(self, name, email): self.__name = name self.__email = email # 'self' in Python is the same as 'this' in ruby def set_name(self, name): self.__name = name def get_name(self): return self.__name def set_email(self, email): self.__email = email def get_email(self): return self.__email def toString(self): return '{} can be contacted at {}.'.format(self.__name, self.__email) brad = Person('Brad Longly', 'brad.longly@gmail.com') #brad.set_name('Brad Longly') #brad.set_email('brad.longly@gmail.com') #print(brad.get_name()) #print(brad.get_email()) #print(brad.toString()) class Customer(Person): __balance = 0 def __init__(self, name, email, balance): self.__name = name self.__email = email self.__balance = balance super(Customer, self).__init__(name, email) def set_balance(self, balance): self.__balance = balance def get_balance(self): return self.__balance def toString(self): return '{} has a balance of ${} and can be contacted at {}.'.format(self.__name, self.__balance, self.__email) john = Customer('John Doe', 'jd@gmail.com', 100) john.set_balance(150) kate = Customer('Kate S', 'kate#gmail.com', 3450) print(john.toString()) print(kate.toString())
6e6b6c4c7fe01877bba06adc39d8619aa3e397fe
Miroscyer/PythonStudy
/python_work/Chart6_Dictionary/Test6.4_Dics2.py
356
3.75
4
words = { 'if': 'perhaps', 'or': 'other', 'print': '打印', 'str': 'string', 'len': 'length', } for key, val in words.items(): print(key + " = " + val) words['&&']='and' words['+']='plus' words['-']='decrease' words['*']='multiply' words['/']='divide' print('\n') for key, val in words.items(): print(key + " = " + val)
ba14f4076e2889860b68f9423424b9a988ba4426
saadkang/PyCharmLearning
/basicsyntax/dictmethods.py
1,764
4.59375
5
""" Dictionary Methods """ car = {'Make' : 'Toyota', 'Model' : 'Camry', 'Year' : 2015} cars = {'BMW': {'Model': '550i', 'Year': 2016}, 'Toyota': {'Model': 'Camry', 'Year': 2015}} # key() is a built-in method that can help you get the key inside a dictionary # values() is also a built-in method that can help you get the values of the key inside the dictionary print(car.keys()) print(car.values()) # Now let's do the same thing with our cars dictionary as well print('*'*40) print(cars.keys()) print(cars.values()) print('*'*40) # And if we want to see the key and the value at the same time we can use another method items() # First we will try and print the keys and values set for car and then for cars print(car.items()) print('*'*40) print(cars.items()) # When you see the pair 'key:value' and this type of data is known as Tuple print('*'*40) print('*'*40) # There is another method copy() that we can be used and that will copy the dictionary from one place to another copy_car = car.copy() print(car) print(copy_car) # There are a lot of different methods that we can use to do something with the dictionary # Another method that was used in the tutorial is clear() that can be used to clear the data of the dictionary copy_car.clear() # So now the copy_car is cleared we will try it to print on the console print('*'*40) print(car) print(copy_car) # Now we will use the pop() method with the dictionary to remove a data from the car dictionary # Let's first print the car as it is and then we will use pop() and then print after the pop() is applied print('*'*40) print(car) print(car.pop('Model')) print(car) # Looking at the console I found out that pop() has a return type and that means that we can print the value of # the key that was popped out
af511f49144ffe066f001cdccfda98783419ee3c
yachialice/Leetcode
/15-3Sum.py
1,212
3.625
4
""" 15. 3Sum Sort the input array and use two pointers l and r to make the sum of three integers approximate 0. Pay attention to avoid putting the same triplets in the output by skipping the same nums in iteration. """ class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums = sorted(nums) res = [] for i in range(len(nums)-2): #avoid repetition if i > 0 and nums[i] == nums[i-1]: continue l = i+1 r = len(nums) - 1 while l < r: sum_ = nums[i] + nums[l] +nums[r] if sum_ == 0: res.append([nums[i], nums[l], nums[r]]) #avoid repetition while l < r and nums[l] == nums[l+1]: l+=1 #avoid repetition while l < r and nums[r] == nums[r-1]: r-=1 l+=1 r-+1 elif sum_ < 0: l+=1 elif sum_ > 0: r-=1 return res
ea65d6aaa9b85bfb1815bc590ee2a4d9b7243b64
qizongjun/Algorithms-1
/Leetcode/Divide and Conquer/#106-Construct Binary Tree from Inorder and Postorder Traversal/main.py
2,124
3.953125
4
# coding=utf-8 ''' Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. ''' ''' 标准的分治算法思维,可能有其他的方式解决,不过这里参照的是清华数据结构课介绍的思路 第一种思路,最为清晰易理解,但是因为递归调用过多额外内存导致内存超限 ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if len(preorder) == 0: return None if len(preorder) == 1: return TreeNode(preorder[0]) mid = inorder.index(preorder[0]) # 利用preorder的头结点也就是根节点划分数组 lchild = self.buildTree(preorder[1:mid + 1], inorder[:mid]) rchild = self.buildTree(preorder[mid + 1:], inorder[mid + 1:]) root = TreeNode(preorder[0]) root.left = lchild root.right = rchild return root ''' 参考discussion后的第二种方式,由于preorder和inorder数组规模太大导致内存超限 这时观察可以发现每次分治只需要把中序数组分开就行,因为preorder数组永远是按照顺序 从前到后来划分inorder数组的,这样preorder的分数组就不存在了,只需要保存inorder 数组的子数组就行,Beat 51.34% ''' class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if len(inorder) == 0: return None node = preorder.pop(0) # 每次都是preorder的第一个数来划分inorder,需要弹出 mid = inorder.index(node) root = TreeNode(node) root.left = self.buildTree(preorder, inorder[:mid]) root.right = self.buildTree(preorder, inorder[mid + 1:]) return root
eb7076d9c7d75d4b0ce59b5a1f74c6cdfe311b7e
jessiecantdoanything/Week10-24
/CodesAndStrings.py
1,531
4.125
4
# strings # concatenation firstName = "Jesus" lastName = "Monte" print(firstName + " " + lastName) name = firstName + " " + lastName lastFirst = lastName + ", " + firstName print(lastFirst) # repition print("uh "*2 + "AAAAAAAAA") def imTiredofSchool(): print("me, "*3 + "young Jessie,") print("is extremely exhausted") print("Why must you ask?") print("school "*3) imTiredofSchool() # indexing name = "Roy G Biv" firstChar = name[0] print(firstChar) middleCharIndex = len(name) // 2 print(middleCharIndex) print(name[middleCharIndex]) print(name[-3]) for i in range(0, len(name)): print(name[i]) #slicing and dicing print(name[0:3]) for i in range(0, len(name)+1): print(name[0:i]) # searching print("biv" in name) print("y" not in name) # String Methods to investigate: # Method Use Example Explanation # center aStr.center(w) # ljust aStr.ljust(w) # rjust aStr.rjust(w) # upper aStr.upper() # lower aStr.lower() # index aStr.index(item) # rindex aStr.rindex(item) # find aStr.find(item) # rfind aStr.rfind(item) # replace aStr.replace(old, new) # Be sure to include multiple examples of all of them in use # Character functions from mapper import * print(letterToIndex('M')) print(indexToLetter(24)) from crypto import * print(scramble2Encrypt("THE MEETING IS AT FIVE OCLOCK")) print(scramble2Decrypt("H ETN SA IEOLCTEMEIGI TFV COK"))
9b2726378853130eb5f92064efe235f7c4f3e572
Coder2Programmer/Leetcode-Solution
/twentySixthWeek/remove_sub_folders_from_the_filesystem.py
984
3.734375
4
class TrieNode: def __init__(self): self.children = dict() self.value = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.value = True def find(self): def dfs(cur, node): if node.value: folder.append('/' + '/'.join(cur)) return for char in node.children: dfs(cur + [char], node.children[char]) folder = [] dfs([], self.root) return folder class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: trie = Trie() for f in folder: trie.insert(f.split('/')[1:]) return trie.find()
5135e847fe397123f43ed49445d619609f2b73b3
amardipkumar91/PracticePython
/function_oriented_strategy.py
2,698
3.9375
4
from abc import ABC, abstractmethod from collections import namedtuple Customer = namedtuple('Customer', 'name fidelity') class ListItem(object): def __init__(self, product, quantity, price): self.product = product self.quantity = quantity self.price = price def total(self): return self.price * self.quantity class Order(object): def __init__(self, customer, cart, promotion = None): self.customer = customer self.cart = list(cart) self.promotion = promotion def total(self): if not hasattr(self, '__total'): self.__total = sum(item.total() for item in self.cart) return self.__total def due(self): if self.promotion is None: discount = 0 else: discount = self.promotion(self) return self.total() - discount def __repr__(self): fmt = '<Order total: {:.2f} due: {:.2f}>' return fmt.format(self.total(), self.due()) promos = [] def promotion(promos_func): promos.append(promos_func) @promotion def fidelity_promo(order): # import pdb;pdb.set_trace() """5% discount for customers with 1000 or more fidelity points""" return order.total() * .05 if order.customer.fidelity >= 1000 else 0 @promotion def bulk_item_promo(order): """10% discount for each LineItem with 20 or more units""" discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * .1 return discount @promotion def large_order_promo(order): """7% discount for orders with 10 or more distinct items""" distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * .07 return 0 # promos = [fidelity_promo, bulk_item_promo, large_order_promo] def best_promo(order): """Select best discount available """ return max(promo(order) for promo in promos) joe = Customer('John Doe', 1000) ann = Customer('Ann Smith', 1100) cart = [ListItem('banana', 4, .5),ListItem('apple', 10, 1.5),ListItem('watermellon', 5, 5.0)] obj = Order(joe, cart, fidelity_promo) import pdb;pdb.set_trace() # print ("------------") # print (obj) # print ("------------") # obj1 = Order(ann, cart, large_order_promo) # print (obj1) # banana_cart = [ListItem('banana', 30, .5),ListItem('apple', 10, 1.5)] # obj2 = Order(joe, banana_cart, bulk_item_promo) # print (obj2) # long_order = [ListItem(str(item_code), 1, 1.0) for item_code in range(10)] # obj3 = Order(ann, long_order, large_order_promo) # print (obj3) # print ("---") # obj4 = Order(joe, long_order, best_promo) # print ("---") # print (obj4)
df5fe54777a01e15ab699e6b1984d3a83679867f
userr2232/PC
/Codeforces/A/667.py
258
3.515625
4
import sys import math d, h, v, e = (map(float, input().strip().split())) if not h: print("YES\n0") else: drink_speed = v / (math.pi * d ** 2 / 4) if drink_speed < e: print("NO") else: print(f"YES\n{h / -(e - drink_speed)}")
f77a9da0834313b21af2a16a3988a0b4ca3fc496
aucan/ilkpython
/ilkpython/08recursion.py
166
3.640625
4
def faktoryel(sayi): if sayi==0: return 1 else: return sayi*faktoryel(sayi-1) girdi= int(input("bir sayi giriniz:")) print(faktoryel(girdi))
75e7ce7b780e7c5b41f3390587c2c3a85741356d
Shantanu1395/Algorithms
/Trees/print_leftmost_rightmost.py
1,583
4.03125
4
class Node(object): def __init__(self,data): self.data=data self.left=None self.right=None class Tree(): def __init__(self): self.root=None class Queue: def __init__(self): self.queue = list() def enqueue(self,data): self.queue.insert(0,data) def dequeue(self): if len(self.queue)>0: return self.queue.pop() return ("Queue Empty!") def size(self): return len(self.queue) def printQueue(self): for i in self.queue: print(i.data,end=' ') def isEmpty(self): return len(self.queue)<=0 def getFront(self): return self.queue[-1] def getLast(self): return self.queue[0] def printOuterTreeLevelWise(root): q=Queue() q.enqueue(root) level=0 while True: if q.isEmpty(): break count=q.size() initialcount=count level+=1 if q.size()==1: print(q.getFront().data) else: print(q.getFront().data,q.getLast().data) while count>0: front=q.getFront() if front.left: q.enqueue(front.left) if front.right: q.enqueue(front.right) temp=q.dequeue() count-=1 tree=Tree() tree.root=Node(15) tree.root.left=Node(10) tree.root.right=Node(20) tree.root.left.left=Node(8) tree.root.left.right=Node(12) tree.root.right.left=Node(16) #tree.root.right.right=Node(25) printOuterTreeLevelWise(tree.root)
16ea99409a47ab6242fed43f8bada3d95ba3d687
lucasbflopes/codewars-solutions
/6-kyu/are-we-alternate?/python/solution.py
187
3.828125
4
def isAlt(s): vowels = 'aeiou' rule = lambda x,y : x in vowels and y not in vowels or x not in vowels and y in vowels return all(rule(s[i], s[i+1]) for i in range(len(s) - 1))
11f68fe3ba8962efa382354d23caf645d0a46348
frogonhills/OOP-.Practice
/oop5.py
960
3.984375
4
class Employee: raise_amount = 1.04 num_of_employee = 0 def __init__(self , first , last , pay ): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + "@company.com" Employee.num_of_employee += 1 def fullName(self): return '{} {}'.format(self.first , self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amount) def __repr__(self): return " Employee ( '{}' , {} , {} ) ".format(self.first , self.last , self.pay) def __str__(self): return '{} , {}'.format(self.fullName(), self.email) def __add__(self , other): return self.pay + other.pay emp_1 = Employee('rakib' , 'hossain' , 50000 ) emp_2 = Employee('mofiz' , 'faruk' , 20000) print(emp_1.__repr__()) print(emp_1.__str__()) print(emp_1) print(emp_1 + emp_2) # __add__() chara eta cholbe na karon duita object jog kora jay na
64c1a44e3a6ed34cbe66e092c2bb628b65e76cdf
jackie-kinsler/Labs
/dicts-word-count/wordcount.py
898
3.921875
4
import sys def make_word_counts(): wordcount_in_textfile = {} #Write a table that takes ASCII values and translates them to other characters #In this case, the other character is None #Table handles: .(46) ,(44) !(33) ?(63) ;(59) :(58) _(95) "(34) punctuation = { 44 : None, 46 : None, 33 : None, 63 : None, 59 : None, 58 : None, 95 : None, 34 : None} textfile = open(sys.argv[1]) for line in textfile: words = line.rstrip().split(" ") #check if .strip() works better! for word in words: word_without_punctuation = word.translate(punctuation).lower() wordcount_in_textfile[word_without_punctuation] = wordcount_in_textfile.get(word_without_punctuation, 0) + 1 for word_pair in wordcount_in_textfile.items(): print(word_pair[0], word_pair[1]) textfile.close make_word_counts()
f1d886bbcf6ae7200ded8b0936ba48ce94d398cf
AsanalievBakyt/classwork
/functional_programming_2.py
330
3.546875
4
def twoSum(nums, target): for index in range(len(nums)): current = nums[index] next_list = nums[index + 1:] for j in range(len(next_list)): num = next_list[j] if current + num == target: return index, nums.index(num, index+1) print(twoSum([2,7,11,15],9))
b8b6206a110dbd92e7fc31c7fac2d9a6d1ab4898
Lucas-Guimaraes/Reddit-Daily-Programmer
/Easy Problems/131-140/136easy.py
990
3.71875
4
# https://www.reddit.com/r/dailyprogrammer/comments/1kphtf/081313_challenge_136_easy_student_management/ #Allows multiple lines to be read import sys #This program handles the initial function #Stu = 'students' def student_management(stu_input): #This handles all of the new lines space = stu_input.find(' ') + 1 line = stu_input.find('\n') + 1 n, m = int(stu_input[0:space]), int(stu_input[space:line]) average = 0 students = stu_input[line::].split("\n") #checks the amount of students and loops from that for i in range(n): data = students[i].split(" ", 1) students[i] = data[0] + (" %.2f" % (sum(float(n) for n in data[1].split(" ")) / m)) average += sum(float(n) for n in data[1].split(" ")) / (m * n) print "%.2f" % average #Prints each student at once for i in range(int(n)): print students[i] s = sys.stdin.read() #use ctrl+D after the input student_management(s)
763f8a75987f704b4f94188f5d0560ebb4721e2b
Airlis/LeetCode
/2.add-two-numbers.py
872
3.6875
4
# # @lc app=leetcode id=2 lang=python3 # # [2] Add Two Numbers # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(-1) result_tail = dummy carry = 0 while l1 or l2 or carry: first_digit = (l1.val if l1 else 0) second_digit= (l2.val if l2 else 0) digit = int((first_digit + second_digit + carry) % 10) carry = int((first_digit + second_digit + carry) / 10) result_tail.next = ListNode(digit) result_tail = result_tail.next l1 = (l1.next if l1 else None) l2 = (l2.next if l2 else None) return dummy.next # @lc code=end
70a39b776e4839816ab51346083e43c80b9dd44b
Chloejay/patterns
/structAlgorithm/selectionsort.py
396
3.890625
4
#! /usr/bin/env python def selectsort(lst): n = len(lst) for i in range(n): smallest = i for j in range(i+1, n): if lst[j] < lst[smallest]: #replace the smallest value to j smallest = j lst[smallest], lst[i]= lst[i], lst[smallest] #swap return lst if __name__ == '__main__': print(selectsort([4,2,10,1]))
b6cd38c77fd2e1749c899645b90e7222b0b8c48c
SamNadjari/Algorithms
/max_flow.py
1,619
3.578125
4
#Resources: https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ import networkx as nx def max_flow(residual, s, t): max_flow = 0 parent = {} for node in residual: parent[node] = "none" while augmenting_path(residual, s, t, parent) == True: v = t max_flow += 1 while v != s: u = parent[v] residual[u].get(v)['capacity'] -= 1 residual[v].get(u)['capacity'] += 1 v = parent[v] flow_dict = [] #print(residual.adj) for v, vals in residual[s].items(): if vals['capacity'] == 0: for u, vals2 in residual[v].items(): if vals2['capacity'] == 0: flow_dict.append(str(u[1]) + ' ' + str(u[0]) + ' ' + str(v[1]) + ' ' + str(v[0])) #done = [] #for u in residual: # for v, vals in residual[u].items(): # if vals['capacity'] == 1: # done.append((u,v)) # if (v,u) not in done: # flow_dict.append(str(v[1]) + ' ' + str(v[0]) + ' ' + str(u[1]) + ' ' + str(u[0])) return max_flow, flow_dict def augmenting_path(residual, s, t, parent): Q = [] Q.append(s) visited = [] visited.append(s) while Q: u = Q.pop(0) for v, vals in residual[u].items(): if v not in visited and vals['capacity'] > 0: Q.append(v) visited.append(v) parent[v] = u if t in visited: return True return False
352684d4471e2387368f2d8c11e49bc96df77b3a
mayakhanna4/adventofcode
/day7.py
1,191
3.59375
4
total_count = set() val_dict = {} def find(line_list, to_look ): print('TO LOOK: ' + to_look) for i in line_list: print(i[1]) if(i[1].find(to_look) != -1 ): print('in here') print(i[0].strip()) if(i[1].strip() not in total_count): total_count.add(i[0].strip()) find(line_list,i[0].strip()) def calc(val_list, to_look): track = 0; if(not val_list[to_look]): return 0; for key in val_list[to_look]: track = track + int(key[0]) + int(int(key[0]) * calc(val_list, key[1])) return track; def main(): input_file = open("day7.txt") line_list = [] val_list = {} for line in input_file.readlines(): line_list.append(line.split('bags contain')) temp_dict = [] for i in line.split('bags contain')[1].split(','): all_words = i.strip().split(' ') if(all_words[0] != "no"): temp_dict.append([all_words[0],all_words[1] + ' ' + all_words[2]]) val_list[line.split('bags contain')[0].strip()] = temp_dict print(calc(val_list, 'shiny gold')) if __name__ == "__main__": main()
26a94e93ffff957f7c6b187cbf85a72de9e1beef
ThiagoNFerreira/PythonFund
/exercicios/lojaRoupas/modules/produtos.py
492
3.75
4
produtos = [] def addProduto(nome, tamanho, preco): produto = { 'nome': nome, 'tamanho': tamanho, 'preco': preco } produtos.append(produto) def verProduto(): for p in produtos: print('================') print(f"Nome: {p['nome']}") print(f"Tamanho: {p['tamanho']}") print(f"Preço: {'preco'}") def removerProduto(produto): for p in produtos: if p==['Nome'] == produto: produtos.remove(p)
8b7a3409afe32eb96defc06cb3c81af1eb1a0932
tawatchai-6898/tawatchai-6898
/Lab03/Problem5.py
386
4.125
4
from functools import reduce def compute_sum_positive_odd_numbers(): get_num = list(map(int, input("Enter number of elements:").split())) less_than_zero = list(filter(lambda x: (x % 2 == 1 and x > 0), get_num)) product = reduce((lambda x, y: x + y), less_than_zero) return print(product) if __name__ == '__main__': compute_sum_positive_odd_numbers()
a7587bd466310d9453efea24fa0dc8528f2668da
cry999/AtCoder
/beginner/092/B.py
639
3.578125
4
def chocolate(N: int, D: int, X: int, A: list) -> int: # i 人目の参加者が食べる個数を m とすると、m は # (m-1)ai + 1 <= D # を満たす最大の m である。したがって、これを変形して、 # m = 1 + (D-1)//ai # となる。 # これを各 i について和をとって、残った X 個を足せば # 初日に用意されていた個数が算出できる。 return X + sum(1 + (D-1)//a for a in A) if __name__ == "__main__": N = int(input()) D, X = map(int, input().split()) A = [int(input()) for _ in range(N)] ans = chocolate(N, D, X, A) print(ans)
8e946987c9072069173e92d0746defeee815ccc8
Jon-Rey/DodgeBallZ
/game/buttons.py
1,751
3.890625
4
# Button class to create our on-screen buttons from globals import * import pygame class Button(pygame.sprite.Sprite): """Allows for the creation of buttons. Give the class its parameters and make a button that is any color, size, font and position""" def __init__(self, w, h, label="Button", color=RED): super().__init__() self.image1 = pygame.image.load("../assets/DBZ_GUIArt/DBZ_Main Menu/Buttons/DBZ_ButtonNormal.png") self.image2 = pygame.image.load("../assets/DBZ_GUIArt/DBZ_Main Menu/Buttons/DBZ_ButtonHover.png") self.label = label self.color = color self.image = self.image1 self.image = pygame.transform.scale(self.image, (w, h)) self.rect = self.image.get_rect() self.labelSurf = gameFont.render(self.label, \ True, \ WHITE) self.labelSize = gameFont.size(self.label) self.offset = ((w - self.labelSize[0])//2, (h - self.labelSize[1])//2) self.image.blit(self.labelSurf, self.offset) self.w = w self.h = h def onClick(self): """Return a message""" return self.label def onHover(self): """Highlight our button""" self.image = self.image2 self.image = pygame.transform.scale(self.image, (self.w, self.h)) self.image.blit(self.labelSurf, self.offset) def draw(self): """Draw Default button""" self.image = self.image1 self.image = pygame.transform.scale(self.image, (self.w, self.h)) self.image.blit(self.labelSurf, self.offset) def setPos(self, pos): """Set the center pos of the button""" self.rect.center = pos
6399eecebfec8538b62e259851041d786d9be62b
HKuz/MOOCMITx600
/6_00_1x/Midterm/midterm.py
6,365
3.765625
4
#!/usr/local/bin/python3 def main(): test_is_triangular = True test_print_without_vowels = True test_largest_odd_times = True test_dict_invert = True test_general_poly = True test_is_list_permutation = True if test_is_triangular: nums = [-1, 0, 0.5, 1, 2, 3, 4, 6, 10, 12, 15] res = [False, False, False, True, False, True, False, True, True, False, True] for i, k in enumerate(nums): test = is_triangular(k) if test == res[i]: print('PASSED: is_triangular({}) returned {}'.format(k, test)) else: print('FAILED: is_triangular({}) returned {}, should have returned {}'.format(k, test, res[i])) if test_print_without_vowels: strings = ['This is great!', 'THIs is greAt!'] res_2 = ['Ths s grt!', 'THs s grt!'] for i, s in enumerate(strings): test_2 = print_without_vowels(s) if test_2 == res_2[i]: print('PASSED: print_without_vowels({}) returned {}'.format(s, test_2)) else: print('FAILED: print_without_vowels({}) returned {}, should have returned {}'.format(s, test_2, res_2[i])) if test_largest_odd_times: lists = [[], [2, 2, 4, 4], [3, 9, 5, 3, 5, 3]] res_3 = [None, None, 9] for i, L in enumerate(lists): test_3 = largest_odd_times(L) if test_3 == res_3[i]: print('PASSED: largest_odd_times({}) returned {}'.format(L, test_3)) else: print('FAILED: largest_odd_times({}) returned {}, should have returned {}'.format(L, test_3, res_3[i])) if test_dict_invert: dicts = [ {1:10, 2:20, 3:30}, {1:10, 2:20, 3:30, 4:30}, {4:True, 2:True, 0:True} ] res_4 = [ {10: [1], 20: [2], 30: [3]}, {10: [1], 20: [2], 30: [3, 4]}, {True: [0, 2, 4]} ] for i, D in enumerate(dicts): test_4 = dict_invert(D) if test_4 == res_4[i]: print('PASSED: dict_invert({}) returned {}'.format(D, test_4)) else: print('FAILED: dict_invert({}) returned {}, should have returned {}'.format(D, test_4, res_4[i])) if test_general_poly: polys = [ [[1,2,3,4], 10] ] res_5 = [ 1234 ] for i, p in enumerate(polys): test_5 = general_poly(p[0])(p[1]) if test_5 == res_5[i]: print('PASSED: general_poly({})({}) returned {}'.format(p[0], p[1], test_5)) else: print('FAILED: general_poly({})({}) returned {}, should have returned {}'.format(p[0], p[1], test_5, res_5[i])) if test_is_list_permutation: perms = [ [['a', 'a', 'b'], ['a', 'b']], [[1, 'b', 1, 'c', 'c', 1], ['c', 1, 'b', 1, 1, 'c']], [[], []] ] res_6 = [ False, (1, 3, type(1)), (None, None, None) ] for i, p in enumerate(perms): test_6 = is_list_permutation(p[0], p[1]) if test_6 == res_6[i]: print('PASSED: is_list_permutation({}, {}) returned {}'.format(p[0], p[1], test_6)) else: print('FAILED: is_list_permutation({}, {}) returned {}, should have returned {}'.format(p[0], p[1], test_6, res_6[i])) return 0 def is_triangular(k): ''' k, a positive integer returns True if k is triangular and False if not Triangular number is a sum of sequential integers (1+2+3=6, 6 is triangular) ''' if type(k) is not int or k <= 0: return False tri = 0 for n in range(1, k+1): tri += n if tri == k: return True return False def print_without_vowels(s): ''' s: the string to convert Finds a version of s without vowels and whose characters appear in the same order they appear in s. Prints this version of s. Does not return anything (REMOVE RETURN AND UNCOMMENT PRINT AFTER TESTING) ''' vowels = 'AEIOUaeiou' no_vowel_for_you = '' for char in s: if char not in vowels: no_vowel_for_you += char # print(no_vowel_for_you) return no_vowel_for_you def largest_odd_times(L): ''' Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None ''' if not L: return None sorted_L = sorted(L, reverse=True) for num in sorted_L: count = sorted_L.count(num) if count % 2 == 1: return num return None def dict_invert(d): ''' d: dict Returns an inverted dictionary where keys are d's values, and values are a list of all d's keys that mapped to that original value ''' inverted = {} for k, v in d.items(): try: inverted[v].append(k) except KeyError: inverted[v] = [k] for k, v in inverted.items(): inverted[k] = sorted(v) return inverted def general_poly (L): ''' L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k + n1 * x^(k-1) + ... nk * x^0 ''' global k k = len(L) - 1 def f(x): global k result = 0 for n in L: result += n * (x ** k) k -= 1 return result return f def is_list_permutation(L1, L2): ''' L1 and L2: lists containing integers and strings Returns False if L1 and L2 are not permutations of each other. If they are permutations of each other, returns a tuple of 3 items in this order: the element occurring most, how many times it occurs, and its type ''' if len(L1) != len(L2): return False if not L1 and not L2: return (None, None, None) max_count = 0 max_item = None for item in L1: L1_count = L1.count(item) if item not in L2 or L2.count(item) != L1_count: return False if L1_count > max_count: max_count = L1_count max_item = item return (max_item, max_count, type(max_item)) if __name__ == '__main__': main()
0bdbe712ce37645c2308541c49e475f1732c6060
ekivoka/PythonExercises
/gen.py
304
3.671875
4
def primes(): n = 1 while True: n +=1 d = 0 for k in range(n): if n%(k+1) == 0: d+=1 if d==2: d = 0 yield n d = 0 k = 0 for x in primes(): print(x) k+= 1 if k > 10: break
2e5e388438add44633428d1e02144df0c901b6d9
igortereshchenko/amis_python
/km73/Samodryga_Oleg/3/task4.py
313
3.59375
4
n=int(input("Введіть кількість студентів ")) k=int(input("Введіть кількість яблук ")) stud=int(n/k) bag=int(n%k) print("Кількість яблук на студента", (str)(stud),"\nКількість яблук у кошику", (str)(bag)) input("")
a67bd5986d05e6ebbd9fa43e85248077a6f583d2
CCG-Magno/Tutoriales_Python
/utils/easy_plot.py
476
3.65625
4
import matplotlib.pyplot as plt def plot_fn(data=tuple(), labels=('X','Y'), scale="linear", title="Graph"): '''Disclaimer: Streamlined plotting from matplotlib functions, for ease of use not claiming ownership. ''' x, y = data x_label, y_label = labels plt.plot(x,y) plt.xlabel(x_label) plt.ylabel(y_label) plt.yscale(scale) plt.title(title) plt.show() plt.savefig(fname=title.join('.png'), format='png') return
60424942859871b84af7c9b1197f194a0cb16eb0
davidcoxch/PierianPython
/6_Methods_and_Functions/is_greater.py
325
4.15625
4
#create a function that returns True if first value is higher or equal # and false if the second value is higher def is_greater(c,d): return c>=d #When you run the statement above, you won't get any output #for the return satement displayed #So you have to wrap the function in a print statement print(is_greater(9,7))
8031a19f009cc8bfe7092d321f56b400135430a8
electriclo/quizgame
/quiz.py
1,003
3.765625
4
q1 = "what color is the sky? a.blue, b.red, c.green, d.yellow" print (q1) userchoice = input() count = 0 q1answer = "a" if userchoice == q1answer: print ("correct") count += 1 print (count) else: print ("incorrect") q2 = "what is 1 + 1? a.1, b.5, c.2" print (q2) userchoice = input() q2answer = "c" if userchoice == q2answer: print ("correct") count += 1 print (count) else: print ("incorrect") count-=1 print (count) q3 = "what is july 1? a.canada day, b.christmas, c.halloween" print (q3) userchoice = input() q3answer = "a" if userchoice == q3answer: print ("correct") count += 1 print (count) else: print ("incorrect") count-=1 print (count) q4 = "is tomato a fruit? a.True, b. False" print (q4) userchoice = input() q4answer = "a" if userchoice == q4answer: print ("correct") count += 1 print (count) else: print ("incorrect") count-=1 print (count)
8010e58862aa0561436f162f659284022b31f4f1
anotimpp90c2c7/zulip-gci-submissions
/interactive-bots/message_info/LarsZauberer/message_info.py
824
3.609375
4
# See readme.md for instructions on running this code. from typing import Any class MessageInfoHandler(object): def usage(self) -> str: return ''' This bot will allow users to analyze a message for word count. The gathered information will then be sent to a private conversation with the user. Users should @-mention the bot in the beginning of a message. ''' def handle_message(self, message: Any, bot_handler: Any) -> None: words_in_message = message['content'].split() content = "You sent a message with {} words.".format(len(words_in_message)) original_sender = message['sender_email'] bot_handler.send_message(dict( type='private', to=original_sender, content=content, )) handler_class = MessageInfoHandler
a888129e29c60ee7899e023b62061f184abfc52a
RaimundoJSoares/Programs-in-Python
/Separando_Numerais.py
519
3.8125
4
n = int(input('digite um numero')) #m = str(n) #print('analisando o numero{}'.format(n)) #print('Unidade : {}'.format(m[3])) #print('Dezena: {}'.format(m[2])) #print('Centena: {}'.format(m[1])) #print(' Milhar: {} '.format(m[0])) ( Vamos tentar o metodo 2, pq esse não da pra digitar numeros abaixo de 1000 pois da erro) u = n // 1 % 10 d = n // 10% 10 c = n // 100 % 10 m = n // 1000 % 10 print('Unidade: {}'.format(u)) print( 'Dezena : {}'.format(d)) print('Centena: {}'.format(c)) print(' Milhar: {}'.format(m))
216131c0fb36ff2d5c864d419ede8895d948c3c7
andriiglukhyi/codewars
/multi-tap-keypad/solution.py
299
3.5625
4
def presses(phrase): print(phrase) total = 0 char = ['1', 'abc2', 'def3', 'ghi4', 'jkl5', 'mno6','pqrs7', 'tuv8', 'wxyz9', ' 0', '#', '*'] for let in phrase.lower(): for but in char: if let in but: total+=but.index(let)+1 return total
b242242e6848f5c3c06d5635696f4135a8130dc1
CoraJung/book-recommendation-system
/working_files/nmslib_recommend2.py
2,499
3.53125
4
def augment_inner_product_matrix(factors): """ This involves transforming each row by adding one extra dimension as suggested in the paper: "Speeding Up the Xbox Recommender System Using a Euclidean Transformation for Inner-Product Spaces" https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/XboxInnerProduct.pdf # Code adopted from 'implicit' repo # https://github.com/benfred/implicit/blob/4dba6dd90c4a470cb25ede34a930c56558ef10b2/implicit/approximate_als.py#L37 """ import numpy as np norms = np.linalg.norm(factors, axis=1) max_norm = norms.max() extra_dimension = np.sqrt(max_norm ** 2 - norms ** 2) return np.append(factors, extra_dimension.reshape(norms.shape[0], 1), axis=1) def nmslib_recommend(spark, df, model, k=500): import nmslib import numpy as np # user_factors only for the users in the given df (ordered by user id) subset_user = df.select('user').distinct() whole_user = model.userFactors user = whole_user.join(subset_user, whole_user.id == subset_user.user).orderBy('id') user_factors = user.select('features') # item_factors ordered by item id item = model.itemFactors.orderBy('id') item_factors = item.select('features') # save user/item label user_label = [user[0] for user in user.select('id').collect()] item_label = [item[0] for item in item.select('id').collect()] # to numpy array user_factors = np.array(user_factors.collect()).reshape(-1, model.rank) item_factors = np.array(item_factors.collect()).reshape(-1, model.rank) print("feature array created") # Euclidean Transformation for Inner-Product Spaces extra = augment_inner_product_matrix(item_factors) print("augmented") # create nmslib index recommend_index = nmslib.init(method='hnsw', space='cosinesimil') recommend_index.addDataPointBatch(extra) recommend_index.createIndex({'post': 2}) print("index created") # recommend for given users query = np.append(user_factors, np.zeros((user_factors.shape[0],1)), axis=1) results = recommend_index.knnQueryBatch(query, k) recommend = [] for user_ in range(len(results)): itemlist = [] for item_ in results[user_][0]: itemlist.append(item_label[item_]) recommend.append((user_label[user_], itemlist)) return recommend
b076717a05b1032acb6fd355316c11ab3c78987a
JeradXander/pythoMyCode
/loops/WorkingWith/csvChallenge.py
1,948
4.03125
4
#!/usr/bin/env python3 """CSV Challenge reading and writing food data""" # standard library import import csv #lists to add data too boysList = [] girlsList = [] with open("babyName.csv","r") as names: #variables ind = 0 year = 2000 haveGirl = False rowNumber = 0 #for loop to loop through names for row in csv.reader(names): rowNumber += 1 #skipping first legend row if ind ==0: ind += 1 continue else: #skipping first row which is the legend if len(row) != 0: #if current row is eqauls to year wanted if int(row[0]) == year: if row[2] == "F" and haveGirl is False: #adding girl to List girlsList.append(f"{row[1]} was the most popular girls name in the year {row[0]} with {row[3]} girls being named that!!\n") ind += 1 haveGirl = True elif row[2] == "M": #increasing variables year +=1 ind +=1 #adding boys to list boysList.append(f"{row[1]} was the most popular boys name in the year {row[0]} with {row[3]} girls being named that!!\n") haveGirl = False #writing most popular names with open ("mostPopularNames", "w") as popFile: #writing girls names print("Girls Name",file=popFile) print("-"* 30,file=popFile ) for girls in girlsList: print(girls,file=popFile) #writing boys names print("\n\nBoys List", file=popFile) print("-"* 30,file=popFile ) for boys in boysList: print(boys,file=popFile) #output to let user know file was saved print(f"mostPopularNames file created from {rowNumber} names")
331fc8f0f0c0280da993772157a0585a38aad03c
joanne282/code-up
/zz/201023_1094.py
183
3.796875
4
def main(): n = int(input()) numbers = input().strip().split(' ') for number in reversed(numbers): print(number, end=' ') if __name__ == '__main__': main()
66c18ccffc4a1a2f0cdb62cc34c7664b8dc3b549
aspidistras/grandpy-bot
/botapp/models/user.py
1,525
3.75
4
"""defines User model and Login Form""" from wtforms import form, fields, validators from flask_sqlalchemy import SQLAlchemy from flask_security import UserMixin db = SQLAlchemy() class User(db.Model, UserMixin): """initializes User object with its attributes to permit account creation and login""" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) role = db.Column(db.String(255)) def __init__(self, email, password, active, role): self.email = email self.password = password self.active = active self.role = role class LoginForm(form.Form): """initializes LoginForm object with its attributes and methods to permit login and raise errors if login data doesn't match db data""" email = fields.StringField(validators=[validators.required()]) password = fields.PasswordField(validators=[validators.required()]) def validate_login(self): """get user or return errors if user doesn't exist or pasword is wrong""" user = self.get_user() if user is None: raise validators.ValidationError('Invalid user') if user.password != self.password.data: raise validators.ValidationError('Invalid password') def get_user(self): """query user from database matching entered infos""" return db.session.query(User).filter_by(email=self.email.data).first()
81fc4c546b2f906537134bb87b25a40107860d6b
KevenGe/LeetCode-Solutions
/problemset/1001. 网格照明/solution.py
2,140
3.6875
4
# 1001. 网格照明 # https://leetcode-cn.com/problems/grid-illumination/ from typing import List class Solution: def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]: row = {} col = {} dig = {} anti_dig = {} pos = {} for x, y in lamps: if x in pos: pos[x][y] = 1 else: pos[x] = { y: 1 } for k, v in pos.items(): for k2, v2 in v.items(): x = k y = k2 if x in row: row[x] += 1 else: row[x] = 1 if y in col: col[y] += 1 else: col[y] = 1 if y - x in dig: dig[y - x] += 1 else: dig[y - x] = 1 if y + x in anti_dig: anti_dig[y + x] += 1 else: anti_dig[y + x] = 1 ans = [] for x, y in queries: if (x in row and row[x] > 0) or \ (y in col and col[y] > 0) or \ (y - x in dig and dig[y - x] > 0) or \ (y + x in anti_dig and anti_dig[y + x] > 0): ans.append(1) else: ans.append(0) for delta_x in range(-1, 2, 1): for delta_y in range(-1, 2, 1): nx = x + delta_x ny = y + delta_y if nx in pos and ny in pos[nx] and pos[nx][ny] == 1: pos[nx][ny] = 0 row[nx] -= 1 col[ny] -= 1 dig[ny - nx] -= 1 anti_dig[ny + nx] -= 1 return ans if __name__ == "__main__": solution = Solution() print(solution.gridIllumination( 6, [[2, 5], [4, 2], [0, 3], [0, 5], [1, 4], [4, 2], [3, 3], [1, 0]], [[4, 3], [3, 1], [5, 3], [0, 5], [4, 4], [3, 3]] ))
c90e123c1362646ea62541f1d9538b84cc027477
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/mkxtat001/util.py
1,771
3.9375
4
#Tato Moaki MKXTAT001 #Module of functions to manipulate 2-D arrays of size 4 x 4 #Assignment7 question2 def create_grid(grid): """create a 4x4 grid""" for i in range(4): grid.append([0] * 4) #create a list of size 4 and append to grid to create a 2-D array return(grid) def print_grid (grid): """print out a 4x4 grid in 5-width columns within a box""" print("+--------------------+") for row in range(4): print("|",end="") for column in range(4): if (grid[row][column] == 0): print("{0:<5}".format(" "),end="")#left align grid[row][column] in width of 5 else: print("{0:<5}".format(grid[row][column]),end="") print("|") print("+--------------------+") def check_won(grid): """return True if a value>=32 is found in the grid; otherwise False""" for row in range(4): for column in range(4): if grid[row][column] >= 32: return True else: return False def check_lost (grid): """return True if there are no 0 values and no adjacent values that are equal; otherwise False""" for row in range(3): for column in range(3): if grid[row][column] == grid[row][column+1] or grid[row][column] == grid[row+1][column] or grid[row][column]== 0: return False else: return True def copy_grid (grid): """return a copy of the grid""" grid_copy = [] for element in grid: grid_copy.append(list(element)) return grid_copy def grid_equal (grid1, grid2): """check if 2 grids are equal - return boolean value""" if grid1 == grid2: return True return False
915114dcad82ccc9c0597c64e6966f07e30e5ddf
Myusuft/Alpro-part5
/PRAUTS/max4ankga.py
170
3.671875
4
def mulai(nilai): for i in range (1,nilai+1,1): print(i) for i in range(nilai-1,0,-1): print(i) nilai = int(input()) print(mulai(nilai))
b9d6698a9768b274e72fc44d66e6fe482fa1b587
winkitee/coding-interview-problems
/41-50/42_validate_binary_search_tree.py
1,277
4.1875
4
""" Hi, here's your problem today. This problem was recently asked by Facebook: You are given the root of a binary search tree. Return true if it is a valid binary search tree, and false otherwise. Recall that a binary search tree has the property that all keys in the left subtree are less than or equal to the root, and all keys in the right subtree are greater than or equal to the root. Here's a starting point: class TreeNode: def __init__(self, key): self.left = None self.right = None self.key = key def is_bst(root): # Fill this in. """ class TreeNode: def __init__(self, key): self.left = None self.right = None self.key = key def is_bst(root): if root is None: return True if root.left is not None and root.left.key > root.key: return False if root.right is not None and root.right.key <= root.key: return False is_valid_left = is_bst(root.left) if is_valid_left is False: return False is_valid_right = is_bst(root.right) if is_valid_right is False: return False return True a = TreeNode(5) a.left = TreeNode(3) a.right = TreeNode(7) a.left.left = TreeNode(1) a.left.right = TreeNode(4) a.right.left = TreeNode(6) print(is_bst(a)) # True
3b35b7856a31eaf4c30425c94a2def2d5e269edb
NChesser/Challenge
/005/budgeter.py
1,631
4.03125
4
# budget program, where I can enter in my expenses and it will store results # perhaps I can also incorperate some graphs or something import sqlite3 import random # might want to change the database name, if I want this to be a budget program EXPENSE_DATABASE = "expenses.db" EXPENSE_TYPES = ("FOOD", "RENT", "UTILITIES", "ENTERTAINMENT", "MISC") # Perhaps I need an income table def create_database(): db = sqlite3.connect(EXPENSE_DATABASE) cursor = db.cursor() cursor.execute('''DROP TABLE expenses''') db.commit() cursor.execute("CREATE TABLE expenses(uid INTEGER PRIMARY KEY, type TEXT, cost INTEGER)") db.commit() db.close() def get_expenses(expense_type): db = sqlite3.connect(EXPENSE_DATABASE) cursor = db.cursor() cursor.execute("SELECT cost, type FROM expenses WHERE type=?", (expense_type,)) values = [row for row in cursor] for row in values: print('{0} : {1}'.format(row[0], row[1])) print(expense_type + " Total: " + str(sum([row[0] for row in values]))) db.close() def add_expense(uid, expense_type, cost): db = sqlite3.connect(EXPENSE_DATABASE) cursor = db.cursor() if expense_type in EXPENSE_TYPES: cursor.execute("INSERT INTO expenses(uid, type, cost) \ VALUES(?,?,?)", (uid, expense_type, cost)) db.commit() db.close() #create_database() #for i in range(100): #add_expense(i, random.choice(EXPENSE_TYPES), random.randrange(1000)) get_expenses("FOOD") print() get_expenses("RENT") print() get_expenses("MISC")
9e60a508267078e8f308650a0a2944663fcc0783
shihongup/MNIST_KNN
/MNIST_KNN/MNIST_KNN_Py.py
6,107
3.9375
4
# coding: utf-8 # <h1><font size="6">CSCI 6364 - Machine Learning</font></h1> # <h1><font size="5">Project 1 - MNIST</font></h1> # <p><font size="4"><span style="line-height:30px;">Student: Shifeng Yuan</span><br> # <span style="line-height:30px;">GWid: G32115270<span><br> # Language: Python<font><br> # <span style="line-height:30px;">Resource: MNIST data from Kaggle <span></p> # In[4]: import numpy as np import pandas as pd import matplotlib.pyplot as plt, matplotlib.image as mpimg from sklearn.model_selection import train_test_split #get_ipython().run_line_magic('matplotlib', 'inline') # <h1>1. Dataset Details</h1> # <p> &nbsp; <font size="3">Here we have two datasets, one is training data and another is the testing data.</font></p> # <ol><font size="3"> # <li>The training data contains the data of 28000 images</li> # <li>Each image is described as 28*28=784 columns with numbers representing its lightness or darkness</li> # <li>The first column is the actual number of what the image represents</li> # <li>The testing data is the same as the training data but it does not have the "label" column which should be generated.</li> # <font></ol> # <h2>Data Spliting</h2> # <p><font size="3">First, we need to read the data into a variable called dataset. And we should split the data into images and labels as two parts. Usually, we divide our dataset into 2 to 3 parts. Here, I split the dataset into training data (80%) and testing data(20%)</font></p> # In[5]: dataset=pd.read_csv('data/mnistdata/train.csv') images=dataset.iloc[0:28000,1:] labels=dataset.iloc[0:28000,:1] train_images,test_images,train_labels,test_labels=train_test_split(images,labels,random_state=2,test_size=0.2) # <h2> Inspect the Dataset </h2> # In[93]: # Read the dataset and then print the head print( len(dataset) ) print( dataset.head() ) # <h2>Dataset Visualization</h2> # <p><font size="3">We can use the .imshow() in the matplotlib package to visualize the data as a picture. We first select a row, here it the 4th row, and then reshape it into 28*28 matrix, finally the package gives the picture.</font></p> # In[61]: i=3 img=images.iloc[i].values img=img.reshape(28,28) plt.imshow(img,cmap='gray') plt.title(train_labels.iloc[i]) # <p><font size="3">Use the .hist() to draw a histgram of the data.</font></p> # In[68]: plt.hist(images.iloc[0]) # <h1>2. Algorithm Description</h1> # <p><font size="3"></font></p> # <h2>Selection of K</h2> # <p><font size="3">The selection of value K is important for KNN, usually, we make K the square root of the size of the test sample, however, because this dataset is too big, we simply make it 5.</font></p> # <p><font size="3">The package sklearn.neighbors.KNeighborsClassifier implementing the K-nearest Neighbors # classification.</font></p> # <p><font size="3"> # Using the sklearn KNeighborsClassifier package, define the metric method as euclidean. # we simply use a brute force algorithm.</font></p> # In[13]: from sklearn.neighbors import KNeighborsClassifier clf=KNeighborsClassifier(n_neighbors = 5, algorithm = 'brute', p = 2, metric = 'euclidean') clf.fit(train_images,train_labels.values.ravel()) # <h1>3. Algorithm Results</h1> # <p><font size="3">Start predict and measure the accuracy of the algorithm.</font></p> # In[14]: predictions=clf.predict(test_images) # In[15]: print(predictions) # <h2>Confusion Matrix</h2> # In[19]: from sklearn.metrics import confusion_matrix cm = confusion_matrix(test_labels, predictions) print(cm) # <p><font size="3">The full confusion matrix shown below, and the accuracy score is 0.9578571428571429.</font></p> # <img src='../MNIST_confusion.png' width = '800' height='500'> # In[46]: from sklearn.metrics import accuracy_score print(accuracy_score(test_labels,predictions)) # <p><font size="3">Then start predicting the test data in the test.csv</font></p> # In[8]: # read the test data into variable testd testd=pd.read_csv('data/mnistdata/test.csv') # In[47]: result=clf.predict(testd) # In[48]: print(result) # <p><font size="3">Choosing the 100th number in the test set so see the variance caused by the K.</font></p> # In[9]: img_100 = testd.iloc[99:100,:] # In[86]: # k=5 result1 = clf.predict(img_100) print(result1) # In[87]: # k=9 from sklearn.neighbors import KNeighborsClassifier clf=KNeighborsClassifier(n_neighbors = 9, algorithm = 'brute', p = 2, metric = 'euclidean') clf.fit(train_images,train_labels.values.ravel()) result2 = clf.predict(img_100) print(result2) # In[88]: # k=3 from sklearn.neighbors import KNeighborsClassifier clf=KNeighborsClassifier(n_neighbors = 3, algorithm = 'brute', p = 2, metric = 'euclidean') clf.fit(train_images,train_labels.values.ravel()) result3 = clf.predict(img_100) print(result3) # In[89]: # k=11 from sklearn.neighbors import KNeighborsClassifier clf=KNeighborsClassifier(n_neighbors = 9, algorithm = 'brute', p = 2, metric = 'euclidean') clf.fit(train_images,train_labels.values.ravel()) result4 = clf.predict(img_100) print(result4) # <p><font size="3">It turns out that the 100th number is predicted as 4 when k=5,9,3,11. The accuracy is fine.</font></p> # In[50]: # Output the result as .csv file df=pd.DataFrame(result) df.index.name='ImageId' df.index+=1 df.columns=['Label'] df.to_csv('results.csv',header=True) # <h1>4. Runtime</h1> # <p><font size="3"></font></p> # <p><font size="3"> # For d dimension, we need O(d) runtime to compute one distance between two data, so computing all the distance between one data to other data needs O(nd) runtime, then we need O(kn) runtime to find the K nearest neibors, so, in total, it takes O(dn+kn) runtime for the classifier to classify the data. # </font></p> # In[10]: import time start = time.time() clf=KNeighborsClassifier(n_neighbors = 5, algorithm = 'brute', p = 2, metric = 'euclidean') clf.fit(train_images,train_labels.values.ravel()) result=clf.predict(testd) end = time.time() print(end-start) # <p><font size="3"> # As is shown above, the "wall-clock" of the runtime is about 158.66s # </font></p>
4c53ba02b1b8aa08839f8d938c0f0ec358ec0a91
ebertti/PAA-PUCRio
/fastpower.py
256
3.90625
4
#-*- coding: utf-8 -*- def FastPower(a,b) : if b == 1: return a else: c = a*a ans = FastPower(c,b/2) if b % 2 != 0: return a*ans else: return ans if __name__ == "__main__": print FastPower(2, 9)
8025ca02c2bfda5094529b9cf719eb7a89bb6afc
dsnair/python3-examples
/python1/01_bignum.py
188
3.6875
4
# Print out 2 to the 65536 power # (try doing the same thing in the JS console and see what it outputs) from math import pow print("2^2 is", pow(2, 2)) print("2^65536 is", pow(2, 65536))
ce354a9afa400dd931f6b76e94c70e86f40243db
bannavarapu/Competetive_Programming
/competetive_programming/week1/day4/second_largest_tree.py
1,249
4.1875
4
def find_second_largest(root): # Find the second largest item in the binary search tree elements=[] elements.append(root) values=[] while(len(elements)>0): temp=elements.pop() values.append(temp.value) if(temp.left is not None): elements.append(temp.left) if(temp.right is not None): elements.append(temp.right) values=sorted(values) if(len(values)==1): raise Exception if(len(values)>=2): return values[len(values)-2] def find_largest(root): if root is None: return None while(root.right is not None): root=root.right return root.value def find_second_largest(root): # Find the second largest item in the binary search tree parent=root child= parent.right if parent.right is not None else None if(child==None and parent.left is None): raise Exception elif parent.right is None and parent.left!=None: return find_largest(parent.left) else: while(child.right is not None): parent=child child=child.right if(child.left is not None): return find_largest(child.left) else: return parent.value
c65b9a90def083856515f772682986094dcc596a
ErdenebatSE/resource-of-python-book
/7-python/function/squares.py
486
4.3125
4
# Модулийн тодорхой хэсгийг импортлох """ from functions import square for i in range(3,6): print(f"{i} -н квадрат: {square(i)}") """ # Модулийг бүхэлд нь импортлох """ import functions for i in range(3,6): print(f"{i} -н квадрат: {functions.square(i)}") """ # Модулийг дахин нэрлэх import functions as f for i in range(3,6): print(f"{i} -н квадрат: {f.square(i)}")
a17135f97e8ab8687a75e52c02e2292373677b1f
2648226350/Python_learn
/pych-eight/8_3to8_5.py
547
3.96875
4
#8-3 def make_shirt(size, words): print("This T-shirt is "+str(size)+" yards in size, and it was printed with '"+words+"'.") make_shirt(34,'Warrios') make_shirt(words = 'Rise',size = 55) #8-4 def make_big_shirt(size, words = 'I love Python'): print("This T-shirt is "+str(size)+" yards in size, and it was printed with '"+words+"'.") make_big_shirt(34) #8-5 def describe_city(name, country = 'china'): print(name.title()+" is in "+country.title()+".") describe_city('Peking') describe_city('Changsha') describe_city('London','england')
5eca1fa7a68665227b38cd6249b90199adfdf792
SonjaZucki/Lektion12
/sum.py
179
3.703125
4
def sum_numbers(num1, num2): result = num1 + num2 return result print(sum_numbers(2, 8)) print(sum_numbers(10, 3)) print(sum_numbers(87, 30)) print(sum_numbers(74, 112))
383ba0ecde3b55400966390764cdbf9effe7c567
adithyakumar303/python
/quiz.py
2,136
4.0625
4
print("genaral knolsdge quiz") score=0 print("\n") print("1. who is the first man on the moon") answer=input("enter you answer: ") if answer == "neil armstrong": print("answer is correct") score=score+1 else: print("anser is wrong") print("\n") print("2. who is the first man to climb mount everest") answer=input("enter you answer: ") if answer == "edmund hillary": print("answer is correct") score=score+1 else: print("anser is wrong") print("\n") print("3. who was the 16 president of the united states") answer=input("enter you answer: ") if answer == "abraham lincon": print("answer is correct") score=score+1 else: print("anser is wrong") print("\n") print("4. who is the current president of india") answer=input("enter you answer: ") if answer == "ram nath kovind": print("answer is correct") score=score+1 else: print("anser is wrong") print ("score= ",score) print("\n") print("5. who discovored penicillin") answer=input("enter you answer: ") if answer == "alexander fleming": print("answer is correct") score=score+1 else: print("anser is wrong") print("\n") print("6. who created stan lee") answer=input("enter you answer: ") if answer == "stan lee": print("answer is correct") score=score+1 else: print("anser is wrong") print("\n") print("6. who was the first president of USA") answer=input("enter you answer: ") if answer == "GEORGE washinton": print("answer is correct") score=score+1 else: print("anser is wrong") print("\n") print("8. who invented telephone") answer=input("enter you answer: ") if answer == "alexsander grahambel": print("answer is correct") score=score+1 else: print("answer is wrong") print("\n") print("9. who is th the co-founder of microsoft") answer=input("enter you answer: ") if answer == "bill gates": print("answer is correct") score=score+1 else: print("answer is wrong") print("\n") print("9. who founded apple ") answer=input("enter you answer: ") if answer == "steve jobs": print("answer is correct") score=score+1 else: print("answer is wrong") print ("score= ",score)
5673c2fca3e69019f2ca443a09226ea8a8595a74
Poloeli303/mandelbrot
/mandelbrot.py
1,890
4.53125
5
#Mandelbrot Set Program #Graphs the Mandelbrot set iteratively (function is NOT recursive) #Written by Dr. Mo, Fall 2019 import pygame import math import cmath pygame.init() pygame.display.set_caption("mandelbrot") # sets the window title screen = pygame.display.set_mode((800, 800)) # creates game screen screen.fill((0,0,0)) #mandelbrot function definition------------------------ def mandelbrot(c): z = complex(0,0); count = 0; while abs(z) < 2 and count < 80: z = z * z + c; count+=1; return count; #end mandelbrot function-------------------------------- #------------------------------------------------------- #in C++, this would be the start of main---------------- t = -2 #lower bound for real axis while t<2: #upper bound for real (horizontal) axis t+=.01 #make this number SMALLER to increase picture resolution m = -2 #lower bound for imaginary axis while m<2: #upper bound for imaginary (vertical) axis m+=.01 #make this number SMALLER to increase picture resolution c = complex(t, m) #create a complex number from iterators num = mandelbrot(c); #call the function #these if statements are just to differentiate the colors more, not needed if you want black & white image if num < 20: screen.set_at((int(t * 200 + 400), int(m * 200 + 400)), (num*8, num*6, num*12)) elif num<40: screen.set_at((int(t * 200 + 400), int(m * 200 + 400)), (num*2, num/2, num*6)) elif num is 80: screen.set_at((int(t * 200 + 400), int(m * 200 + 400)), (255,255,255)) else: screen.set_at((int(t * 200 + 400), int(m * 200 + 400)), (num*3, num/2, num*2)) pygame.display.flip()#this actually puts the pixel on the screen pygame.time.wait(10000)#pause to see the picture pygame.quit()#quit pygame
379344e8cdfb21f9ac4b32e4773802447ce476c3
RIT-CS-Mentoring-Center-Queueing/mmcga_project
/server/rmq_examples/hw_server.py
994
3.578125
4
#!/usr/bin/python3 ## ## File: hw_server.py ## ## Author: Schuyler Martin <sam8050@rit.edu> ## ## Description: Initial "hello world" server program for RabbitMQ using pika ## import pika #### GLOBALS #### #### FUNCTIONS #### def callback(ch, method, properties, body): print("Got: " + str(body)) #### MAIN #### def main(): ''' Main execution point of the program ''' # establish connection to server socket = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = socket.channel() # send information to a specific RabbitMQ queue; building this queue for # the first time channel.queue_declare(queue="Default Queue") # actually submit the message channel.basic_consume(callback, queue="Default Queue", no_ack=True); print("Waiting for messages. CTRL-C to exit") # busy loop that waits for messages to come in; will clean up itself? channel.start_consuming() if __name__ == "__main__": main()
2982c39c1e086231f9ed1528acf290c82d8eb82c
sei1225/python_biginner
/56.py
390
3.71875
4
# def outer(a: int, b: int) -> None: # def inner() -> int: # return a + b # return inner # f = outer(1, 2) # r = f() # print(r) def circle_area_func(pie: float) -> None: def circle_area(radius: int) -> float: return pie * (radius ** 2) return circle_area ca1 = circle_area_func(3.14) ca2 = circle_area_func(3.14159265) print(ca1(10)) print(ca2(10))
38517484c7aac9bb4ba767d08f6a492e10e96895
zmmille2/playground
/swapper.py
1,095
3.5625
4
from collections import defaultdict if __name__ == "__main__": num_tests = int(raw_input()) while num_tests > 0: string = raw_input() forward_x = 0 forward_y = 0 forward_best = 0 backward_x = 0 backward_y = 0 backward_best = 0 for index in xrange(len(string) - 1): if string[index] == 'x': forward_x += 1 if string[index] == 'y': forward_y += 1 if forward_x < forward_y: forward_best = forward_x else: forward_best = forward_y string = string[::1] for index in xrange(len(string) - 1): if string[index] == 'x': backward_x += 1 if string[index] == 'y': backward_x += 1 if backward_x > backward_y: backward_best = backward_x else: backward_best = backward_y if backward_best < forward_best: print backward_best else: print forward_best num_tests -= 1
2797d337634abfed1890e8b1a96ec202f145e80a
epsequiel/LPTHW
/ex32.py
765
4.21875
4
#! /usr/bin/python # Ejercicio 32 pagina 106 the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # Ciclo sobre una lista for number in the_count: print "This is the count %d" % number # Mismo tipo de ciclo for fruit in fruits: print "A fruit of type %s" % fruits # Tambien podemos recorrer listas cuyos elementos son # de diferente tipo de dato/ # Como no sabemos de antemano el tipo usamos '%r' for i in change: print "I got %r" % i # Tambien podemos construir listas elements = [] # Luego usar la funcion ;range' for i in range(0, 6): print "Adding %d to the list." % i elements.append(i) # Ahora imprimo for i in elements: print "Element was: %d" % i
3e79a67ea7ffd78a7ef1d629b6f6cd122cdf8c09
MrLoh/ALP2-Uebungen
/U04/A1 - mergesort.py
4,347
3.75
4
# Aufgabenteil a) def is_sorted(L): '''Kontrolliert ob eine Liste sortiert ist, für ansteigend sortierte Listen wird 1 zurüch gegeben, für absteigend sortierted Listen -1, für unsortierte 0 und für Listen mit gleichem Element None.''' sort = None i = 0 while sort == None and i+1 < len(L): if L[i] < L[i+1]: #Liste ist nicht absteigend sort = 1 elif L[i] > L[i+1]: #Liste ist nicht aufsteigend sort = -1 i += 1 while sort == 1 and i+1 < len(L): if L[i] > L[i+1]: #Liste ist weder auf- noch absteigend sort = 0 i += 1 while sort == -1 and i+1 < len(L): if L[i] < L[i+1]: #Liste ist weder ab- noch aufsteigend sort = 0 i += 1 return sort # Tests L1 = [1,2,3,4,5] L2 = [5,4,3,2,1] L3 = [5,4,3,1,2] L4 = [1,2,3,5,4] L5 = [0,0] for L in [L1,L2,L3,L4,L5]: print(is_sorted(L)) print() # Aufgabenteil b) from random import randint def generate_random_list(a=0,b=99,n=50): '''Generiert eine Liste der Länge n mit ganzen Zufallszahlen im Bereich zwischen a und b.''' return [ randint(a,b) for i in range(n) ] # Aufgabenteil c) def bubble_sort(L,lo,up): '''Sortiert den abschnitt zwischen lo und up der gegebene Liste L mit Bubble-Sort.''' remain_up = up-1 done = False while not done: done = True for i in range(lo,remain_up): if L[i] > L[i+1]: done = False L[i], L[i+1] = L[i+1], L[i] remain_up -= 1 def merge(L,H,lo,up,mid): '''Merged die beiden Listenabschnitte von L zwischen lo-mid und mid-up in der Hilfsliste H.''' i = lo j = mid for k in range(lo,up): if i < mid and j < up: if L[i] <= L[j]: H[k] = L[i] i += 1 else: H[k] = L[j] j += 1 elif i < mid: H[k] = L[i] i += 1 elif j < up: H[k] = L[j] j += 1 def merge_sort(L,H,lo,up,length,threshold=9): '''Sortiert die Liste L zwischen up und lo. Dabei wird die Hilfsliste H verwendet und die Liste wird an der Stelle lo+length geteilt. Up threshold wird Bubble-Sort verwendet.''' if length <= threshold: # print("SORTING:\nlength: %s, lo: %s, up: %s" % (length,lo,up)) # print(" L: %s \n ->" % (L) ) bubble_sort(L,lo,up) # print(" L: %s \n" % (L) ) else: mid = lo+length L = merge_sort(L,H,lo,mid,length//2,threshold) #rekursiv die erste Hälfte sortieren L = merge_sort(L,H,mid,up,length//2,threshold) #rekursiv die zweite Hälfte sortieren # print("MERGING:\nlength: %s, lo: %s, up: %s, mid: %s" % (length,lo,up,mid)) # print(" L: %s \n H: %s \n ->" % (L,H) ) merge(L,H,lo,up,mid) # print(" H: %s \n" % (H) ) L = H[:] #L updaten return L def merge_sort_init(L,threshold=9): '''Sortiert die Liste L mit Mergesort. Optional, kann angegeben werden, ab welchem threshold Bubble-Sort benutzt werden soll.''' if len(L) < threshold: bubble_sort(L,0,len(L)) else: H = L[:] length = len(L)//2 #gibt die Länge der zu mergenden Listen an L = merge_sort(L,H,0,len(L),length,threshold) return L # Tests for i in range(10): L = generate_random_list(0,20,16) L = merge_sort_init(L) # L = [16, 14, 6, 5, 1, 7, 10, 4, 15, 9, 2, 12, 11, 13, 3, 8] # L = merge_sort_init(L,2) if is_sorted(L) == 1: print("Eine Liste wurde erfolgreich sortiert") else: print("!!! ERROR !!!") print() # Aufgabenteil d def merge_sort(L,threshold=9): '''Sortiert die Liste L mit Mergesort. Optional, kann angegeben werden, ab welchem threshold Bubble-Sort benutzt werden soll.''' len_L = len(L) size = min(threshold,len_L) #sortiere die Teillisten for lo in [i*size for i in range(round(len_L/size+.5))]: up = min(lo+size,len_L) # print("SORTING:\nlength: %s, lo: %s, up: %s" % (size,lo,up)) # print(" L: %s \n ->" % (L) ) bubble_sort(L,lo,up) # print(" L: %s \n" % (L) ) #merge die Teillisten while size < len_L: H = L[:] #H updaten for lo in [i*2*size for i in range(round(len_L/(2*size)+.5))]: mid = lo+size up = min(lo+2*size,len_L) # print("MERGING:\nlength: %s, lo: %s, up: %s, mid: %s" % (size,lo,up,mid)) # print(" L: %s \n H: %s \n ->" % (L,H) ) merge(L,H,lo,up,mid) # print(" H: %s \n" % (H) ) L = H[:] #L updaten size *= 2 return L # Tests for i in range(10): L = generate_random_list(0,20,16) L = merge_sort(L) # L = [16, 14, 6, 5, 1, 7, 10, 4, 15, 9, 2, 12, 11, 13, 3, 8] # L = merge_sort(L,2) if is_sorted(L) == 1: print("Eine Liste wurde erfolgreich sortiert") else: print("!!! ERROR !!!")
3acb35589324d9b6b1841a7bbd72a548d5b6589f
yukatherin/project-euler
/my_solutions/p66.py
1,089
3.609375
4
from math import sqrt import numpy as np def is_square(n): return sqrt(n)==int(sqrt(n)) def solvable_for(x,D): y = (x**2-1)/float(D) return is_square(y) and y>0 def argmax_min(maxD): max_x = 10**8 Ds = set([i for i in range(2,maxD+1) if not is_square(i) ]) for x in range(1,max_x): newDs = Ds.copy() for D in Ds: if solvable_for(x,D): newDs.remove(D) if (len(Ds)==1): print Ds return Ds = newDs print Ds def min_x_soln(D): assert not is_square(D) max_x=10**7 for x in range(1,max_x): if solvable_for(x,D): return x print 'no soln found for', D def argmax_D(maxD): curr_max_D = None curr_max_min = 1 for D in range(2,maxD+1): #print D if is_square(D): continue min_x = min_x_soln(D) if min_x > curr_max_min: curr_max_D= D curr_max_min=min_x return curr_max_D, curr_max_min if __name__=="__main__": print argmax_min(100)
613ae55a27ccff2a521695c0f209704569893e49
gschen/sctu-ds-2020
/1906101100-卢栎冰/Day20200225/作业test3.py
474
3.9375
4
# 3.(使用def函数完成)找出传入函数的列表或元组的奇数位对应的元素,并返回一个新的列表 # 样例输入 # 1,2,3,4,5,6,7 # 样例输出 # 1, 3, 5, 7 # x=[1,2,3,4,5,6,7] # def f(x): # return x=2*n+1 # print(x) 错的 def f(x): list=[] for i in range(len(x)): if i%2==1: list.append(x[i]) return list print(f([1,2,3,4,5,6,7,8,9])) def f(x): list=[] for i in range(len(x)): if i%2==1:
61712a005f494d877132ce0c33d6058776c9a9e4
acastro84/Intro-to-Python
/Lab5b.py
5,964
4.375
4
#Cleans up previous code a user menu. Imports package conversionlabs to perform the conversion functions. #import the module needed for the conversions import conversionslabs #Set constraints for the menu: MILES_TO_KM = 1 FAH_TO_CELSIUS = 2 GAL_TO_LITERS = 3 POUNDS_TO_KG = 4 INCHES_TO_CM =5 QUIT_CHOICE = 0 QUIT2 = int(2) # The main function def main(): choice = 6 while choice != QUIT_CHOICE: display_menu() #Get the users choice choice = int(input('Please select which conversion you would like to use. ')) #Perform the selected action if choice == MILES_TO_KM: sent = 1 max_tries = 0 miles = float(input('Please enter the amount of miles. ')) while sent == 1: max_tries = max_tries + 1 if miles < 0: print('Miles cannot be less than zero.') if max_tries <3: print((3 - max_tries), "tries remaining.") miles = float(input("Please enter a new number. ")) else: sent = 0 else: sent = 0 else: if max_tries == 3 and miles < 0: print(' You entered the incorrect value',max_tries, 'times, closing program. ') choice = 0 else: print(miles, 'miles is' ,conversionslabs.milesToKm(miles), 'kilometers.') elif choice == FAH_TO_CELSIUS: sent = 1 max_tries = 0 cels = float(input('Please enter the degrees in Fahrenheit. ')) while sent == 1: max_tries = max_tries + 1 if cels > 1000: print('Temperature entered cannot be larger than 1000.') if max_tries < 3: print((3 - max_tries), "tries remaining.") cels = float(input("Please enter a new number. ")) else: sent = 0 else: sent = 0 else: if max_tries == 3 and cels > 1000: print(' You entered the incorrect value',max_tries, 'times, closing program. ') choice = 0 else: print(cels, "degrees Fahrenheit is " ,format(conversionslabs.FahToCel(cels), '.2f'),"degrees celsius.") elif choice == GAL_TO_LITERS: max_tries = 0 sent = 1 liters = float(input('Please enter the number of liters to be converted. ')) while sent == 1: max_tries = max_tries +1 if liters < 0: print('Entered amount cannot be less than zero.') if max_tries < 3: print((3 - max_tries), "tries remaining.") liters = float(input("Please enter a new number. ")) else: sent = 0 else: sent = 0 else: if max_tries == 3 and liters < 0: print(' You entered the incorrect value',max_tries, 'times, closing program. ') choice = 0 else: print(liters, "gallons is ",conversionslabs.GalToLit(liters), "liters.") elif choice == POUNDS_TO_KG: max_tries = 0 sent = 1 pounds = float(input('Please enter the amount of pounds to be converted. ')) while sent == 1: max_tries = max_tries + 1 if pounds < 0: print('Entered amount cannot be a negative number.') if max_tries < 3: print((3 - max_tries), "tries remaining.") pounds = float(input("Please enter a new number. ")) else: sent = 0 else: sent = 0 else: if max_tries == 3 and pounds < 0: print(' You entered the incorrect value',max_tries, 'times, closing program. ') choice = 0 else: print(pounds, "pounds is ",conversionslabs.PoundsToKg(pounds), "Kilograms.") elif choice == INCHES_TO_CM: max_tries = 0 sent = 1 inches = float(input('Please enter the number of inches to be converted. ')) while sent == 1: max_tries = max_tries + 1 if inches < 0: print('Entered amount cannot be a negative number.') if max_tries < 3: print((3 - max_tries), "tries remaining.") inches = float(input('Please enter a new number.')) else: sent = 0 else: sent = 0 else: if max_tries == 3 and inches < 0: print(' You entered the incorrect value',max_tries, 'times, closing program. ') choice = 0 else: print(inches, "inches is",conversionslabs.InchesToCm(inches), "centimeters.") elif choice == QUIT_CHOICE: QUIT2 = 2 else: if choice == 6 and QUIT2 != 2: choice= input('Invalid Selection. Please try again. Enter 0 to quit. ') else: print('Exiting Program. ') # The display function displays a menu for the user def display_menu(): print(' Menu' ) print('1) Miles to Kilometers') print('2) Fahrenheit to Celsius') print('3) Gallons to Liters') print('4) Pounds to Kilograms') print('5) Inches to Centimeters') print('0) Quit') # Call the main function main()
14b935b0b7c78cfb1be6eb9ecaf78f012e075ad8
jandirafviana/python-exercises
/my-python-files/aula07_desafio006.py
886
4.1875
4
print('=== DESAFIO 006 ===') print('Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada:') n = int(input('Digite um número:')) print(f'O dobro de {n} é {n*2}, o triplo é {n*3} e a raiz quadrada é {n**(1/2):.2f}.') n = int(input('Digite outro número: ')) dobro = n*2 triplo = n*3 raiz = n**(1/2) print(f'O dobro de {n} é {dobro}, o triplo é {triplo} e a raiz quadrada é {raiz:.2f}.') # Para que o programa force a execução do "meio" (1/2) primeiro ao invés da potência, a gente coloca entre parênteses. # Porque os parênteses estão na ordem de precedência. # Format é o método, do objeto que é a string. n = int(input('Digite outro número: ')) dobro = n*2 triplo = n*3 raiz = pow(n, (1/2)) print('O dobro de {} é {}, o triplo é {} e a raiz quadrada é {:.2f}.'.format(n, dobro, triplo, raiz)) # pow(power) - função de potência
a9d71a0ed6825624fea6e099bc1e829b69eda285
CReesman/Python_Crash_Course
/Python_Crash_Course_Book/CH5/stages_of_life_5_6.py
1,083
4.40625
4
''' 5-6 Stages of Life: Write an if-elif-else chain that determines a person’s stage of life. Set a value for the variable age, and then: *If the person is less than 2 years old, print a message that the person is a baby. *If the person is at least 2 years old but less than 4, print a message that the person is a toddler. *If the person is at least 4 years old but less than 13, print a message that the person is a kid. *If the person is at least 13 years old but less than 20, print a message that the person is a teenager. *If the person is at least 20 years old but less than 65, print a message that the person is an adult. *If the person is age 65 or older, print a message that the person is an elder. Christopher Reesman 5/7/20 ''' age = 15 if age < 2: print("This person is a baby.") elif age == 2 or age < 4: print("This person is a toddler.") elif age == 4 or age < 13: print("This person is a kid.") elif age == 13 or age < 20: print("This person is a teenager.") elif age == 20 or age < 65: print("This person is an adult.") else: print("This person is an elder.")
09729d23b344960ffee4ab15c5817923fb84c2bc
algebra-det/Python
/OOPs/Polymorphism_Method_Overriding.py
833
4.125
4
class A: def show(self): print("In A show") class B: pass a1 = A() a1.show() b1 = B() #b1.show() # this will not work as show is not present in class B print("__________") class Al: def show(self): print("In A show") class Bl(Al): pass al1 = Al() al1.show() bl1 = Bl() bl1.show() # as Bl has inherited Al, so if it does not have show() than it will go to parent class # for executing show() method print("________") class Alp: def show(self): print("In A show") class Blp(Alp): def show(self): print("In B show") alp1 = Alp() alp1.show() blp1 = Blp() blp1.show() # Now as we have show() in Class Blp, SO it will not go to parent class for show() # Hence it will execute the show() method of it's own class
88cf63f62ac4c58413519b2d00b94fde2c123b86
wbkusy/pythonalx
/Arytmetyka.py
554
4.15625
4
# 1. przypisz do zmiennych x i y jakieś wartości liczbowe kożystając z funkcji print wypisz na ekranie podstawowe działania arytmetyczne # (dodawanie, dzielenie, odejmowanie, potęgowanie, mnożenie, dzielenie z resztą, dzielenie całkowite) # uruchom program kilka raz dla różnych wartości x = 13 y = 6.3 print("x=", x, "y=", y) print("dzielenie:", x / y) print("mnożenie:", x * y) print("odejmowanie:", x - y) print("dodawanie:", x + y) print("dzielenie całkowite:", x // y) print("dziel z resztą", x % y) print("potęgowanie:", pow(x, y))
1c52cabacf6958d664ea9d4803faa7109f4ce2ea
Ynjxsjmh/PracticeMakesPerfect
/LeetCode/p0239/I/sliding-window-maximum.py
2,175
3.875
4
# -*- coding: utf-8 -*- # ******************************************************************************** # Copyright © 2022 Ynjxsjmh # File Name: sliding-window-maximum.py # Author: Ynjxsjmh # Email: ynjxsjmh@gmail.com # Created: 2022-06-28 10:03:33 # Last Updated: # By: Ynjxsjmh # Description: You are given an array of integers `nums`, there is a # sliding window of size `k` which is moving from the very left of the # array to the very right. You can only see the `k` numbers in the # window. Each time the sliding window moves right by one position. # # Return *the max sliding window*. # # Example 1: # Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 # Output: [3,3,5,5,6,7] # Explanation: # Window position Max # --------------- ----- # [1 3 -1] -3 5 3 6 7 3 # 1 [3 -1 -3] 5 3 6 7 3 # 1 3 [-1 -3 5] 3 6 7 5 # 1 3 -1 [-3 5 3] 6 7 5 # 1 3 -1 -3 [5 3 6] 7 6 # 1 3 -1 -3 5 [3 6 7] 7 # # Example 2: # Input: nums = [1], k = 1 # Output: [1] # # Constraints: # * `1 <= nums.length <= 105` # * `-104 <= nums[i] <= 104` # * `1 <= k <= nums.length` # ******************************************************************************** class Solution(object): def maxSlidingWindow(self, nums, k): """使用大根堆记录滑动窗口内 k 个数和索引, 因此根节点就是窗口内的最大数和其索引。 每次窗口右移时,当新数加进堆中, 1. 新数是最大的,直接取堆顶 2. 新数不是最大的,比较堆顶索引是否在当前 滑动窗口内,不是的话弹出,直到堆顶索引 在滑动窗口内。此时堆顶为窗口内最大值。 :type nums: List[int] :type k: int :rtype: List[int] """ heap = [(-nums[i], i) for i in range(k)] heapq.heapify(heap) max_nums = [-heap[0][0]] for i in range(k, len(nums)): heapq.heappush(heap, (-nums[i], i)) while heap[0][1] <= i-k: heapq.heappop(heap) max_nums.append(-heap[0][0]) return max_nums
1bd0781093c119be099ede8f1260207e682e59b0
Pradeepsuthar/pythonCode
/PythonProgramsTraining/classes (1)/exh.py
882
3.703125
4
try: bill = int(input("Enter bill amount:- ")) quantity = float(input("Enter quantity:- ")) rate=bill/quantity print("RATE:- %0.2f"%rate) except Exception as ex1: print(type(ex1)," : ",ex1) try: marks=[90.2,34,56.87,15] rno=int(input("Enter roll number:- ")) print("Marksof roll no %d is %0.2f"%(rno,marks[rno-1])) except Exception as ex2: print(type(ex2)," : ",ex2) try: FILE_NAME=input("Enter file name:- ") fr=open(FILE_NAME) print(fr.read()) fr.close() except Exception as ex3: print(type(ex3)," : ",ex3) try: str="Divyansh" print(str[4]) except Exception as ex4: print(type(ex4)," : ",ex4) print("HAHAHAAHAAHHAHAHHAHAHAHAHAHHAHAHHHAHAHAHHAHHAHHHHAHAHHHAHAHAHAHHAHAHAHAHHAHHAHAHAHAHHAHAHAHAHHAHAHAHHAHAHAHAHAHAHHAHAHAHHAHAAHHAHAHAHAHHAHAHAHAHAHHAAHAHAHHAHAHAHHAHAHAHAHHAHAHAH :)")
799c8c958c1f82c2bf8ad522efc7deda894228c5
atulgupta9/DigitalAlpha-Training-Programs
/Day2/prog1.py
250
4.28125
4
# Write a program which will find all # such numbers which are divisible by 9 but are # not a multiple of 5,between 0 and 3000 (both included). Print them on screen for x in range(0, 3000): if x % 9 == 0 and x % 5 != 0: print(x)
1fb1320979773158abbb95b91417e69512f0c5c4
JasonkayZK/Python
/Python_Fundamental_Lesson/3_Exception_File/file/Readlines.py
169
3.546875
4
file = open("test.txt", "r") print(file.readlines()) file.close() # Use for ... in ... clause file = open("test.txt", "r") for line in file: print(line) file.close()
846389d288b41f2cdea794e0b90c7a0088b5452b
bondarchukb/patterns
/behavior/chain_of_responsibility.py
1,418
3.640625
4
class WeirdCafeVisitor(object): def __init__(self, cafe_visitor=None): self.cafe_visitor = cafe_visitor def handle_food(self, food): print("just pass") if self.cafe_visitor is not None: self.cafe_visitor.handle_food(food) class BestFriend(WeirdCafeVisitor): def __init__(self, cafe_visitor): super(BestFriend, self).__init__(cafe_visitor) self.coffe_cintain_food = [] def handle_food(self, food): print("I take some coffe and meat") test_food = food[0] if test_food == 'coffe' or test_food == 'meat': self.coffe_cintain_food.append(food.pop()) print(self.coffe_cintain_food) return self.cafe_visitor.handle_food(food) class GirlFriend(WeirdCafeVisitor): def __init__(self, cafe_visitor): super(GirlFriend, self).__init__(cafe_visitor) self.some_food_for_girls = [] def handle_food(self, food): print("I take some girls food") test_food = food[0] if test_food == 'girls food': self.some_food_for_girls.append(test_food) print(self.some_food_for_girls) return self.cafe_visitor.handle_food(food) if __name__ == '__main__': some_company = BestFriend(GirlFriend(WeirdCafeVisitor())) food = ['food1', 'food2'] food = ['girls food', 'food2'] some_company.handle_food(food)
4518d571c62dc4b32335b4eff9a9343b299e175e
mingyyy/onsite
/week_02/mini_projects/02_bottles.py
1,762
4.3125
4
''' -------------------------------------------------------- 99 BOTTLES OF BEER LYRICS -------------------------------------------------------- https://www.reddit.com/r/beginnerprojects/comments/19kxre/project_99_bottles_of_beer_on_the_wall_lyrics/ -- GOAL -- Create a program that prints out every line to the song "99 bottles of beer on the wall." This should be a pretty simple program, so to make it a bit harder, here are some rules to follow. -- RULES -- 1) If you are going to use a list for all of the numbers, do not manually type them all in. Instead, use a built in function. MY: ord("c") is 99 2) Besides the phrase "take one down," you may not type in any numbers/names of numbers directly into your song lyrics. 3) Remember, when you reach 1 bottle left, the word "bottles" becomes singular. 4) Put a blank line between each verse of the song. ''' num = ord("c") def repeat(n): if num-n-1 == 0: return str(num-n) + " bottle of beer on the wall, " + str(num-n) + " bottle of beer.\n" \ "Take one down and pass it around, no more bottles of beer on the wall." elif num-n-1 == 1: return str(num-n) + " bottles of beer on the wall, " + str(num-n) + " bottles of beer.\n" \ "Take one down and pass it around, " + str(num-n-1) + " bottle of beer on the wall." else: return str(num-n) + " bottles of beer on the wall, " + str(num-n) + " bottles of beer.\n " \ "Take one down and pass it around, " + str(num-n-1) + " bottles of beer on the wall." for i in range(num): print(repeat(i),"\n") print("No more bottles of beer on the wall, no more bottles of beer. \n" "Go to the store and buy some more, " + str(num) + " bottles of beer on the wall.")
b68da7030cf713c2fc0c53483df835cf9b3be83f
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4194/codes/1630_2946.py
250
3.71875
4
ml=float(input("Media dos laboratorios: ")) mt=float(input("Media dos trabalhos: ")) mp=float(input("Media das provas: ")) var1=round(ml/100, 2) var2=round(mt/100, 2) var3=round(mp/100, 2) notafinal=round((var1*25+var2*30+var3*45),2) print(notafinal)
8cdfeb75b07c506db6523f312ff52727a4a903e2
ming-log/Multitasking
/03 协程/06 生成器.py
344
3.859375
4
# !/usr/bin/python3 # -*- coding:utf-8 -*- # author: Ming Luo # time: 2020/9/8 15:55 # 列表生成式 nums = [x*2 for x in range(10)] # 生成器generator nums = (x*2 for x in range(10)) # 使用next()方法取生成器的值 next(nums) # 生成器是一种特殊的迭代器 # 生成器都是迭代器,但是迭代器不一定是生成器
6fa86c826862497c0e21e25c9d71777ca5629982
erika-r/CA268_python
/week7/hash.py
254
3.90625
4
def main(): lst = [1, 5, 27, 35, 11, 15, 105, 95, 31] hashset = HashSet() for x in lst: hashset.add(x) print(hashset) #all numbers that end in the same number are all indexed the same eg 5,35,15 if __name__ == "__main__": main()
3e61587f7e3c19ef6ba6131b080b234bc3d93e16
brandonhillert/StructeredProgramming
/Mastering Mastermind/mastermind_comp_vs_me.py
4,439
4.03125
4
""""BRON : 2.1 A Simple Strategy YET ANOTHER MASTERMIND STRATEGY Department of Philosophy, University of Groningen, The Netherlands Barteld Kooi """ import itertools import random """Deze functie genereert een random combinatie uit de lijst https://pynative.com/python-random-choice/""" def random_combinatie_computer(lijst): return random.choice(lijst) """Deze functie retouneert een lijst met alle mogelijke combinaties van abcdef""" """https://stackoverflow.com/questions/45990454/generating-all-possible-combinations-of-characters-in-a-string""" def lijst_combinaties(): lijst = [] for x in itertools.product(*(['abcdef'] * 4)): lijst.append(''.join(x)) return lijst """Deze functie vraagt de gebruiker om een code in te voeren en checkt de code op invoer""" def code_invullen(): code = " " print("Vul een code in: ") code = input() for i in code: if i not in "abcdef" or len(code) != 4: print("Foutmelding") print("Vul een code in") code = input() return code """" Hier zou ik nog een if/else/while/for loop kunnen maken die de input controleert": Als zwartpinnen is 0, moet witte pinnen 0 tm 4 zijn Als zwartepinnen is 1, moeten witte pinnen 0 tm 3 zijn Als zwartepinnen is 2 moeten witte pinnen 0 tm 2 zijn Als zwartepinnen is 3, moeten witte pinnen 0 tm 1 zijn Als zwartepinnen is 4, moeten wittte pinnen 0 zijn """ def feedback_geven_mens(): feedback = [] print("Geef aantal zwarten pinnen: ") zwarten_pinnen = int(input()) print("Geef aantal witte pinnen: ") witte_pinnen = int(input()) feedback.append(zwarten_pinnen) feedback.append(witte_pinnen) return feedback """ Deze functie krijgt 2 waardes die worden meegegeven: 1. De random waarde die wordt gekozen door de computer in een lijst = de gok 2. De lijst met nog alle combinaties die mogelijk zijn De functie gaat de lijst door met alle combinaties die mogelijk zijn. Hij vergelijkt de combinatie in die lijst met de gok van de computer. Ieder getal krijgt hiervoor een bepaalde feedback. Deze lijst kan vervolgens in een andere functie worden gebruikt, om de feedback met de code te vergelijken met de feedback van de gok. """ def lijst_analyseren_comp(gok_computer , lijst ): lijst_feedback = [] for combinatie in lijst: zwarte_pinnen = 0 witte_pinnen = 0 #stopt de waardes in een lijst, zodat deze bewerkt kan worden combinatie_in_lijst = list(combinatie) gok_in_lijst = list(gok_computer) for i in range(len(combinatie_in_lijst)): if combinatie_in_lijst[i] == gok_in_lijst[i]: zwarte_pinnen += 1 combinatie_in_lijst[i] = 0 gok_in_lijst[i] = 1 if combinatie_in_lijst[i] in gok_in_lijst: witte_pinnen += 1 combinatie_in_lijst[i] = 0 gok_in_lijst[i] = 1 feedback_per_combinatie = [zwarte_pinnen, witte_pinnen] lijst_feedback.append(feedback_per_combinatie) return lijst_feedback """" Vergelijk de feeedback ( feedback_geven_mens) met de lijst die alle feedback van de gok heeft Alle elementen in die lijst, die niet gelijk staan aan de feedback verwijderen Ook alle combinaties in lijst_combinaties verwijderen met dezelfde index als de feedback""" def nieuwe_lijst_feedback(feedback, lijst_combinaties, lijst_feedback ): nieuwe_lijst_feedback = [] lijst_mogelijke_combinaties = [] index = 0 for i in lijst_feedback: if i == feedback: nieuwe_lijst_feedback.append(i) lijst_mogelijke_combinaties.append(lijst_combinaties[index]) index += 1 return lijst_mogelijke_combinaties def hoofd_programma(): #Lijst met alle mogelijke combinaties lijst = lijst_combinaties() #Code invullen code = code_invullen() print("________________________") for i in range(10): gok_computer = random_combinatie_computer(lijst) print("De computer gokt:") print(gok_computer) print("Mogelijkheden code:") print(lijst) print(lijst_analyseren_comp(gok_computer ,lijst )) if len(lijst) == 1: print("Je hebt verloren") break feedback = feedback_geven_mens() lijst = nieuwe_lijst_feedback(feedback, lijst, lijst_analyseren_comp(gok_computer , lijst ))
7fc6d6bb5303815e46d847e793b0140b014296ad
ElliotSis/Projets
/IA/TP IA Polytechnique/TP1/Miscellaneous/antenna.py
1,061
4.0625
4
import math from utilities import * # Class Antenna # Represents an Antenna # - Coordinates # - Radius # - Enclosed points class Antenna: # When an antenna is created, we first enclose only one point def __init__(self, point): self.center = point self.radius = 1 self.points = [] self.addPoint(point) def equals(self, antenna): return self.center == antenna.center and self.radius == antenna.radius and set(self.points) == set(antenna.points) # Adds a point to the antenna def addPoint(self, point): self.points.append(point) if (not isInside((self.center[0], self.center[1], self.radius), point)): x, y, self.radius = smallestEnclosingCircleInt(self.points) self.center = (x, y) # Cost of the antenna def cost(self, K, C): return K + C*((self.radius)**2) def show(self): print '\tAntenna :' print '\t\tCenter :', self.center print '\t\tRadius :', self.radius print '\t\tPoints covered :', self.points
871a180c4b62fc550a0887beb398ca61907d34cc
hadassa5sf/cleanFunction.py
/presisionMach_Function.py
11,273
3.921875
4
import pandas as pd import numpy as np import math import xlsxwriter as xlsw """ CHANGING ROW AND COLON AND WORK WITH DATAFRAME - VERY GOOD SITE: https://www.askpython.com/python-modules/pandas/update-the-value-of-a-row-dataframe ADDING NEW LIST TO A DATAFRAME import pandas as pd info= {"Num":[], "NAME":[], "GRAD":[]} data = pd.DataFrame() print("Original Data frame:\n") print(data) #SYNTAX: dataframe.at[index,'column-name']='new value' data.at[0,'NAME']='Safa' data.at[0,'GRAD']=90 data.at[1,{'NAME','GRAD'}]=50, 'Hadassa' print("new Data frame:\n") print(data) """ """" help function """ def is_letter(row): """ check if the all row is only caracters :param row: :return: true if there are a number """ for n in row: if n.isalpha()==False: return True return False def list_contains(data, testing): """ check match between two lists :param data: line from excel :param testing: xRow testing :return: the number of same latter in order start to end, not have to be consecutive """ t = 0#index for testing count = 0#count how match good latter type_g = "A"#each move latter move to the secand latter secont = False #for case that we begine fron the secont true number fron the vin excel for s in range(len(testing)-1):#find the first letter in the test barcod that is similar to the true vin if data[0] == testing[s]: t=s#from there continue to check for not have stop in the start of the list break if data[1] == testing[s+1]:#if we have a mistake in the first latter to start to check from the secend one t=s+1#from there continue to check for not have stop in the start of the list secont = True break for i in range(len(data)):#check in the true vin, if there are other same latter if YES Advance the test list also #if we begain from the secent number vin if secont==True: i = 1 # be sure that we begin from the second latter secont = False # for do this law only one time #if there are a latter in the middel of the vin scip it if testing[t].isalpha() == True: t = t+1 i = i+1 if t == len(testing): break if i == len(data): break #if we begane from the first number vin or after update the "secont case" if data[i] == testing[t]: count = count + 1 """ #find the Type if t-i==1: type_g = 'B' elif t-i==2: type_g = 'C' elif t - i > 2: type_g = 'bad' """ t = t+1 if t == len(testing): break if i == len(data): break return count#, type_g # Python program to Split string into characters def split(word): return [char for char in word] def get6final(vincolon,fullVINashdod , trueVIN_6latter): """ get from the Ashdod the kast 6 latter with out space :param vincolon:the all data_Excel :return: a list of string """ for index, row in vincolon.iterrows(): a = str(row['שילדה']) #print("The full VIN:",a) a_vin = [] count = 6 #print(type(row['שילדה']) ) fullVINashdod.append(a) for i in range(len(a)-1, -1, -1): if count == 0:# we get 6 last vin number break if a[i] != ' ': a_vin.append(a[i]) count = count - 1 a_vin.reverse() #print(a_vin) trueVIN_6latter.append(a_vin) def smallerList(list): """ if there are no match small the list if it is big then len(list)>7 :param vincolon:a test list :return: a small list """ count = 6 small_list = [] for i in range(len(list)-1, -1, -1): if count == 0:# we get 6 last vin number break small_list.append(list[i]) count = count - 1 small_list.reverse() return small_list def charExsisted(char, char_list): """ check if a char already exsist in the charlist :return: the list """ for c in char_list: if c == char: return char_list char_list.append(char) return char_list def last_8_latter(listfullVin): """ to fine the possible character in place -6 and -7 in the full vin :param vincolon:a test list :return: a small list """ count = 8 charList_6 = [] charList_7 = [] for row in listfullVin: #for not full vin continue if len(row)<17:continue #save the -6 vin place if row[12].isalpha(): charList_6 = charExsisted(row[12],charList_6) # save the -7 vin place if row[11].isalpha(): charList_7 = charExsisted(row[11],charList_7) return charList_6, charList_7 def adapted(fullVINashdod , xRow): charList_6, charList_7 = last_8_latter(fullVINashdod) #chack if the last char are number and the len row is between 14-17 or 3-6 if xRow[-1].isalpha()!=True: if 14<=len(xRow)<17: miss = 17-len(xRow) for i in range(miss):xRow.append('&') print(xRow) elif 3<=len(xRow)<6: miss = 6 - len(xRow) for i in range(miss):xRow.append('&') print(xRow) #if the first vin is a latter if xRow[0].isalpha(): goodChar = False #if she is part of the posible start vin latter for char in charList_6: if char == xRow[0]: goodChar = True break #if it is not a good start latter, it is a false read if goodChar == False: y=8 #change """ work steps """ def firstUpdate(ashdodExcel): """ read the ashdod excel and create the data frame resault :param ashdodExcel: :return: a empty data frame """ fullVINashdod = [] trueVIN_6latter = [] dataAshdod = pd.read_excel(ashdodExcel) # "ashdod_4_3_21.xlsx" get6final(dataAshdod ,fullVINashdod , trueVIN_6latter) info = {"Camera Name":[], "Test Vin From Image":[], "index from excel":[], "Potential vin from excel":[], "Grade":[], "Type":[]} df_resaulte = pd.DataFrame(info) return df_resaulte, fullVINashdod, trueVIN_6latter def AddNewRow(df,df_index,cameraName, vinFromImage, indexExcel, vinFromExcel, Grade , Type): """ function that add a new row to the data frame :return: the update data frame and the index for the next row """ # SYNTAX: dataframe.at[index,'column-name']='new value', list of value as to be in a revers order df.at[df_index, "Camera Name"] = cameraName df.at[df_index, "Test Vin From Image"] = vinFromImage df.at[df_index, "index from excel"] = indexExcel df.at[df_index, "Potential vin from excel"] = vinFromExcel df.at[df_index, "Grade"] = Grade df.at[df_index, "Type"] = Type #df.at[df_index, {"Camera Name", "Test Vin From Image", "index from excel", "Potential vin from excel", "Grade" , "Type"}] =Type, Grade, vinFromExcel,indexExcel,vinFromImage,cameraName df_index = df_index+1 return df, df_index def checkTextRow(fullVINashdod, name_cam, trueVIN_6latter, xRow , resaultDataframe, df_index): """ get the row and chack: * there are number on it * check if this txt row is cut or have a big error * did thise txt fixed row are matching to an excel line * give a weight to different potencial excel rows with similar grad :param xRow: :return:resaultDataframe (-update one),df_index(-for continuse write in) , [xRow,best_i_excel,bestVin] (-for save the best resault) """ ###two side range case #save the best resault bestGrad = 0 #flage for no vin row noVin_row = True best_i_excel = None bestVin = None j = 1 #for all the true excel compere to single test line from barcod for trueL in trueVIN_6latter: j = j + 1 number = list_contains(trueL, xRow) #if there are more then 3 samilare from 6 letter - save it as a potencial if number>3: noVin_row = False print(trueL,"number " ,number )#, "type grade:",type_g) temp = (number*100)/6 print("grad:",temp) # save the all parameter #AddNewRow(resaultDataframe, df_index, name_cam, xRow, j, trueL, temp, 'A') df_index = df_index+1 if temp >= bestGrad:# and Type=='A': bestVin = trueL best_i_excel = j bestGrad = temp if noVin_row == True: best_i_excel = None bestVin = 'No VIN row' return resaultDataframe, df_index , [xRow,best_i_excel,bestVin,bestGrad] def PrecisionMach(fullVINashdod, trueVIN_6latter ,googleText ,resaultDataframe ): """ get a line from the txt file and send it to check vin only if it is not start or end, and containe number on it :param ashdodlist: :param googleText: :param resaultDataframe: :return: """ run_df_index = 0 save_best_resault = [] #open the .txt google file resault f = open(googleText, "r") # ("tester.txt", "r") for x in f: # find the first and end line for each image #if x == '\n': #print("Finish this image") #print("\n-------------------------------------------\n") #break #scip notusfull lines if x == '\n' or x == 'Output:':continue if 'Image name:' in x: name_cam = x.split(':')[1].split('\n')[0] print("start ",name_cam," image:") continue #if the all text no containe any vin if 'Time estimate' in x: print("Finish this image") print("\n-------------------------------------------\n") continue xArr = split(x) xArr.remove('\n') # chack that the row is not cut, if it is cut add the sine & adapted(fullVINashdod, xArr) # if there are number if is_letter(xArr) and len(xArr) > 7: xArr = smallerList(xArr) resaultDataframe, run_df_index , [xRow,best_i_excel,bestVin,bestGrad] = checkTextRow(fullVINashdod,name_cam, trueVIN_6latter, xArr, resaultDataframe, run_df_index) save_best_resault.append([xRow,best_i_excel,bestVin,bestGrad]) return save_best_resault, resaultDataframe #read the Excel and creat the dataFrame ans df_resaulte, fullVINashdod, trueVIN_6latter = firstUpdate('ashdod_4_3_21.xlsx') save_best_resault, df_resaulte = PrecisionMach(fullVINashdod, trueVIN_6latter , 'run1.txt', df_resaulte) for ob in save_best_resault: print(ob)
6c4f4eb8bb911da17184707281d15dae751042c8
EricRovell/project-euler
/deprecated/037/python/037.py
1,209
3.828125
4
# primes generator [left_limit; right_limit] def prime(left, right): for possiblePrime in range(left, right + 1): for number in range(2, int(possiblePrime ** 0.5 + 1)): if possiblePrime % number == 0: break else: yield possiblePrime # returns a list of all truncation of the given number # direction: -1 - for left truncation; 1 - for right only; 0 - for both def truncate(number, direction = 0): if 0 <= number <= 9: return [number] number = str(number) left = [int(number[index:]) for index in range(len(number))] if direction == -1: return left right = [int(number[:index]) for index in range(1, len(number) + 1)] if direction == 1: return right left.extend(right) return left # returns the list of the first "amount" of truncatable primes def truncatable_primes(amount): primes = set() truncatable_primes = set() while True: for prime_number in prime(2, 10 ** 9): primes.add(prime_number) truncated = set(truncate(prime_number)) if truncated.issubset(primes): truncatable_primes.add(prime_number) if len(truncatable_primes) == amount: return truncatable_primes # tests print(truncatable_primes(15))
89bc3339e32a09673bc5b2536ac68852281975b1
weiguozhao/LeetCodes
/src/_python/hot100/53_MaximumSubarray.py
2,296
3.703125
4
# coding:utf-8 from typing import List class Solution: """ problem 53 https://leetcode-cn.com/problems/maximum-subarray/ 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 """ def maxSubArrayGreedy(self, nums: List[int]) -> int: length = len(nums) curr_sum = max_sum = nums[0] for i in range(1, length): # 当前元素与当前和的最大值 curr_sum = max(nums[i], curr_sum + nums[i]) # 当前最大和与历史最大和的最大值 max_sum = max(max_sum, curr_sum) return max_sum def maxSubArrayDivideAndConquer(self, nums: List[int]) -> int: return self._devide_and_conquer_(nums, 0, len(nums) - 1) def _cross_sum_(self, nums: List[int], left: int, right: int, mid: int) -> int: """ cross部分一定包含 nums[mid], 因此由mid向两端连加取其中最大值 """ if left == right: return nums[left] left_subsum = float('-inf') curr_sum = 0 for i in range(mid, left - 1, -1): curr_sum += nums[i] left_subsum = max(left_subsum, curr_sum) right_subsum = float('-inf') curr_sum = 0 for i in range(mid + 1, right + 1): curr_sum += nums[i] right_subsum = max(right_subsum, curr_sum) return left_subsum + right_subsum def _devide_and_conquer_(self, nums: List[int], left: int, right: int) -> int: if left == right: return nums[left] mid = (left + right) >> 1 left_sum = self._devide_and_conquer_(nums, left, mid) right_sum = self._devide_and_conquer_(nums, mid + 1, right) cross_sum = self._cross_sum_(nums, left, right, mid) return max(left_sum, right_sum, cross_sum) if __name__ == '__main__': nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] res = Solution().maxSubArrayDivideAndConquer(nums) print(res)
1530299c56d70e7f8d3d6249478e478ad19db9c8
adrgrc26/Learning-Python
/fizzbuzz.py
935
4.25
4
#!/usr/bin/env python3 # Write a program that prints the numbers from 1 to 100 # For multiples of 3 print “Fizz” instead of the number # For the multiples of 5 print “Buzz” # For numbers which are multiples of both 3 and 5 print “FizzBuzz”. for i in range (1, 101): if i % 3 == 0 and i % 5 == 0: print ('FizzBuzz') elif i % 5 == 0: print ('Buzz') elif i % 3 == 0: print ('Fizz') else: print (i) #let's hope this goes 1--> 100; it does. other code did 0' """ python3 fizzbuzz.py 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz """
8f5feed067f82d046f142fd20b668f4516eb8e83
Ayushkumar11/Data-structure-Algo
/problem_1.py
1,399
4.3125
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number == 0 or number == 1: return number if number < 0: return -1 lower_bound = number // 2 upper_bound = lower_bound delta = upper_bound - lower_bound while delta != 1: if lower_bound * lower_bound > number: upper_bound = lower_bound lower_bound //= 2 if upper_bound * upper_bound <= number: return upper_bound delta = upper_bound - lower_bound if delta > lower_bound: upper_bound -= delta // 2 elif delta < 10 and delta > 1: upper_bound -= (upper_bound % 2) + 1 elif delta == 1: return lower_bound else: upper_bound -= delta // 1000 + 1 print ("Pass" if (3 == sqrt(9)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (4 == sqrt(16)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") print ("Pass" if (-1 == sqrt(-27)) else "Fail") print ("Pass" if (4567 == sqrt(20857489)) else "Fail") print ("Pass" if (9510 == sqrt(90440100)) else "Fail")
3e1f6e26f98aef8bc22d23faa57f8bb6c87c2b7c
yashms25/DataStructure-using-python
/Dequeue(Double-Ended-queue).py
1,134
4.125
4
class Deque: def __init__(self): self.queue= [] def addRear(self, elem): self.queue.append(elem) def addFront(self, elem): self.queue.insert(0, elem) def removeFront(self): if len(self.queue) == 0: print("Dequeue Is Empty") else: self.queue.pop(0) def removeRear(self): if len(self.queue) == 0: print("Dequeue Is Empty") else: self.queue.pop() def show(self): if len(self.queue) == 0: print("Dequeue Is Empty") else: print("Dequeue Contains:") print(self.queue) queue=Deque() while(True): print("""1. InsertRear 2. InsertFront 3. RemoveRear 4. RemoveFront 5. Show 6. Exit""") choice=input() if(choice=='1'): queue.addRear(int(input("Enter element to be insert:"))) elif(choice=='2'): queue.addFront(int(input("Enter element to be insert:"))) elif(choice=='3'): queue.removeRear() elif(choice=='4'): queue.removeFront() elif(choice=='5'): queue.show() elif(choice=='6'): break else: print("Invalid Input")
2d934f98de2d2915f873f133ca42ff2bafd0481e
KATO-Hiro/AtCoder
/ARC/arc051-arc100/arc052/a.py
213
3.65625
4
# -*- coding: utf-8 -*- def main(): s = input() result = '' for si in s: if si.isdigit(): result += si print(result) if __name__ == '__main__': main()
ab8f4a0bf797053a530019049ca438242a8eb38e
ngxtop/ngxtop
/ngxtop/utils.py
546
3.796875
4
import sys def choose_one(choices, prompt): for idx, choice in enumerate(choices): print(("%d. %s" % (idx + 1, choice))) selected = None if sys.version[0] == "3": raw_input = input while not selected or selected <= 0 or selected > len(choices): selected = input(prompt) try: selected = int(selected) except ValueError: selected = None return choices[selected - 1] def error_exit(msg, status=1): sys.stderr.write("Error: %s\n" % msg) sys.exit(status)
fad02c5d656c1a8e84be35d68e8852620795f424
park950414/python
/第二章/4triangle.py
414
3.5625
4
import turtle turtle.setup(1000,1000,200,200) turtle.pensize(2) a=1 for i in range (3): turtle.fd(200) turtle.seth(120*a) a=a+1 turtle.seth(-120) a=1 for i in range (3): turtle.fd(200) turtle.seth(-120+120*a) a=a+1 turtle.seth(0) turtle.penup() turtle.fd(200) turtle.pendown() turtle.seth(-120) a=1 for i in range (3): turtle.fd(200) turtle.seth(-120+120*a) a=a+1 turtle.done()
dc3a0eeb1e2d572f53b7f1dd2f76a201cc41dd0d
manoflogan/comscore-takehome
/datastore_importer.py
2,301
3.859375
4
"""Entry point for importer and datastore. It accepts arguments in two ways. 1. through the file argument. The invocation would be something like python importer_datastore.py datastore.csv 2. through standard input such as python importer_datastore.py < datastore.csv """ import csv import fileinput import logging from logging import config import os import constants config.fileConfig('logging.conf') logger = logging.getLogger('root') # Global variables FILE_HEADER: str = None DATASTORE_DIR: str = 'datastore' def store_data_to_file(): """The implementation does the following 1. Creates a directory output directory if it does not exist. 2. Reads the header if it not already parsed; if the header has not been parsed, then a file is created in write mode such a file name is a combination of "stb", "title,", and "date" and the header is written to a file 3. The contents of the datastore are written to a file; if the file already exists, then the contents are overwritten. """ # Step 1: Create a directory if it does not exist. datastore_directory = os.path.join(constants.OUTPUT_DIRECTORY, DATASTORE_DIR) os.makedirs(datastore_directory, exist_ok=True) is_header_parsed: bool = False for content in fileinput.input(): content = content.replace('\n', '') if not is_header_parsed: FILE_HEADER = content.split('|') is_header_parsed = True continue # Step # 2: Parse the header data_set = content.split('|') stb, title, _, date, _, _ = data_set # Creating the directory per stb, title, and date file_name = os.path.join( datastore_directory, constants.OUTPUT_FILE_NAME.format(stb.lower(), title.lower(), date)) with open(file_name, 'w', encoding='utf-8') as file_object: file_writer = csv.writer(file_object, delimiter='|', quoting=csv.QUOTE_ALL) if FILE_HEADER and is_header_parsed: file_writer.writerow(FILE_HEADER) is_header_parsed = True file_writer.writerow(data_set) if __name__ == '__main__': store_data_to_file()
0b52da3c563d6c19cb26850d35485f9932308f8b
nivipandey/python
/string/str3.py
84
3.65625
4
s1="good" s2=input("enter age ") s3=input("enter name") print(s1+" "+s2+" "+s3+" ")