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
aa4f3a2176da1d7817598d0dc676d956c9e188f1
HarryZhang0415/Coding100Days
/100Day_section1/Day36/Sol1.py
580
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: self.values = [] def search(node): if not node: return self.values.append(node.val) search(node.left) search(node.right) search(root) return sorted(self.values)[k-1]
4ccbbf9c8a20b541d8f4c40ebcbb790cbc446699
AJLightfoot/hello-world
/CH8-User-Album.py
485
3.984375
4
def make_album(artist_nm, album_nm): album_info = {'artist': artist_nm, 'album': album_nm} return album_info while True: print("\nPlease Enter an music artist and album title:") print("(you can quit by entering q at anytime)") artist_name = input("Artist: ") if artist_name == 'q': break album_name = input("Album Title: ") if album_name == 'q': break formatted_name = make_album(artist_name, album_name) print(formatted_name)
e4dfdb4eb260363477345cd5fa74d5d115edb1bc
acspike/PythonSamples
/states.py
1,721
3.984375
4
import random # http://geography.about.com/od/lists/a/statecapitals.htm text = '''Alabama - Montgomery Alaska - Juneau Arizona - Phoenix Arkansas - Little Rock California - Sacramento Colorado - Denver Connecticut - Hartford Delaware - Dover Florida - Tallahassee Georgia - Atlanta Hawaii - Honolulu Idaho - Boise Illinois - Springfield Indiana - Indianapolis Iowa - Des Moines Kansas - Topeka Kentucky - Frankfort Louisiana - Baton Rouge Maine - Augusta Maryland - Annapolis Massachusetts - Boston Michigan - Lansing Minnesota - St. Paul Mississippi - Jackson Missouri - Jefferson City Montana - Helena Nebraska - Lincoln Nevada - Carson City New Hampshire - Concord New Jersey - Trenton New Mexico - Santa Fe New York - Albany North Carolina - Raleigh North Dakota - Bismarck Ohio - Columbus Oklahoma - Oklahoma City Oregon - Salem Pennsylvania - Harrisburg Rhode Island - Providence South Carolina - Columbia South Dakota - Pierre Tennessee - Nashville Texas - Austin Utah - Salt Lake City Vermont - Montpelier Virginia - Richmond Washington - Olympia West Virginia - Charleston Wisconsin - Madison Wyoming - Cheyenne''' caps = {} for line in text.split("\n"): state, capital = line.split(" - ") caps[state] = capital states = caps.keys() random.shuffle(states) for state in states: print "What is the capital of %s?" % state correct = False for i in range(3): ans = raw_input() if ans == caps[state]: correct = True break else: print "Oops! :-(" if correct: print "Yay!" else: print "The capital of %s is %s." % (state, caps[state])
37a90364dc29fea31cfe39ec8f52776780d1ee63
gustavoem/abc-sysbio
/cudasim/relations.py
1,033
3.90625
4
import re def mathml_condition_parser(string): """ Replaces and and or with and_ and or_ in a string and returns the result. """ string = re.compile("and").sub("and_", string) string = re.compile("or").sub("or_", string) return string def eq(a, b): return a == b def neq(a, b): return a != b def gt(a, b): return a > b def lt(a, b): return a < b def geq(a, b): return a >= b def leq(a, b): return a <= b def and_(a, b): return bool(a) & bool(b) def or_(a, b): return bool(a) or bool(b) def piecewise(*args): """ Implements MathML piecewise function passed as args. N.B. piecewise functions have to be passed through MathMLConditionParser because they may contain and and or statements (which need to be made into and_ and or_ statements). """ result = None for i in range(1, len(args), 2): if args[i]: result = args[i - 1] break else: result = args[-1] return result
eacafbe23f2c628b712f7adc1c61d25fd2f9165f
MrGumba/Computer-Guesses-Number
/DatornGissar.py
5,453
3.921875
4
# coding: utf-8 import time import random ''' computerGuesses är funktionen som utför gissningarna och sökningen till talet. Där den gör detta genom att gissa på ett tal mellan intervallet och sedan veta om talet är midnre eller störe och sedan sätta intervallet mellan talet den gissade + 1 och det andra talet som beror på om svaret var mindre eller störe.''' def computerGuesses(lowest, higest, answer = None): correct = 1 guessCount = 0 # guessCount räknar hur många gånger den har gissat på ett tal för att visa det senare. while correct != 0: # Denna whole loop loopar tills programet har gissat rätt på talet där programet får värdet 0. guess = random.randint(lowest, higest) guessCount += 1 print('Jag gissar på att numret är',guess) if answer: # Program för att göra så att datorn kan köra koden genom att söka sig närmare och närmare nummret. if answer == guess: correct = 0 elif answer < guess: correct = -1 elif answer > guess: correct = 1 else: # Programmet för att användaren kan manuelt låta datorn gissa talet. correct = helpToGuess() if correct == 0: print('Yey! Jag gissade rätt och det tog mig bara', guessCount,'försök!') elif correct > 0: # Kollar om nästa tal är störe. print('-'*50) print('Störe du säger? Okej låt mig gissa igen..') if lowest < guess: # Ifall den nya gissningen är störe en den förra så ändras värdet. lowest = guess + 1 elif correct < 0: # kollar om nästa tal är mindre print('-'*50) print('Mindre du säger? Okej låt mig gissa igen..') if higest > guess: # Ifall den nya gissningen är mindre en den förra så ändras värdet. higest = guess - 1 ''' helpToGuess är en funktion som gör att användaren kan hjälpa datorn att gissa rätt på vilket tal du har tänkt på. Där användaren kan säga om det är rätt, eller om talet är större eller mindre. ''' def helpToGuess(): while True: try: print('Skriv 0 om det är korekt, 1 eller mer om det är större, och -1 eller mindre ifall det är mindre') correct = int(input('Svar (0, 1, -1): ')) return correct except ValueError: # Ifall användaren inte ger ett korekt värde ältså ett heltal så skickas denna felkod. print('Oops! du skrev inte in ett tal testa igen!') ''' Denna funktion tar hand om det mästa med interactivitet och när den körs kan användaren skriva in hur den vill att programmet ska köras.''' def interactive(): print('-'*50) while True: try: x = input("Ange sökintervall (ex '1-100'): ") x = x.replace(' ', '') # Tar bort ALLA mellan rum så även om användaren skriver 1 00 så blir det 100. x = x.split("-") # Tar bort - från ex 1-100 och delar up det i en lista av två värden. x.sort() # Soterar listan så att om användaren skriver 100-1 tar programmet det som 1-100. lowest = int(x[0]) higest = int(x[1]) break except (ValueError, IndexError): # Skickar denna felkod ifall användaren inte ger ut två heltal som värde. print("Oops.. Du skrev inte in ett heltal testa igen") computerGuesses(lowest, higest) playerInput = 'y' while playerInput == 'y': # While loop som frågar användaren om dom vill köra igen eller inte. playerInput = input("Får jag köra en gång till? ('y' för ja och 'n' för nej): ") playerInput = playerInput.strip() if playerInput == 'y' or playerInput == 'n': # Detta kollar om användaren skrev 'n' eller 'y'. if playerInput == 'y': print("Yey! Då kör vi igen!") find(lowest, higest) if playerInput == 'n': print("Det var synd..") else: # Ifall användaren inte angav 'n' eller 'y' så skickas denna felkod ut. print("Du angav inte 'y' eller 'n' försök igen..") ''' Test kod som kollar om programmet fungerar genom automatiskt köra genom programmet med 3 värden två för vilket intervall den ska gissa på och 1 för vad det korrekta gissningen är.''' def runTestCode(lowest, higest, answer): print('-'*50) print('Talet datorn ska gissa är',answer) print('Samt är intervallet',str(lowest)+'-'+str(higest)) print("Låt mig tänka", end='') for i in range(5): # Denna loop skapar punkter som gör att programmet syns ut som att den tänker. time.sleep(0.5) # Även uppfyler detta att användaren kan läsa vilket intervall och vad svaret var. print('.', end='') print() computerGuesses(lowest, higest, answer) interactive() # Kallar till interavtive så att användaren kan lägga in sina egna värden. ''' För att ändra värden i runTestCode så är lowest det minsta värdet datorn kan gissa och highest är största samt är answer vilket tal den ska försöka gissa på''' runTestCode(20, 300, 42) # Används för att kalla till runTestCode för att testa programet där
86ddeed678d13f354d86b098e73986477bc33ad3
ShreyasGangadhar/Python
/add.py
45
3.65625
4
a=30 b=5 print('''sum of a and b is''',a+b)
5f76276e941d5eabf7db1192923e9b196b834b32
bsuresh0212/Data-Science
/Python/23-09-2017/FILES/file.py
372
3.5625
4
''' read a file from ''' ''' data = open('text.txt','r') for line in data: print(line) data.close() ''' ''' write in a file ''' tar = open('new_file.txt','w') tar.write('Hey i m suresh ') tar.write('Python') tar.write('\n') tar.write('finally i got') tar.close() tar = open('new_file.txt','a') tar.write('\n') tar.write('I added the line') tar.close()
d4acc86fc7d7861d07d80420a92c224b5d85d147
mikiwang820/coding-practice
/class_practice_BankAccount.py
1,203
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 1 14:33:02 2020 @author: wangmeiqi """ #Python coed to create BankAccount class #with deposit() and withdraw() function #Reference https://www.geeksforgeeks.org/python-program-to-create-bankaccount-class-with-deposit-withdraw-function/ class BankAccount: def __init__(self): self.balance = 0 print("Welcome to the Deposit & Withdrawal Machine") def deposit(self): amount = float(input("Enter amount to be Deposited: ")) self.balance += amount print("Amount Deposited: ", amount) def withdraw(self): amount = float(input("Enter amount to be Deposited: ")) if amount > self.balance: print("Insufficient balance") else: self.balance -= amount print("You withdrew: ", amount) def display(self): print("\n New available balance:", self.balance) #drive code balance = BankAccount() balance.deposit() balance.withdraw() balance.display()
68587de01c8da9979281c0d2aab0570e9fe23ef3
kimjiwook0129/Coding-Interivew-Cheatsheet
/Data-Structures/Trees/BinaryTreeIteration.py
2,114
4.15625
4
from collections import deque # Same BinaryTree, but the print methods are implemented using iterations class BinaryTree: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def preOrderPrint(self): s = deque([self]) while s: curNode = s.pop() print(curNode.data, end = " ") if curNode.right: s.append(curNode.right) if curNode.left: s.append(curNode.left) def inOrderPrint(self): s = deque([]) while True: if self: s.append(self) self = self.left else: if len(s) == 0: break self = s.pop() print(self.data, end = " ") self = self.right def postOrderPrint(self): s1 = deque([self]) s2 = deque([]) while s1: curNode = s1.pop() s2.append(curNode) if curNode.left: s1.append(curNode.left) if curNode.right: s1.append(curNode.right) while s2: print(s2.pop().data, end = " ") def postOrderPrintOneStack(self): pass def levelOrderPrint(self): q = deque([]) q.append(self) while q: curNode = q.popleft() print(curNode.data, end = " ") if curNode.left: q.append(curNode.left) if curNode.right: q.append(curNode.right) if __name__ == "__main__": tree = BinaryTree(1, BinaryTree(2, BinaryTree(4)), \ BinaryTree(3, BinaryTree(5, None, BinaryTree(7)), BinaryTree(6, BinaryTree(8), BinaryTree(9)))) tree.preOrderPrint() # 1, 2, 4, 3, 5, 7, 6, 8, 9 print() tree.inOrderPrint() # 4, 2, 1, 5, 7, 3, 8, 6, 9 print() tree.postOrderPrint() # 4, 2, 7, 5, 8, 9, 6, 3, 1 print() # tree.postOrderPrintOneStack() # 4, 2, 7, 5, 8, 9, 6, 3, 1 # print() tree.levelOrderPrint() # 1, 2, 3, 4, 5, 6, 7, 8, 9 print()
3664c7d1578c74a9b03db6542250dae30e5dfbc0
oski89/AoC
/2017/day-09.py
1,407
4.125
4
with open('input/09.txt') as f: INPUT = f.read() # Function that deletes "!" and the character after def ignore(in_tuple): in_string = in_tuple[0] start = in_string.find('!') end = in_string.find('!') + 2 in_string = in_string[:start] + in_string[end:] return in_string, in_tuple[1] # Function that deletes garbage (characters inside "<>") and returns the number of removed characters def garbage(in_tuple): in_string = in_tuple[0] removed = 0 start = in_string.find('<') end = in_string.find('>') if start != -1 and end != -1: removed = (len(in_string[start:end - 1])) in_string = in_string[:start] + in_string[end + 1:] return in_string, in_tuple[1] + removed # Function that calculates the score of the groups def group_score(in_string): value = 0 score = 0 new_string = in_string.replace(',', '') for c in new_string: if c == '{': value += 1 score += value else: value -= 1 return score def main(): my_tuple = (INPUT, 0) removed = 0 while '!' in my_tuple[0]: my_tuple = ignore(my_tuple) while '<' in my_tuple[0]: my_tuple = garbage(my_tuple) score = group_score(my_tuple[0]) removed = my_tuple[1] print("Answer to Part 1:", score) print("Answer to Part 2:", removed) if __name__ == '__main__': main()
8504340b6287a84f16c851de8c13cd0a39078048
liviumihai/practicePython.org
/exercises_page1.py
5,055
4.28125
4
''' Exercise 1: Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Extras: Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python) Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button) ''' # import datetime so that we'll know the current year from datetime import datetime # this variable provides us the current year year = datetime.now().year # ask the user to type in his name and his age name = input("Type in your name:\n") age = input("How old are you?\n") age = int(age) # make the difference between 100 years and user's age, then make the sum to find out when the user will be 100 years old agediff = (100 - age) age100 = (year + agediff) # display the results print("Your name is ", name, "and you are", age, "years old.") print("You'll be 100 years old in", age100) ''' Exercise 2: Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. ''' num = input("Enter a number:\n") num = int(num) check = num % 4 check2 = num % 2 if check == 0: print("The number", num, "is even and a multiple of 4.") elif check2 == 0: print("The number", num, "is even and divides by 2, not by 4.") else: print("The number", num, "is odd.") ''' Exercise 3: Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5. Extras: Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list. Write this in one line of Python. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user. ''' a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [i for i in a if i <=5 ] # print(b) c = input("Type in a number:\n") c = int(c) d = [i for i in a if i < c] print(d) ''' Exercise 4: Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) ''' # ask user for input a = input("Type in a number: \n") a = int(a) # generate a list based on the user input # the a + 1 generates a higher number than a so we're sure we'll find the user's number in the list list_range = list(range(1, a +1)) # create an empty list to append the results divisor_list = [] # divide a to all the number in the list and if i in the list is a divisor of a, then append it to the newly created list for i in list_range: if a % i == 0: divisor_list.append(i) # output the result print(divisor_list) ''' Exercise 5: Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Extras: Randomly generate two lists to test this Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon) ''' # import random to use randrange import random # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] # generate 2 random list from 1 to 10 and up to 10 numbers. it will give us duplicates as well a = [random.randrange(1, 10, 1) for _ in range(10)] b = [random.randrange(1, 10, 1) for _ in range(10)] # print the lists so we can check the results print(a) print(b) # create a new list to append the numbers from both random generated lists c = [] # verify first the items in b and if they show in a, append them to list c. 'if not i in c' makes sure that we won't get duplicates in # our list for i in b: if i in a: if i not in c: c.append(i) # output the new list print(c) ''' Exercise 6: Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) ''' word = input("Type in a word: \n") x = word[:] y = word[::-1] if x == y: print("It's a palindrome") else: print("It's not a palindrome")
af68fdca1492d905abf142a5cb4d5640e68ffab7
ChuhanXu/LeetCode
/jiuzhang/Two pointer/Two pointer move face to face/TwoSum/twoSum3DatastructureDesign.py
2,246
3.71875
4
# https://www.jiuzhang.com/problem/two-sum-iii-data-structure-design/ # 设计实现一个TwoSum类,支持 add find操作 # add使用hash记录每一个元素的count # find for循环 hash 的key set,看是否value-key在hash列表中,并检查count是否为0 # 考虑添加的时候要不要有序加入 class TwoSum: def __init__(self): self.nums = [] self.count={} # 1.维护有序 直接插入法 O(n),通过不断交换来维护数组的有序性,比较前一个数是否比这个数大 # def add(self,number): # self.nums.append(number) # index = len(self.nums)-1 # while index>0 and self.nums[index-1]>self.nums[index]: # self.num[index-1],self.num[index]=self.num[index],self.num[index-1] # index-=1 # 2. 使用hash表存 def add(self,number): if number in self.count: self.count[number]+=1 else: self.count[number]=1 # 1.heap # 你以为他是sorted array,但是不是 java:priority queue,python:heapq # heap 其实是一个二叉树,但是存储的时候是一个数组,但是不是有序,只能知道最大最小的数是什么 # i*2 和 i*2+1 代表左右子树,没有办法在O(1)的时间找到次小数,只能再删除最小数后调整堆得到 # # 2.binary search 的插入是O(n)的 # 3.binary Search + linked list # linked list 插入时O(1)的,但前提是知道应该插在哪, # linked list 是离线数据结构不支持 binary search O(1) index access,只能从head开头一个个找到它 # 4.doubly linked list + hashtable # hashtable存的是key值 不是index # 5.treemap 维护的也不是一个array 红黑树 可以 log(n)的时间增删查改,用O(n)中序遍历输出array # 如果没有排序 find就会麻烦一点 # hash 有序O(n) def find(self,value): for num in self.count: # 为了防止target为10 但是数组里只有一个5 答案却给了(5,5)的情况 # if value - num in self.count and (value-num!=num or self.count[num]>1): return True return False
ffda9fc7ee5de8634598498816576ad7adb720be
McSerful/Scrabble_game_final
/main.py
2,575
3.78125
4
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] letters_to_points = {letter: point for letter, point in zip(letters, points)} letters_to_points[" "] = 0 def score_word(word): point_totall = 0 for letter in word: point_totall += letters_to_points.get(letter.upper(), 0) return point_totall player_to_words = { "player1": [""], "player2": [""], "player3": [""], } player_to_points = {} for player, words in player_to_words.items(): player_points = 0 for word in words: player_points += score_word(word) player_to_points[player] = player_points take_a_game = True def player_word(player, word): while word != "Stop": for players in player_to_words: if player in players: player_to_words[player].append(word) player_to_points[player] += score_word(word) if word == "Stop": break return game_is_on = True count = 0 while game_is_on == True: if count >= 3: game_is_on = False else: for players, words in player_to_words.items(): player_name = input("Who's turn?: ").lower() if player_name in player_to_words.keys(): word_new = input("Enter a word: ").lower() if word_new not in player_to_words.values(): player_to_words[player_name].append(word_new) player_to_points[player_name] += score_word(word_new) print(player_to_points) count += 1 print(count) elif word_new in player_to_words.values(): print("There is such a word already!") elif player_name == "stop": question = input("Are your sure? (Y/N) ").lower() if question == "y": game_is_on = False elif question == "n": continue else: print("There is no such a player!") break def winner(dict): winner_name = "" max_number = 0 for key, value in dict.items(): if dict[key] > max_number: max_number = dict[key] winner_name = str(key) elif dict[key] <= max_number: continue return "The winner is " + winner_name.upper() print(winner(player_to_points))
f66bb67555ef428ba2275362ff7c3295e3468c39
Bandit254/IntroToPython
/IntroToPython - Module 2/IntroToPython___Module_2.py
2,022
4.59375
5
#Introduction to functions #Some functions, like print, can take many parameters. #Other functions, like type, can only take one parameter my_type = type(2.2) print(my_type) #Create a function using the 'def' keyword, the function name, parentheses and semicolon #The actual body of the function is defined underneath the function name, indented 4x spaces #Ending the indentation will end the function body def say_hi(): print("Hello there!") print("Goodbye!") #call the function by simply typing the name and any input parameters: say_hi() def yell_it(): phrase="Well hello there" print(phrase.upper(),"!") yell_it() #Function parameters: def say_this(phrase): print(phrase) say_this("Hi!") #Default parameters: def nowSayThis(phrase="Good Night"): print(phrase) nowSayThis() nowSayThis("Goodnight Moon!") #Functions with return values def msg_double(phrase): double = phrase +" "+phrase return double msg_2x = msg_double("Hey y'all!") print(msg_2x) def half_value(value): return value/2 print(half_value(42)) #Multi-parameters: def make_schedule(period1, period2): schedule=("[1st] "+ period1.title() +", [2nd] "+ period2.title()) return schedule student_schedule=make_schedule("mathematics", "history") print("SCHEDULE: ", student_schedule) def format_info(name, age, school): return "Student: " + name+"\nAge: " +str(age)+"\nSchool: "+ school print(format_info("Tobias Ledford", 15, "Oak")) #Sequence #Objects must be defined before they are called, otherwise you get a name error birds_available = "crow robin parrot sandpiper hawk pigeon" def bird_availability(bird): return bird.title(),"available is",bird in birds_available bird = input("enter a bird to search: ").lower() print(bird_availability("Owl")) #Module Completion Exercise: def fishstore(fish_entry, price_entry): result = fish_entry.title()+ " costs $"+price_entry return result fish_entry = input("Enter a type of fish: ") price_entry = input("Enter the price of the fish: ") print(fishstore(fish_entry, price_entry))
2976c321a47391632875814f6933a475b5bd472e
logicals7/problems-solving-python
/Bittersweet occasion/task.py
231
3.5625
4
# finish the function def find_the_parent(child_): if issubclass(child_, Drinks): print('Drinks') elif issubclass(child_, Pastry): print('Pastry') elif issubclass(child_, Sweets): print('Sweets')
2d96411cc681604e9e5908108a4e6f42cf0cdbb3
jacob-create/Experimental-evo-bio-code
/Randombutton.py
527
4.15625
4
#This code generates a list of the whole numbers 1-20 and a random button which #causes a random number from that list to be printed and then removed from the list. #The button can be used until all 20 numbers have been picked import random from tkinter import * def randomize(): num = random.choice(lizt) print(num) lizt.remove(num) lizt = [] for number in range(1, 21): lizt.append(number) root = Tk() button = Button(root, text = 'randomize', command = randomize) button.pack() root.mainloop()
7742aa86b83131c15a82a0a714274d77657017d4
tuobashaoli/LearningPython
/reduce.py
452
3.71875
4
#reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数 #reduce把结果继续和序列的下一个元素做累积计算 #效果如下reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) def add(x,y): return x+y from functools import reduce print(reduce(add,[1,2,3,4,5,6,7,8,9,0])) #把序列[1, 3, 5, 7, 9]变换成整数13579 def fn(x,y): return x*10+y print(reduce(fn,[1,2,3,4,5]))
4806bebbb4759b0b7f85ce6c4b7f77d77dd78b68
annalieb/PythonWork-2018
/al_employeeEarnings.py
2,251
4.15625
4
#Anna Lieb #7/5/18 #Summer Python Work #al_employeeEarnings.py #used this website to learn more about the formatting in histogram(): #https://www.programiz.com/python-programming/methods/string/format#numbers EMPLOYEEMONTHLYSALARY = [5000, 10000, 6500, 3600, 2500, 1200, 5100, 7100, 5900, 7000, 7800, 3600, 18000, 8400, 5000, 9000, 4500, 9000, 7500, 3900, 8000, 3400, 6900, 4800, 2100, 6600, 11000, 3700, 8900, 20000, 2700, 3140, 8300, 3900, 3600, 5600, 6000, 6200, 2300, 7800, 5100, 4600, 4000, 2900, 3000, 5900, 3700, 9400, 9900, 25000, 8800, 3600, 4200, 2400, 3300, 6000, 3700, 3000, 3200, 8500, 14000, 5200, 4700, 2500, 2900, 7800, 8300, 31000, 4300, 6200, 5400, 8300, 7400, 5200, 6500, 8200, 4400, 9400, 8300, 2100, 3600, 4100, 6700, 8100, 3200, 2800, 8700, 6200] NUMOFRESPONSES = len(EMPLOYEEMONTHLYSALARY) # 390600 is the greatest salary. I found it by executing: print(max(yearlySalary)) in main(). def convertSalary(monthlySalary): #converts monthly salary to yearly salary with bonus yearlySalary = [] for x in range(NUMOFRESPONSES): yearlySalary.append((monthlySalary[x]*12)*1.05) return yearlySalary def countFrequencies(dataList): #organize the survey responses rankings = [0] * (40) for x in range(0, NUMOFRESPONSES): rankings[int(dataList[x]//10000)] += 1 return rankings def histogram(rankings): #output information to the user print ("Employee Annual Earnings Histogram: ") for x in range(10): print("{:>20}".format("$" + str(x*10000) + " - $" + str((x*10000)+9999)), "*" * rankings[x]) lowerTotal = 0 for y in range(10,15): lowerTotal += rankings[y] print("{:>20}".format("$100000 - $149999"), "*" * lowerTotal) upperTotal = 0 for z in range(15, 40): upperTotal += rankings[z] print("{:>20}".format("$150000 and over"), "*" * upperTotal) def main(): yearlySalary = convertSalary(EMPLOYEEMONTHLYSALARY) sumData = countFrequencies(yearlySalary) histogram(sumData) main()
1ef2bd95f22e0358937835907302ed38a68c17ff
Vishal97Singh/OnlineQuiz
/next.py
1,445
3.9375
4
from Tkinter import* top = Tk() a=["Q1)Python is a________","Q2) What is the output of print str * 2 if str = 'Hello World!'?","Q3) What is the output of print tinylist * 2 if tinylist = [123, 'john']?","Q4) Which of the following function convert an integer to octal string in python?","Q5) What is the output of L[2] if L = [1,2,3]?","Q6) Who developed python?","Q7) Suppose list1 is [2445,133,12454,123], what is max(list1) ?","Q8) Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?","Q9) Which of the following is a Python tuple?","Q10) What will be the output? if t=(1,2,4,3),t[1:3]=?"] b=["Structured language"," Hello World! * 2","[123, 'john'] * 2","dec(x)","error"," hello ",2445,"Error","1,3,3","1,2"] c=["object oriented","Hello World!Hello World!","[123, 'john', 123, 'john']","oct(x)","3"," [h, e, l, l, o ]",12454,25,"1,2,3","2,4"] d=["scripting language","Hello World!"," Error","hex(x)","1"," llo","Error","none","[1,1,3]","1,2,4"] e=["markup language","None of the above"," None of the above","unichar(x)","2","olleh ","123","2","1,1,2","2,4,3"] i=0 k=i l=Label(top, text=a[i],fg="red",font="50",bd=10).grid(row=0) r1=Radiobutton(top,text=b[i],variable=k,value=1,font="150").grid(row=2) r2=Radiobutton(top,text=c[i],variable=k,value=2,font="150").grid(row=3) r3=Radiobutton(top,text=d[i],variable=k,value=3,font="150").grid(row=4) r4=Radiobutton(top,text=e[i],variable=k,value=4,font="150").grid(row=5) top.mainloop()
aecfc4163aad8680623e14cb4d5196114430c548
pkoarmy/Learning-Python
/week3/season.py
902
4.40625
4
# https://github.com/pkoarmy/Learning-Python/blob/master/week1/indent1.py import random print("We are going to calculate season from given Month") print("We call Spring if the month between March and May") print("We call Jun - Aug as Summer") print("We call Sep - Nov as Fall") print("We call Dec - Feb as Winter") month = random.randint(1, 12) print("current month is ", month) print("So it is") # You remember this code what we learned on our class ''' if month == 1: print("January") elif month == 2: print("February") elif month == 3: print("March") ''' # please complete the Python code to print out what is the season from month # hint : you can use logical operator with if clause if month >= 3 and month <=5: print("Spring") elif month >= 6 and month <= 8: print("Summer") elif month >= 9 and month <= 11: print("Fall") elif month == 12 or month < 3: print("Winter")
47d5d9207f65b9a32810770a9bbe5d56dbdf76c8
gseeni/HottestDayCalculation
/HottestDay.py
2,163
3.609375
4
#!/usr/bin/env python # coding: utf-8 #Importing the Required classes import pyspark.sql.functions as f import pyspark.sql.types from pyspark.sql import Window from pyspark.sql import SparkSession #Creating Spark Session and Reads the csv files sc = SparkSession.builder.master("local").appName("WeatherTest").getOrCreate() df = sc.read.csv('C:\Govind\WeatherData\*.csv',header=True) #df.count() #Removing duplicate records from the input csv files df = df.dropDuplicates() df.count() #Converting the necessary columns to make ready for the calculatios and check df = df.withColumn("ObservationDate",df.ObservationDate.cast('date')) .withColumn("ScreenTemperature", df.ScreenTemperature.cast('float')) .withColumn("ObservationTime", df.ObservationTime.cast('int')) .withColumn("SignificantWeatherCode", df.SignificantWeatherCode.cast('int')) #Removing the records whose ScreenTemperature is -99 (outlier) and considering only sunny hours df = df.filter(("SignificantWeatherCode ==1") or ("ScreenTemperature != -99") ) df.count() #Dropping the columns which are not considered for the calculation df = df.drop("ForecastSiteCode",'ObservationTime','WindDirection','SiteName','Country', 'WindSpeed','WindGust','Visibility', 'Pressure','SignificantWeatherCode','Latitude', 'Longitude') #Grouping the data based on date and region to find out the average temperature for a day and write those records in parquet file windowSpec = Window.partitionBy("ObservationDate","Region") result = df.withColumn("AvgDayTemperature",f.avg(f.col("ScreenTemperature")).over(windowSpec)).drop("ScreenTemperature") result = result.distinct() result.write.parquet('C:\Govind\WeatherData\Grouped_weather_data',mode='overwrite') #Reading the converted parquet file and create a temporary view out of that pfile = sc.read.parquet('C:\Govind\WeatherData\Grouped_weather_data') pfile.createOrReplaceTempView("pfile") #Viewing the records based on the average temperature query = "select ObservationDate,Region,round(AvgDayTemperature,1) HighestTemperature from pfile order by AvgDayTemperature desc" data = sc.sql(query) data.show(truncate=False)
1053e5f700e1de2c057baecf1b5f55e965f67895
Horlawhumy-dev/csc_lab_problems
/readletters.py
330
3.90625
4
# Python Program that make special code from lines of file file = open('books.txt', 'r') # opening the file in read only mode Lines = file.readlines() # reading the lines of the file count = 0 # Strips the newline character for line in Lines: word = line.strip() print(f"{word} -> {word[0]}{len(word)}") count += 1
1705268d791de6c7f976b92ffe69a2a0a2be1914
connorodell/ModelSelection
/ModelSelection.py
3,385
4.15625
4
# Forward stepwise selection for best predictor subset selection import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split class ForwardSelection: '''Class for selecting the best predictor subset to train a linear model such and LinearRegression or LogisticRegression''' def __init__(self, pipe): self.pipe = pipe forward_results = None def plot_results(self, size=(10, 6)): fig, ax = plt.subplots(figsize=size) ax.plot([len(x) for x in self.forward_results[:, 0]], self.forward_results[:, 1]) plt.title('R^2 versus number of best predictors') plt.xlabel('Number of predictors in model') plt.ylabel('R^2') def bestfit(self, X, y, include=[], random_state=None): '''Class method that finds the best predictors using forward selection. User may specify predictors to include in all models via the optional include argument.''' # Split input into test and train sets x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state) # List to store best result for each number of predictors best_per_level = [] # Algorithm starts with no predictors my_predictors = [] + include # List of predictors that have not been chosen and remove any the user specifies for inclusion remaining_predictors = X.columns.tolist() for item in my_predictors: remaining_predictors.remove(item) def give_score(score_data): return score_data[1] # Find the total number of iterations in the forward selection algorithm (nth triangular number) total_iterations = len(remaining_predictors)*(len(remaining_predictors)+1)/2 print('The total number of iterations is {}.'.format(total_iterations)) # Forward stepwise algorithm current_iteration = 0 while len(remaining_predictors) > 0: testing_data = [] # results for current level for predictor in remaining_predictors: current_predictors = my_predictors + [predictor] self.pipe.fit(x_train[current_predictors], y_train) score = self.pipe.score(x_test[current_predictors], y_test) testing_data.append([current_predictors, score, predictor]) # Progress bar current_iteration += 1 progress = 100 * current_iteration / total_iterations print('Current progress: {:.2f}%'.format(progress), end='\r', flush=True) # Find the best predictors at current level and store result to list testing_data.sort(key=give_score) my_predictors.append(testing_data[-1][2]) best_per_level.append((testing_data[-1][0], testing_data[-1][1])) # Remove chosen predictor from list of remaining predictors remaining_predictors.remove(testing_data[-1][2]) print('Current progress: 100.00%') # Save results to class parameter self.forward_results = np.array(best_per_level) # Find the best overall model and print result best_per_level.sort(key=give_score) print(best_per_level[-1]) print('The best linear model found uses {} predictors.'.format(len(best_per_level[-1][0])))
879574e0890450544b05c478f9592db464c17f13
thill3-zz/Compute-Total-weekly-Pay
/Assignment4.6.py
652
4.0625
4
hours = input("How many hours did you work?") rate = input("What is your hourly rate?") bonus = input("What is your hourly bonus?") try: hours = float(hours) rate = float(rate) bonus = float(bonus) bonusPay = 0 except Exception as e: print("Invalid input. Rerun the program and input only integers") quit() def computepay(hrs, rt, bon): bonusPay = 0 regularHours = hrs if hrs > 40: regularHours = 40 bonusHours = hrs - 40 bonusPay = bonusHours*rt*bon regularPay = regularHours*rate return(regularPay + bonusPay) print("Pay", computepay(hours, rate, bonus))
e3203522a38066c7ba1f18240503ac85b9af11f1
lightengine/gamejam-demo
/lib/position.py
440
3.5625
4
class Position(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __sub__(self, pos): x = self.x - pos.x y = self.y - pos.y return Position(x, y) def __repr__(self): return '<Pos %d,%d>' % (self.x, self.y) def isWithin(self, region): return region.contains(self) def percentTo(self, pos, percent=0.5): diff = self - pos return Position(self.x - (diff.x*percent), self.y - (diff.y*percent))
929be39726ac8a569a1255a2d99cd656dc7a024a
ya1sec/Advent-of-Code-2020
/8/8.py
898
3.53125
4
fn = "input.txt" dat = [x for x in open(fn).read().split("\n")] dat.remove(dat[-1]) code = [] visited = {} # PART 1 for x in dat: operation, value = x.split() code.append((operation, int(value))) def run(code, visited, a=0, i=0): while i not in visited and i < len(code): visited[i] = a operation, value = code[i] if operation == "acc": a += value elif operation == "jmp": i += value - 1 i += 1 return a, i a, _ = run(code, visited) print(a) # PART 2 s = set(visited.keys()) for j in s: operation, value = code[j] # skip ops that would continue in loops if (operation == "nop" and (i := j + value) not in visited) or \ (operation == "jmp" and (i := j + 1) not in visited): a, i = run(code, visited, visited[j], i) if i >= len(code): print(a) break
2ae4f6a878b25a035d5a36e9b65b2c45e8c4e2e3
yash-sinha-850/Personal
/dfs_iterative.py
619
3.796875
4
class Node: def __init__(self,name): self.name=name self.adj_list=[] self.visited=False class depth_first_search: def dfs(self,startnode): stack=[] stack.append(startnode) startnode=True while stack: actualnode = stack[-1] stack.pop() print(actualnode.name) for i in actualnode.adj_list: if not i.visited: i.visited=True stack.append(i) n1=Node("A") n2=Node("C") n3=Node("B") n4=Node("D") n5=Node("E") n1.adj_list.append(n2) n1.adj_list.append(n3) n2.adj_list.append(n4) n3.adj_list.append(n5) dfs=depth_first_search() dfs.dfs(n1)
2c1000c5f5a043daf7977cba0f4135cbe707f8a8
LovepreetSingh-09/Machine_Learning_1
/Unsupervised.py
6,576
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 07:38:13 2019 @author: user """ # Unsupervised Learning import graphviz import mglearn import numpy as np import matplotlib.pyplot as plt import pandas as pd import os from IPython.display import display from sklearn.model_selection import train_test_split # Types :- # 1.) Unsupervised Transformations - representation of the data which might be easier for humans or other machine learning algorithms # 2.) Clustering - partition data into distinct groups of similar items # Preprocessing and Scaling :- mglearn.plots.plot_scaling() plt.show() # 1.) The StandardScaler in scikit-learn ensures that for each feature the mean is 0 and the variance is 1, bringing all features to the same magnitude. However, this scaling does not ensure any particular minimum and maximum values for the features. # 2.) The RobustScaler works similarly to the StandardScaler that it ensures statistical properties for each feature that guarantee that they are on the same scale. The RobustScaler uses the median and quartiles, instead of mean and variance. This makes the RobustScaler ignore data points that are very different from the rest (like measurement errors). These odd data points are also called outliers, and can lead to trouble for other scaling techniques # The median of a set of numbers is the number x such that half of the numbers are smaller than x and half of the numbers are larger than x. The lower quartile is the number x such that one-fourth of the numbers are smaller than x, and the upper quartile is the number x such that one-fourth of the numbers are larger than x. . # 3.) The MinMaxScaler, on the other hand, shifts the data such that all features are exactly between 0 and 1. For the two-dimensional dataset this means all of the data is contained within the rectangle created by the x-axis between 0 and 1 and the y-axis between 0 and 1. # 4.) The Normalizer does a very different kind of rescaling. It scales each data point such that the feature vector has a Euclidean length of 1. In other words, it projects a data point on the circle (or sphere, in the case of higher dimensions) with a radius of 1. This means every data point is scaled by a different number (by the inverse of its length). This normalization is often used when only the direction (or angle) of the data matters, not the length of the feature vector. # Data Transformtion :- # The most common motivations of transforming data are visualization, compressing the data, and finding a representation that is more informative for further processing. from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=1) print(X_train.shape) print(X_test.shape) from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaler.fit(X_train) # transform data X_train_scaled = scaler.transform(X_train) # print dataset properties before and after scaling print("transformed shape: {}".format(X_train_scaled.shape)) print("per-feature minimum before scaling:\n {}".format(X_train.min(axis=0))) print("per-feature maximum before scaling:\n {}".format(X_train.max(axis=0))) print("per-feature minimum after scaling:\n {}".format(X_train_scaled.min(axis=0))) print("per-feature maximum after scaling:\n {}".format(X_train_scaled.max(axis=0))) # transform test data X_test_scaled = scaler.transform(X_test) # transform method always subtracts the training set minimum and divides by the training set range, which might be different from the minimum and range for the test set. # print test data properties after scaling print("per-feature minimum after scaling:\n{}".format(X_test_scaled.min(axis=0))) print("per-feature maximum after scaling:\n{}".format(X_test_scaled.max(axis=0))) # Scaling Training and Test the same way from sklearn.datasets import make_blobs # make synthetic data X, _ = make_blobs(n_samples=50, centers=5, random_state=4, cluster_std=2) # split it into training and test sets X_train, X_test = train_test_split(X, random_state=5, test_size=.1) # plot the training and test sets fig, axes = plt.subplots(1, 3, figsize=(13, 4)) axes[0].scatter(X_train[:, 0], X_train[:, 1] ,c=mglearn.cm2(0), label="Training set", s=60) axes[0].scatter(X_test[:, 0], X_test[:, 1], marker='^',c=mglearn.cm2(1), label="Test set", s=60) axes[0].legend(loc='upper left') axes[0].set_title("Original Data") # scale the data using MinMaxScaler scaler = MinMaxScaler() scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) # visualize the properly scaled data axes[1].scatter(X_train_scaled[:, 0], X_train_scaled[:, 1] ,c=mglearn.cm2(0), label="Training set", s=60) axes[1].scatter(X_test_scaled[:, 0], X_test_scaled[:, 1], marker='^', c=mglearn.cm2(1), label="Test set", s=60) axes[1].set_title("Scaled Data") # rescale the test set separately # so test set min is 0 and test set max is 1 # DO NOT DO THIS! For illustration purposes only. test_scaler = MinMaxScaler() test_scaler.fit(X_test) X_test_scaled_badly = test_scaler.transform(X_test) # visualize wrongly scaled data axes[2].scatter(X_train_scaled[:, 0], X_train_scaled[:, 1] ,c=mglearn.cm2(0), label="training set", s=60) axes[2].scatter(X_test_scaled_badly[:, 0], X_test_scaled_badly[:, 1] ,marker='^', c=mglearn.cm2(1), label="test set", s=60) axes[2].set_title("Improperly Scaled Data") for ax in axes: ax.set_xlabel("Feature 0") ax.set_ylabel("Feature 1") fig.tight_layout() plt.show() # fit_transform Method :- from sklearn.preprocessing import StandardScaler scaler = StandardScaler() # calling fit and transform in sequence (using method chaining) X_scaled = scaler.fit(X_train).transform(X_train) # same result, but more efficient computation X_scaled_d = scaler.fit_transform(X_train) # Effects of Preprcessing:- from sklearn.svm import SVC X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target,random_state=0) svm = SVC(C=100) svm.fit(X_train, y_train) print("Test set accuracy: {:.2f}".format(svm.score(X_test, y_test))) # Test set accuracy: 0.63 # preprocessing using 0-1 scaling scaler = MinMaxScaler() scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) # learning an SVM on the scaled training data svm.fit(X_train_scaled, y_train) # scoring on the scaled test set print("Scaled test set accuracy: {:.2f}".format(svm.score(X_test_scaled, y_test))) # Scaled test set accuracy: 0.97
301a5c8ee7ebb9922cc7624d42d91f605c386262
Velu2498/codekata-array-python
/42.py
566
3.5625
4
""" Given 2 numbers N,X and an array of N elements, check if there exists any 2 numbers in the array with sum equal to X.If found print 'yes' otherwise print 'no' Input Size : N,X <= 100000 Sample Testcase : INPUT 4 4 2 2 0 0 OUTPUT yes """ N,X=map(int,input().split()) m=map(int, input().split()[:N]) m=list(m) count=0 for i in range(len(m)): for j in range(len(m)): if (i!=j): if (m[i]+m[j]==X): # print("yes") count+=1 break if(count!=0): print("yes") else: print("no")
e1a99c58a88c7d936ae3f5d7f525cce1466a06a1
Anavros/lang
/testing/python/result.py
847
3.546875
4
# file = open("myfile.txt", 'r') err stdin # file = default(open("myfile.txt", 'r'), sys.stdin) class Success: def __init__(self, value): self.result = value class Failure: def __init__(self): pass def force(result): """ Return the result if successful, else raise an exception. """ if type(result) is Success: return result.value elif type(result) is Failure: raise Exception() else: raise ValueError() def default(result, fallback): """ Return the value of the result if successful, else return the fallback. """ if type(result) is Success: return result.value elif type(result) is Failure: return fallback def read_file(path): try: return Success(open(path, 'r')) except IOError: return Failure()
a3068dbc3691372be15050bd44384a08fb8c2c09
shu-csas-changgar/assignment-chapter1-matthewjones447
/midterm-project-matthewjones447/Question 5.py
806
3.921875
4
# Write a function the displays the year, count and rank of all WHITE NON HISPANIC males given the name David. # Note: In 2012 the ethnicity is listed as WHITE NON HISP. Please take this into account in your code. (10 points) def five(year, ethnicity, rank, first_name): if ethnicity.startswith("WHITE NON HISP") and first_name == "David": print(year, count, rank) # ---------------------------------------------------------------------------------------------- inputfile = open("Popular_Baby_Names.csv", "r") zoeys = 0 for line in inputfile: my_list = line.split(",") year = my_list[0] gender = my_list[1] ethnicity = my_list[2] first_name = my_list[3] count = my_list[4] rank = my_list[5][-1] five(year, ethnicity, rank, first_name) inputfile.close()
f4da89fcbb3c3c431cc32b5fddd6648ed2dffa35
chao-ji/LeetCode
/python/string/lc58.py
1,151
3.546875
4
"""58. Length of Last Word Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: "Hello World" Output: 5 """ class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if not s: return 0 # `s` is non-empty from here on. # `h` will point to the first non space char, from the left h = len(s) - 1 while h >= 0: if s[h] != ' ': break h -= 1 # `l` will point to the first space char, from the left l = h while l >= 0: if s[l] == ' ': break l -= 1 # normally, the layout of the pointers `l` and `h` looks like # "_....._" # l h # `.` means non- # in case `s` contains all non-space chars # "......" # l h # l = -1 # or `s` contains all space chars # "______" # h # l # l = h = -1 return h - l
2a499608c62583eb9cdc1911d3157fddca69af0b
gruxic/Ping-Pong
/ball.py
788
3.640625
4
from turtle import Turtle import random class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.penup() self.goto(random.randint(-100,150),random.randint(-100,150)) self.x_move=10 self.y_move=10 self.move_speed=0.1 def move(self): new_y=self.ycor()+self.y_move new_x=self.xcor()+self.x_move self.goto(new_x,new_y) def bounce_y(self): self.y_move *= -1 def bounce_paddle(self): self.x_move *=-1 self.move_speed*=0.9 def restart(self): self.goto(random.randint(-100,150),random.randint(-100,150)) self.bounce_paddle() self.move_speed = 0.1
4eab02e7de2af7969bb83120945d4ad69df61ce3
orralacm/LeetCode
/Problem 27/problem_27.py
275
3.71875
4
nums = [0,1,2,2,3,0,4,2] val = 2 x = 0 while x < len(nums) : if (nums[x] == val) : nums.pop(x) nums.append("") print("if") else : x += 1 print("else") print(nums) print("end cycle") print(nums)
d0e17e7f3cf14b5cb48f6e9de3573e21aa15e0a8
JVN313/Rock-Paper-Scissors
/main.py
2,299
3.8125
4
import random from datetime import datetime # Game Variables playing = True player_wins = 0 computer_wins = 0 draws = 0 games_played = 0 error_count = 0 options = ["ROCK","PAPER","SCISSORS"] answer = options[random.randrange(0,3)] user_input = input("Type Rock, Paper, Scissors, or Q to quit the game: ").upper() # Game Functions def player_win(): global player_wins player_wins+=1 print("You Won!") def replay(): global answer,user_input answer = options[random.randrange(0,3)] user_input = input("To play again type Rock, Paper, Scissors, or Q to quit the game: ").upper() def score_board(): global score_entry score_board_add = open("RPSscoreboard.txt","a") score_entry = input("ENTER YOUR NAME TO BE PLACED ON THE LEADERBOARDS: ").upper() if score_entry == "Q" or score_entry == "QUIT": quit() score_board_add.write(f"\n{score_entry} {str(player_wins)}W/{str(computer_wins)}L/{str(draws)}D") score_board_add.close() score_board_show = open("RPSscoreboard.txt","r") print(score_board_show.read()) score_board_show.close() def log_error(): time = datetime.utcnow().strftime('%m/%d/%Y %H:%M') log_error_add = open("ErrorLog.txt", "a") log_error_add.write(f"\nUser {score_entry} Had {str(error_count)} Errors During Their Play {time}") log_error_add.close() # Game Loop while playing: if user_input == "Q" or user_input =="QUIT": playing = False elif user_input == options[1] and answer == options[0]: games_played+=1 player_win() replay() elif user_input == options[0] and answer == options[2]: games_played+=1 player_win() replay() elif user_input == options[2] and answer == options[1]: games_played+=1 player_win() replay() elif user_input not in options: error_count+=1 print("Invalid Input") replay() elif user_input==answer: games_played+=1 draws+=1 print("DRAW!") replay() else: games_played+=1 computer_wins+=1 print("Sorry You Lost :( ") replay() print(f"You Won {player_wins} Time(s), Lost {computer_wins} Time(s), And Had {draws} Draw(s)!") score_board() log_error() print("Thanks For Playing!")
f3fbd777fdd0bef133cf05de3940619f610143b1
mindprobesven/python-references
/Python References/Syntax Reference/magic_methods.py
2,105
4.28125
4
#!/usr/bin/env python3 """ ---------------------------------------------------------------------------------------------------------------- Magic Methods - Magic methods are most frequently used to define overloaded behaviours of predefined operators in Python ---------------------------------------------------------------------------------------------------------------- """ class Person: def __init__(self, first_name, last_name, salary): self.first_name = first_name self.last_name = last_name self.salary = salary # Overriding the __str__() method def __str__(self): return f"Name: {self.first_name} {self.last_name}\nSalary: {self.salary}" # Overloading the + operator def __add__(self, other_person): sum_salary = self.salary + other_person.salary return sum_salary if __name__ == "__main__": sven = Person(first_name='Sven', last_name='Kohn', salary=100000) barbara = Person(first_name='Barbara', last_name='Massari', salary=80000) # ------------------------------------------------------------------------------------------------------ # Overriding the __str__() method in the Person class can return a string representation of its object. Pure magic! print(sven) print(barbara) # Magic methods can also be called directly. This is not recommended though. print(Person.__str__(barbara)) # ------------------------------------------------------------------------------------------------------ # Overloading the + operator to add the salary values of two Person class instances. Again, magic! total_salary = sven + barbara # Magic methods can also be called directly. This is not recommended though. total_salary = sven.__add__(barbara) print(f"Total salary: {total_salary}") # ------------------------------------------------------------------------------------------------------ # Lists all magic methods inherited by a class print(dir(sven)) # Magic methods can also be called directly. This is not recommended though. print(sven.__dir__())
d599567f13b4607445797fb2d02b12448c938b43
kevbradwick/algorithms
/algorithms/euclid.py
404
3.8125
4
def algo(a: int, b: int) -> int: """ Euclid's algorithm for finding the greatest common divisor of two numbers. >>> algo(10, 15) 5 >>> algo(10, 20) 10 >>> algo(10, 0) 10 >>> algo(0, 10) 10 >>> algo(0, 0) 0 >>> algo(10, 10) 10 >>> algo(10, 1) 1 >>> algo(2740, 1760) 20 """ while b != 0: a, b = b, a % b return a
e4b61f3e977a0bdddf3dc86c081ada7094e59b9c
weady/python
/python.file_dir.py
3,395
4
4
文件读写使用with..as 方式 如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便 f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore') encoding 指定读取文件的编码 linecache,这个模块也可以解决大文件读取的问题,并且可以指定读取哪一行 面对百万行的大型数据使用with open 是没有问题的,但是这里面参数的不同也会导致不同的效率。经过测试发先参数为"rb"时的效率是"r"的6倍 linecache 用以实现高效读取大文件内容或者需要经常访问的文件,linecache先把文件一次性读入到缓存中,在以后访问文件的时候,就不必要再从硬盘读取 lines = linecache.getlines(filename) 得到行列表,然后进行遍历读取 line = linecache.getline(filename,linenum) 读取指定行 file() 函数用于创建一个 file 对象,它有一个别名叫 open() import cPickle as p 利用cPickle模块进行文件的存储读取 f = file(shoplistfile, 'w') p.dump(shoplist, f) f.close() dump数据到文件 f = file(shoplistfile) storedlist = p.load(f) print storedlist load 数据从文件 不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法 F.read([size]) #size为读取的长度,以byte为单位 F.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分 F.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。 F.write(str) #把str写到文件中,write()并不会在str后加上一个换行符 F.writelines(seq) #把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西 用w或a模式打开文件的话,如果文件不存在,那么就自动创建。用w模式打开一个已经存在的文件时,原有文件的内容会被清空,因为一开始文件的操作的标记是在文件的开头的,这时候进行写操作,无疑会把原有的内容给抹掉 用U模式打开文件,就是支持所有的换行模式 F.tell() #返回文件操作标记的当前位置,以文件的开头为原点 F.seek(offset[,whence]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。 r 只读 r+ 读写 w 写入,先删除源文件,在重新写入,如果文件没有则创建 w+ 读写,先删除源文件,在重新写入,如果文件没有则创建(可以写入写出) 利用yield 读取文件,避免文件导致的内存消耗 def read_file(fpath): BLOCK_SIZE = 1024 with open(fpath, 'rb') as f: while True: block = f.read(BLOCK_SIZE) if block: yield block else: return
1df5dc60465487a9cbc9dffc27c5e79ba3ac2fe8
cbeloni/python
/PyTestes/InstanciasTestes.py
804
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class A: a = 1 # atributo publico __b = 2 # atributo privado a class A class B(A): __c = 3 # atributo privado def __init__(self): print self.a print self.__c a = A() print isinstance(a, B) # ''Objeto a'' uma instncia da ''classe B''? Falso. a = B() # Instanca o ''objeto a'' na ''classe B'' e imprime os atributos da classe. print isinstance(a, B) # ''Objeto a'' uma instncia da ''classe B''?Verdadeiro. b = B() # Instanca o ''objeto b'' na ''classe B'' e imprime os atributos da classe. print isinstance(b, B) # ''Objeto b'' uma instncia da ''classe B''? Verdadeiro. b = A() # Instanca o ''objeto b'' na ''classe A''. print isinstance(b, A) # ''Objeto b'' uma instncia da ''classe A''? Verdadeiro.
5ffe1d324e575ffcf495f78b1662e95a447ee8ee
da-ferreira/uri-online-judge
/uri/2149.py
731
3.640625
4
while True: try: entrada = int(input()) if entrada in [1, 2]: print(entrada - 1) else: termo1 = 0 termo2 = 1 alterna = True for i in range(entrada - 2): if alterna: phillbonati = termo1 + termo2 termo1 = termo2 termo2 = phillbonati alterna = False else: phillbonati = termo1 * termo2 termo1 = termo2 termo2 = phillbonati alterna = True print(phillbonati) except EOFError: break
c16c13f1e993b1f949157eb810355ecc567fd251
muondu/datatypes
/password/generator.py
238
3.875
4
import random character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*:;" length = input("Enter password length: ") length = int(length) password = "" for nesh in range(length): password += random.choice(character) print(password)
79fa4fb5c5c42fdd0cbc8b82faae63a70fc722c9
yangzongwu/leetcode
/20200215Python-China/0118. Pascal's Triangle.py
688
3.8125
4
''' Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] ''' class Solution: def generate(self, numRows: int) -> List[List[int]]: if numRows==0: return [] if numRows==1: return [[1]] if numRows==2: return[[1],[1,1]] rep=[[1],[1,1]] prev=[1,1] for k in range(3,numRows+1): cur=[1] for k in range(len(prev)-1): cur.append(prev[k]+prev[k+1]) cur.append(1) prev=cur rep.append(cur) return rep
d0af2d69a39f1cab99ba594a5431dfd898d164cc
starcigi/MyProjectPythonLearn
/binhanshu.py
142
3.796875
4
def binhanshu(x): result = '' if x: result = binhanshu(x//2) return result + str(x%2) else: return result
725ce6d6e44c8d8eccbf4474f1587331c53b2735
modolee/algorithm-practice
/baekjoon/permutation/10974_STL.py
282
3.5
4
from sys import stdin import itertools if __name__ == '__main__': n = int(stdin.readline()) arr = list(range(1, n + 1)) all_per = list(itertools.permutations(arr)) for values in all_per: for val in values: print(val, end=' ') print('')
458b575e9ccddc5c720f80e7adebeefa80701f10
Sesdesoir/PythonPlay
/player.py
1,060
3.734375
4
from gameObject import GameObject #Player is going to be a sub class of GameObject. GameObject is like the parent #We want everything GameObject has PLUS some stuff exclusive to Player. #This is like when we did the vehicle/car/boat classes class Player(GameObject): #This creates the Player object def __init__(self, x, y, width, height, image_path, speed): #Super() is creating all the parent information with the parameters we passed in super().__init__(x, y, width, height, image_path) self.speed = speed def move (self, direction, max_height): # the and is important! We don't want to move off the screen, however we want to be allowed to move in other directions. if (self.y >= max_height-self.height and direction >0) or (self.y == 0 and direction<0): return #Up arrow key will be equivalent to -1 down arrow will be equivalent to 1 #This is because (0.0) is the top left corner. Meaning 0 is the top and max height of 600 is the bottom self.y += (direction * self.speed)
6951be258ff1afd30f32d82389dfb6efa8408f94
Flammifer/Cmath
/V/7.6c.py
838
3.5625
4
import matplotlib.pyplot as plt import numpy as np import MyMath as mm def F(x): return x[0]**2+x[1]**2+x[0]*x[1]+x[0]-x[1]+1 def min_lambda(lambda_, args): #функция для нахождения оптимального лямбда w = args[0] fastest_grad = mm.vec_mul(-1, args[1]) return mm.vec_prod(fastest_grad, mm.gradient(F, mm.vec_sum(w, mm.vec_mul(lambda_, fastest_grad)))) eps = 10**(-5) def fast_grad(func): flag1 = 1 w = [1, 1] while flag1: fastest_grad = mm.gradient(F, w) #первоначальное направление lambda_ = mm.bin_search(min_lambda, 0, 2, w, fastest_grad) if (mm.vec_norm(fastest_grad) < eps): return w w = mm.vec_sum(w, mm.vec_mul((-1)*lambda_ , fastest_grad)) print(fast_grad(F))
64d83e9383ebf22e38342a2fedcdd167c73ee6db
falble/mythinkpython2
/CAP7-Iteration/exercise&solutions/exercise_7_1.py
626
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 2 19:44:59 2019 @author: Utente """ #Chapter 7 - Iteration #Exercise 7.1 import math def mysqrt(a): x = a/5 while True: y = (x+ a/x) / 2 if y == x: return x x = y def test_square_root(): a = 1.0 print('a', repr(mysqrt(a)).rjust(6), repr(math.sqrt(a)).rjust(12), 'diff'.rjust(10)) print("- --------- ------------ ----") while a < 10.0: print(a, " ", mysqrt(a), " ", math.sqrt(a), " ", abs(mysqrt(a)-math.sqrt(a))) a += 1 test_square_root()
8752a38795e55dcfb59b7c776bb0c0d7e90b1f46
Apache0001/Curso-de-Python
/Repeticao-while2/ex066.py
216
3.84375
4
n = 0 totn = 0 soma = 0 while n != 999: soma = soma + n n = int(input('Digite um número: ')) if n == 999: break totn = totn + 1 print(f'total de numeros: {totn}') print(f'soma: {soma}')
595d26ff4470b19b198afeefbc6c5998e8f9ac8a
thatchloe/Data_structures-and-algorithms
/Unscramble Computer Science Problems/P0/Task3.py
2,713
4.1875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ #Part A area_code = [] for record in calls: number = record[0] if number[0] == '(': a_code = number[0:number.find(')')+1][:] if not a_code in area_code: area_code.append(a_code) elif number[0] in ['7','8','9']: mobile_code = number[0:number.find(' ')][:] if not mobile_code in area_code: area_code.append(mobile_code) elif number[0] == '140' : if not '140' in area_code: area_code.append('140') print("The numbers called by people in Bangalore have codes:") for code in sorted(area_code): print(code) #Part B count = 0 for record in calls: call_num = record[0] rec_num = record[1] if call_num.startswith('(') and rec_num.startswith('('): call_code = call_num[0:number.find(')')+1][:] rec_code = rec_num[0:number.find(')')+1][:] if call_code == rec_code: count += 1 print(f"{round(float(count/len(calls)), 2)*100} percent of calls from fixed lines in Bangalore are calls\nto other fixed lines in Bangalore")
b66a4c88f32e3b7c887adee6c9a27d987ad0a446
mcascallares/combinational
/main.py
840
3.578125
4
def combinations(elements, size): if len(elements) == size or size == 1: return elements ret = [] for i, item in enumerate(elements): for j in combinations(elements[i + 1:], size - 1): ret.append(item + j) return ret def variations(elements, size): ret = [] for i in combinations(elements, size): ret.extend(permutations(i)) return ret def permutations(elements): if len(elements) <= 1: return elements ret = [] for i, item in enumerate(elements): for j in permutations(elements[:i] + elements[i + 1:]): ret.append(item + j) return ret def main(): input = ["a", "b", "c", "d", "f"] print "Input {}:".format(input) print "Combinations:" print combinations(input, 3) print "Permutations:" print permutations(input) print "Variations:" print variations(input, 3) if __name__ == '__main__': main()
bff521c9cfbdb5da82ab83fffd694c468e77b0ba
yash147/Python_codes
/palindrome.py
317
4.15625
4
a=eval(input("Enter the number to palindrome : ")) reverse=0 temp=a while (temp > 0): reminder =temp % 10 reverse =(reverse * 10)+reminder temp=temp//10 print("reverse of a string is = %d" %reverse) if(a == reverse): print("Number is palindrome") else: print("Number is not palindrome")
46fe52d420028386e4145eca661b6dd691f10372
NonPersistentMind/Python
/Mathematical Statistics/9 Two-Sample Tests/TwoSampleTests.py
6,473
3.765625
4
import numpy as np from math import sqrt import scipy.stats as st import warnings import sys arr = np.array warn = warnings.warn def get_data_from_file(filename): """ Returns a python list of numpy arrays formed from the specified file. Example below will be converted to [np.array(67,80,48), np.array(24,56,42)] File is structured like this: 67 80 48 % 24 56 42 So every number is on a newline and different samples are divided by a '%' symbol that is also on a newline filename:string - a path to the file where all the numbers reside """ with open(filename, 'r') as file: data = [] current_sample = [] for line in file: if '%' in line: data.append(np.array(current_sample)) current_sample = [] else: current_sample.append(float(line)) data.append(np.array(current_sample)) return data def custom_formatwarning(msg, *args, **kwargs): # ignore everything except the message return 'WARNING: ' + str(msg) + '\n' warnings.formatwarning = custom_formatwarning def _define_basic_statistical_properties(first_sample, second_sample): return (first_sample_mean := first_sample.mean(), second_sample_mean := second_sample.mean(), S_x := first_sample.std(ddof=1), S_y := second_sample.std(ddof=1), n := len(first_sample), m := len(second_sample)) def _get_welchs_freedom_degrees(first_sample, second_sample): first_sample_mean, second_sample_mean, S_x, S_y, n,m = _define_basic_statistical_properties(first_sample, second_sample) theta = (S_x/S_y)**2 numerator = (theta + n/m)**2 denominator = theta**2/(n-1) + (n/m)**2 / (m-1) return round(numerator/denominator) def one_sample_test(data, supposed_mean, alpha=0.5): sample_mean = data.mean() sample_std = data.std(ddof=1) n = len(data) return (sample_mean-supposed_mean)/(sample_std/n**0.5) def two_sample_test(first_sample, second_sample, alpha=0.05, var_alpha=0.02): """ A method that provides hypothesis test on whether means of two samples are equal or not. Before testing, method executes an F_test on two variances to determine if they are equal. In case of very obvious inequality, this method displays a warning first_sample:np.array - the first collection of observations to test on means equality second_sample:np.array - the second collection of observations to test on means equality """ first_sample_mean = first_sample.mean() second_sample_mean = second_sample.mean() S_x = first_sample.std(ddof=1) S_y = second_sample.std(ddof=1) n = len(first_sample) m = len(second_sample) F = st.f F_df1 = n-1 F_df2 = m-1 t = st.t df = n+m-2 # An interval of not-rejection of variance equality hypothesis interval = (F.ppf(var_alpha/2, F_df1, F_df2), F.ppf(1-var_alpha/2, F_df1, F_df2)) different_variances = (F_sampled := (S_y/S_x)**2) <= interval[0] or F_sampled >= interval[1] if different_variances: warn(f'Acquired F_test interval is {interval}') warn(f'Samle variances ratio is {F_sampled}', category=UserWarning) warn( f'Variances cannot be assumed to be equal with {1-var_alpha} confidence level', category=UserWarning) df = _get_welchs_freedom_degrees(first_sample, second_sample) sum_of_variations = (n-1)*S_x**2 + (m-1)*S_y**2 pooled_std = sqrt(sum_of_variations/(n+m-2)) return t.ppf(alpha/2, df=df), (first_sample_mean-second_sample_mean) / (sqrt(1/n + 1/m) * pooled_std), t.ppf(1-alpha/2, df=df) def variance_ratio_confidence_interval(first_sample, second_sample, alpha=0.05): """ A method that returns (1-alpha) confidence interval for the ratio of two variances based on the F random variable. first_sample:np.array - the first collection of observations to test on means equality second_sample:np.array - the second collection of observations to test on means equality alpha:float - the desired confidence level """ first_sample_mean = first_sample.mean() second_sample_mean = second_sample.mean() S_x = first_sample.std(ddof=1) S_y = second_sample.std(ddof=1) n = len(first_sample) m = len(second_sample) F_df1 = n-1 F_df2 = m-1 F_ppf = lambda alpha: st.f.ppf(alpha, F_df1, F_df2) S_ratio_sqr = (S_x/S_y)**2 return S_ratio_sqr * F_ppf(alpha/2), S_ratio_sqr * F_ppf(1-alpha/2) def mean_difference_confidence_interval(first_sample,second_sample, alpha=0.05): """ A method that returns (1-alpha) confidence interval for the difference between two means based on the Student T random variable. This method assumes the variances are equal, so be carefull using in the wrong context first_sample:np.array - the first collection of observations to test on means equality second_sample:np.array - the second collection of observations to test on means equality alpha:float - the desired confidence level """ first_sample_mean, second_sample_mean, S_x, S_y, n,m = _define_basic_statistical_properties(first_sample, second_sample) df = n+m-2 t_ppf = lambda alpha: st.t.ppf(alpha, df=df) sum_of_variations = (n-1)*S_x**2 + (m-1)*S_y**2 S_pooled = sqrt(sum_of_variations/(n+m-2)) sample_mean_difference = first_sample_mean - second_sample_mean return t_ppf(alpha/2)*S_pooled*sqrt(1/n+1/m) - sample_mean_difference, t_ppf(1-alpha/2)*S_pooled*sqrt(1/n+1/m) - sample_mean_difference if __name__ == '__main__': if len(sys.argv) > 1: filename = sys.argv[1] file = open(filename, 'r') sample = 0 sample_one = [] sample_two = [] data = [sample_one, sample_two] for line in file: if '%' in line: sample = 1 continue data[sample].append(float(line)) sample_one = np.array(sample_one) sample_two = np.array(sample_two) else: sample_one = arr([24, 25, 28, 28, 28, 29, 29, 31, 31, 35, 35, 35]) sample_two = arr([21, 22, 24, 27, 27, 28, 29, 32, 32]) # print(two_sample_test(sample_one, sample_two, alpha=0.05, var_alpha = 0.1)) # print(mean_difference_confidence_interval(sample_one, sample_two, alpha=0.01)) print(get_data_from_file('another_file'))
93cf62985a4ca3bfae6630c74b56ac33da25d64c
Sebin0123/Pythonbasics
/DAY1/area_rect.py
107
3.796875
4
#Area of rectange l=int(input("Enter length")) b=int(input("Enter breadth")) area=l*b print("area is",area)
9b7ea467d59ba3f4ebd6457d092586f63e40d8d6
wisdonbond/opendreamtest
/solutions/wisdonbond/01.py
168
3.546875
4
input_data = 15 temp = '' if input_data % 3 == 0: temp = temp + 'Fizz' if input_data % 5 == 0: temp = temp + 'Buzz' print(input_data if not temp else temp)
1e6fdf0cb48b0694f74c940a674c9197fd9aa57d
sameersrinivas/AlgoAndDS
/Algorithms/sorting/MergeSort.py
1,364
3.953125
4
""" T(n) = 2 T(n/2) + n n: time spent on merging Time: O(n log n) : Merge n elements log n times Space: O(n + log n) = O(n) : log n for recursive call depth, n for temporary list n: number of elements to sort """ class MergeSort(): def merge_sort(self, nums): if not nums: return nums tmp = nums[:] self._merge_sort_helper(0, len(nums) - 1 ,nums, tmp) def _merge_sort_helper(self, low, high, nums, tmp): if low < high: mid = low + ((high - low) // 2) self._merge_sort_helper(low, mid, nums, tmp) self._merge_sort_helper(mid + 1, high, nums, tmp) self._merge(low, mid, high, nums, tmp) def _merge(self, low, mid, high, nums, tmp): i, j, k = low, mid + 1, low while i <= mid and j <= high: if nums[i] < nums[j]: tmp[k] = nums[i] i += 1 else: tmp[k] = nums[j] j += 1 k += 1 while i <= mid: tmp[k] = nums[i] i += 1 k += 1 while j <= high: tmp[k] = nums[j] j += 1 k += 1 for i in range(low, k): nums[i] = tmp[i] # sorts in-place nums = [6,4,1,2,8,5] obj = MergeSort() obj.merge_sort(nums) print(nums)
f2863b3270f49ceb290032917b9e6d52c369ee70
skinder/Algos
/PythonAlgos/Done/revers_str_2.py
1,043
3.921875
4
''' https://leetcode.com/problems/reverse-string-ii/ Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. Example: Input: s = "abcdefg", k = 2 Output: "bacdfeg" ''' class Solution: def reverseStr(self, s, k): return s[::-1] if k > len(s) else s[:k][::-1] + s[k:2*k]+self.reverseStr(s[2*k:], k) def reverseStr2(self, s, k): i, ans = 0, "" while (i < len(s)): if i + k >= len(s): ans += s[i:][::-1] elif i + 2 * k >= len(s): ans += s[i:i + k][::-1] + s[i + k:] else: ans += s[i:i + k][::-1] + s[i + k:i + 2 * k] i += 2 * k return ans a = Solution() print a.reverseStr("abcdefg", 2) print a.reverseStr2("abcdefg", 2)
9c307dcc6667aeae342ff0bd3c4ce3cefb0479f0
keisuke-osone/cedec_ai
/SampleAI.py
10,590
3.890625
4
# -*- coding: utf-8 -*- import copy import sys import random class Heroine: def __init__(self, enthusiasm): self.enthusiasm = enthusiasm self.revealedLove = [] self.myRealLove = 0 # 最初に熱狂度順にソート # sortedEnthusiasm = sorted(self.enthusiasm) def readLine(): return list(map(int, raw_input().split())) def getEstimation(_heroines, _numHeroines, enthusiasm, point, num): estimation = 0 # 期待値出力 # print(enthusiasm) # print(point) # print(num) # revealedLoveArray = [0] * for j in range(0, _numHeroines): value = 0 if j == num: value = int(_heroines[j].myRealLove) + point else: value = int(_heroines[j].myRealLove) # 最下位のとき if min(_heroines[j].revealedLove) >= value: minNum = _heroines[j].revealedLove.count(value) if minNum > 1: estimation = (estimation + (-1 * enthusiasm[j])) / minNum else: estimation = (estimation + (-1 * enthusiasm[j])) # 自分が一位のとき elif max(_heroines[j].revealedLove) <= value: maxNum = _heroines[j].revealedLove.count(value) # 追いつかれそうなときは追加したい if maxNum > 1: estimation = (estimation + enthusiasm[j]) / maxNum else: estimation = (estimation + enthusiasm[j]) # それ以外 else: pass # estimation += 0 # print estimation return estimation # 休日を考慮 def getEstimationWithHolidayDate(_heroines, _numHeroines, dated, enthusiasm, point, num): estimation = 0 estimationWithHolidayDate = 0 # print u"振込" + str(num) # print u"振込" + str(point) for j in range(0, _numHeroines): # print u"ヒロイン:" + str(j) value = 0 if j == num: value = int(_heroines[j].myRealLove) + point else: value = int(_heroines[j].myRealLove) # 休日考慮なし # 最下位のとき # print value # print min(_heroines[j].revealedLove) # print max(_heroines[j].revealedLove) if min(_heroines[j].revealedLove) >= value: minNum = _heroines[j].revealedLove.count(value) if minNum > 1: estimation = float(estimation + (-1 * enthusiasm[j])) / minNum else: estimation = float(estimation + (-1 * enthusiasm[j])) # print u"最下位" + float(estimation + (-1 * enthusiasm[j])) # 自分が一位のとき elif max(_heroines[j].revealedLove) <= value: maxNum = _heroines[j].revealedLove.count(value) # 追いつかれそうなときは追加したい if maxNum > 1: estimation = float(estimation + enthusiasm[j]) / maxNum else: estimation = float(estimation + enthusiasm[j]) # それ以外 else: pass # 休日考慮あり # 最下位のとき # print float(min(_heroines[j].revealedLove) + dated[j]) # print float(max(_heroines[j].revealedLove) + dated[j]) # estimationWithHolidayDate = 0.0 if float(min(_heroines[j].revealedLove)) + dated[j] >= value: minNum = _heroines[j].revealedLove.count(value) if minNum > 1: estimationWithHolidayDate += float((-1 * enthusiasm[j])) / minNum else: estimationWithHolidayDate += float((-1 * enthusiasm[j])) # print u"最下位" + str(-1 * enthusiasm[j]) # 自分が一位のとき elif float(max(_heroines[j].revealedLove)) + dated[j] <= value: maxNum = _heroines[j].revealedLove.count(value) # 追いつかれそうなときは追加したい if maxNum > 1: estimationWithHolidayDate += float(enthusiasm[j]) / maxNum else: estimationWithHolidayDate += float(enthusiasm[j]) # print u"首位" + str(enthusiasm[j]) # それ以外 else: pass # estimation += 0 # print u"累積" + str(estimationWithHolidayDate) # print u"休日なし" + str(estimation) # print u"休日あり" + str(estimationWithHolidayDate) return estimationWithHolidayDate print('READY') sys.stdout.flush() stepNum = 2 totalTurns, numPlayers, numHeroines = readLine() enthusiasm = readLine() heroines = [] cnt = 0 datedEstimation = [0] * numHeroines for i in range(numHeroines): heroines.append(Heroine(enthusiasm[i])) for t in range(totalTurns): # ターン数と平日、休日の入力 turn, day = raw_input().split() # ターンをintに変換 turn = int(turn) # 出力 output = [] # プレイヤーごとの好感度の配列 for i in range(numHeroines): heroines[i].revealedLove = readLine() realLove = readLine() # 自分への好感度の配列 for i in range(numHeroines): heroines[i].myRealLove = realLove[i] if day == 'W': dated = readLine() else: dated = [0] * numHeroines # デートの配列の配列 otherDated = copy.deepcopy(dated) for i in range(0, len(datedEstimation)): if len(output) == 2: for j in range(0, len(output)): if otherDated[output[j]] == 1: if otherDated.count(max(otherDated)) == numPlayers * 2: otherDated[output[j]] == 0.0 else: otherDated[output[j]] == 0.5 datedEstimation[i] += float(otherDated[i] * numPlayers * 2) / otherDated.count(max(otherDated)) # print "1の数" # print dated.count(max(dated)) # print "期待値" # print float(numPlayers * 2) / dated.count(max(dated)) command = [] out = heroines[0].revealedLove out.append(3) # 期待値 # トータルの期待値 estimate = 0 # ヒロインそれぞれの期待値配列 estimateArray = [0] * numHeroines length = 5 point = 1 if day == 'H': length = 2 point = 2 outputArray = [] outputEstimationArray = [] estimationMax = [] voteArray = [] # フリの回数 # num = length for cnt2 in range(0, length): # print cnt num = length - cnt2 # print num # 紐づいた振り込みかた maxEstimation = -100000 tmpArray = [] tmpArray = copy.deepcopy(heroines) # 投票する番号 vote = -100 # 期待値がマイナスの可能性もあるので maxVal = -10000 for k in range(0, numHeroines): # 期待値を計算 振り込む数をポイントにかけて期待値計算 # estimateArray[k] = getEstimation(tmpArray, numHeroines, enthusiasm, point * num, k) estimateArray[k] = getEstimationWithHolidayDate(tmpArray, numHeroines, datedEstimation, enthusiasm, point * num, k) # print estimateArray[k] # print k if estimateArray[k] > maxVal: maxVal = estimateArray[k] vote = k # print maxVal # print vote estimationMax.append(maxVal) voteArray.append(vote) estMax = -100000 finalVote = -100 for estNum in range(0,len(estimationMax)): # print estimationMax[estNum] if estimationMax[estNum] > estMax: maxVal = estimationMax[estNum] finalVote = voteArray[estNum] output = [finalVote] * num # print output for input in range(0, len(output)): tmpArray[output[input]].myRealLove += point length1 = length - len(output) for cnt1 in range(0, length1): # 紐づいた振り込みかた maxEstimation = -100000 # if (turn > 0): # tmpArray = heroines # for var in range(1, length): # 投票する番号 vote = -100 # 期待値がマイナスの可能性もあるので maxVal = -10000 for k in range(0, numHeroines): # 期待値を計算 振り込む数をポイントにかけて期待値計算 # estimateArray[k] = getEstimation(tmpArray, numHeroines, enthusiasm, point * length1, k) estimateArray[k] = getEstimationWithHolidayDate(tmpArray, numHeroines, datedEstimation, enthusiasm, point * length1, k) if estimateArray[k] > maxVal: maxVal = estimateArray[k] vote = k estimationMax.append(maxVal) voteArray.append(vote) estMax = -100000 finalVote = -100 for estNum in range(0,len(estimationMax)): # print estimationMax[estNum] if estimationMax[estNum] >= estMax: estMax = estimationMax[estNum] finalVote = voteArray[estNum] # print maxVal out2 = [finalVote] * cnt2 for l in range(0, len(out2)): output.append(out2[l]) outputEstimationArray.append(estMax) outputArray.append(output) # 戦略の決定 # print outputArray # print outputEstimationArray finalOutput = [] maxOutputEstimation = -100000 for m in range(0, len(outputEstimationArray)): if outputEstimationArray[m] > maxOutputEstimation: maxOutputEstimation = outputEstimationArray[m] finalOutput = outputArray[m] output = finalOutput # 配列の長さが足りない場合は適当に足す while len(output) <= length: output.append(random.randrange(numHeroines)) for i in range({'W': 5, 'H': 2}[day]): # ここでロジック # 自分のプレイヤーナンバーは? # 期待値計算したい マイナスとプラス # 最も期待値が高いところに # command.append(str(random.randrange(numHeroines))) # ここでヒロインのIDを指定して出力 # heroineNum = cnt % 8 # cnt = cnt + 1 # print output if (turn > 1): command.append(str(output[i])) else: command.append(str(random.randrange(numHeroines))) print(' '.join(command)) sys.stdout.flush()
a10b09c53c098c89193c4285b833244d0538dd48
samisaf/Learning-Programming
/Learning-Python/TowersOfHanoi.py
296
3.8125
4
cycle = 0 def move_towers(num, fro, to, spare): global cycle cycle = cycle + 1 if num != 0: move_towers(num - 1, fro, spare, to) print "Move tower:", num, "from:", fro, "to:", to move_towers(num - 1, spare, to, fro) move_towers(4, 'A', 'B', 'C') print cycle
f4ea91bf9a11840a5947707ee36e53ac15028cca
Miguel-Duke/introToPython_generalProjects
/project6_Functions.py
5,573
4.5
4
''' PROJECT 6 Functions You are to write a program which: *Defines the following 5 functions: whoamI() This function prints out your name and PRINTS OUT any programming course you have taken prior to this course. sign(number) This function accepts one parameter, a number, and PRINTS OUT a message telling if the number is zero, positive or negative. printOdd(number) This function accepts one parameter, a number, and PRINTS OUT all odd values from 1 thru this number. Keep in mind that an odd value is a value that has a remainder of 1 when divided by 2. right_Most(number) This function accepts one parameter, a whole number, and RETURNS the right most digit in the number howmanyZeros(number) This function accepts one parameter, a whole number, and RETURNS the count of zero's in the number It would be a good idea to write a simple main to test your functions individually and make sure they work before you continue on. * follows the function definition with main process statements which: 1.) calls the 'whoamI' function to that the program begins by outputting uses information 2.) prompt the user for a positive int and stores it If the user does not enter a valid number, reprompt. Continue this until a valid value has been entered. 3.) present the user with 4 choices: -output the sign of the value - printout all odd values up to the number -output the rightmost digit in the value -output the number of zeros in the value 4.) Carry out the user’s choice. Be sure to call one of the functions that you have defined to do this. If you wish you may put the main statements in a loop which repeats until the user chooses to exit. This will make testing easier. ''' def whoamI(): #Introductory statement print('Michael Schwartz') print('I have not taken any other programming courses!') return def sign(number): if number == 0: print('The number is 0') elif number < 0: print('The number is negetive!') else: print('The number is positive!') return def printOdd(number): #Simply starts at one and increases the value by 2 until the threshold is met. numberCount = 1 while numberCount <= number: print(numberCount) numberCount += 2 return def right_Most(number): #We can get the last (right most) digit by indexing -1 from the string version of the number. numString = str(number) rightNum = numString[-1] return rightNum def howmanyZeros(number): #Here we can turn the number into a string to find its length numString = str(number) #After we have the length we can compare the next value in sequence to 0 zeroCount = 0 # If the value is equal to zero we add it to the count! for i in range(len(numString)): if 0 == int(numString[i]): zeroCount += 1 return zeroCount def mainMenu(): print('Please select an option:') print('1) Output the sign of a value.') print('2) Print out all odd values up to the value.') print('3) Output the right-most digit in the value.') print('4) Output the number of zeros in the value.') print('5) Exit the program.') # ---- MAIN PROGRAM ---- programRunning = True while programRunning == True: #This while statement keeps the program running until the user chooses to quit. whoamI() #Introduces the programmer. menuSelection = True #This statement makes sure the user is prompted for an operation as long as the program continues to run. userNum_1 = int(input('Please provide a positive integer:')) while userNum_1 <= 0: #Here we make sure that the user provided a valid integer. userNum_1 = int(input('Please provide a number larger than 0:')) mainMenu() while menuSelection == True: #At this step we can now ask the user what operation they wish to pursue. userChoice = int(input('Please choose an operation:')) if 0 < userChoice < 4: if userChoice == 1: sign(userNum_1) menuSelection = False #Each if statement ends in this 'sentinel value' elif userChoice == 2: printOdd(userNum_1) menuSelection = False elif userChoice == 3: num_Right = right_Most(userNum_1) print(num_Right, 'is the right-most number in', userNum_1) menuSelection = False else: numZeros = howmanyZeros(userNum_1) #We have an if statement tree here to provide a print statement that sounds proper grammatically if numZeros > 1: print('There are', numZeros, 'zeroes in', userNum_1) menuSelection = False elif numZeros == 1: print('There is', numZeros, 'zero in', userNum_1) menuSelection = False elif numZeros == 0: print('There are no zeroes in', userNum_1) menuSelection = False else: continue #Sends us back to the 'menuSelection' while statement in the event that invald input is recieved. elif userChoice == 5: #Quits the program print('Thankyou and goodbye!') menuSelection = False programRunning = False else: continue
c0c9822c4c2da4554106f7ae871200d9c65307a2
ysei/project-euler
/pr018.py
2,254
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) """ input_str = """\ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23""" def instr2lst(instr): """convert input string to num list""" lst = [map(int,l.split(' ')) for l in instr.split('\n')] return lst def routes_sub(lst): """ subroutine of route. ex) [[0]] -> [[0,0],[0,1]] [[0,0], [0,1]] -> [[0, 0, 0], [0, 1, 1], [0, 0, 1], [0, 1, 2]] """ return [l + [l[-1]] for l in lst] + [l + [l[-1]+1] for l in lst] def routes(depth): """create route patterns for binary tree.""" return reduce(lambda lst, val: routes_sub(lst), range(depth-1), [[0]]) def route_value(tree, route): """value sum at route""" return sum([tree[depth][idx] for depth, idx in zip(range(len(route)), route)]) def main(instr): """main function""" lst = instr2lst(instr) # convert input string to list of int lists. depth = len(lst) max_value = max(map(lambda l: route_value(lst, l), routes(depth))) print max_value if __name__ == "__main__": main(input_str)
09019c8c2bfadd70d65bb660a0d5dd99d7fccb4f
RobertHan96/CodeUP_BASIC100_Algorithm
/1068.py
337
3.953125
4
''' 숫자 한개를 입력 받아서 점수에 해당하는 등급 출력하기 90 ~ 100 : A 70 ~ 89 : B 40 ~ 69 : C 0 ~ 39 : D ''' def calc(): a = int(input()) if a >= 90: print('A') elif 70 <= a <= 89: print('B') elif 40 <= a <= 69: print('C') else: print('D') calc()
91821f5413a9e3e7b6fc0289fd1bca98ccdf4520
scyther211/C4E29
/Session 2/hw/3_print_1.py
91
3.65625
4
X = input("Name here bitch: ") print("Hello",end='') print(" My name is ",end='') print(X)
ed102efb4140f7891ed8e33cdbbcbf0eb313ecdf
hendy3/A-beautiful-code-in-Python
/Teil_21_Türme_von_Hanoi.py
210
3.8125
4
def hanoi(anzahl, von, temp, ziel): if anzahl > 0: hanoi(anzahl - 1, von, ziel, temp) print(f'Scheibe {anzahl} von {von} nach {ziel}') hanoi(anzahl - 1, temp, von, ziel) hanoi(3, 'A', 'B', 'C')
1758027caae8127566922e4897649f69bb4d45b7
Gabrielly1234/Python_WebI
/ exercícios senquenciais/questao8.py
307
3.828125
4
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. # Calcule e mostre o total do seu salário no referido mês. print("Horas trabalhadas: ") horas=float(input()) print("Valor da hora:") val=float(input()) salarioh= horas*val print("salário:",salarioh)
4769bf06771ad731216e40dbb1c75b49dba3efa6
MohamedHmini/M2SI-COLLECTIVE-WORK
/COMPLEMENTS_ALGORITHMIQUES/TP/TP1/Moad_Charhbili/Ex10_TD1.py
2,425
3.53125
4
def main(): l=-1 while l!=0: l=int(input("1)Skis avec chaussures :\n 2)Skis sans chaussures \n 3)les batons : 3 euros par jour et 18 euros en forfait semaine \n 0)Exit")) if l==1: c = int(input("1)a la Journee :\n 2)Forfait semaine \n 0)Retour")) if c==1: b = int(input("Combiens des jours ?")) p = int(input("1)Adulte : 15 :\n 2)Enfant : 10 \n 0)Retour")) if p==1: print("Vous devez payer ", b*15," Euros") l = 0 if p==2: print("Vous devez payer ", b*10," Euros") l = 0 if c==2: b = int(input("Combiens des semaines ?")) p = int(input("1)Adulte : 90 :\n 2)Enfant : 60 \n 0)Retour")) if p==1: print("Vous devez payer ", b*90," Euros") l=0 if p==2: print("Vous devez payer ", b*60," Euros") l = 0 if l==2: c = int(input("1)a la Journee :\n 2)Forfait semaine \n 0)Retour")) if c==1: b = int(input("Combiens des jours ?")) p = int(input("1)Adulte : 10 \n 2)Enfant : 8 \n 0)Retour")) if p==1: print("Vous devez payer ", b*10," Euros") l = 0 if p==2: print("Vous devez payer ", b*8," Euros") l = 0 if c==2: b = int(input("Combiens des semaines ?")) p = int(input("1)Adulte : 60 \n 2)Enfant : 48 \n 0)Retour")) if p==1: print("Vous devez payer ", b*60," Euros") l = 0 if p==2: print("Vous devez payer ", b*48," Euros") l = 0 if l==3: p = int(input("1)par jour \n 2)Forfait Semaine\n 0)Retour")) if p==1: b=int(input("Combiens des jours ?")) print("Vous devez payez : ",b*3) l = 0 if p==2: b = int(input("Combiens des semaines ?")) print("Vous devez payez : ", b * 18) l = 0 if __name__=="__main__": main()
9eb26c98ee508d911c80b814bcc04ce376316e9c
AmbystomaMexicanum/pcc2e-exerc
/src/ch_04/e_4_2.py
187
3.9375
4
animals = ['dog', 'cat', 'hamster', 'kiwi', 'Ambystoma mexicanum'] for animal in animals: print(f"A(n) {animal} is a very cute animal.") print(f"All these animals are so cute!")
7b02ba7cf3dcb6ae7855f1d6cf6ba326c689dae0
tothefullest08/TIL_algorithm
/2019_Q3_Q4/프로그래머스/Level 1/레벨1-2.py
207
3.625
4
def solution(x): str_x = str(x) my_sum = 0 for i in str_x : my_sum += int(i) answer = False if not x % my_sum: answer = True return answer print(solution(11))
f5e0e08036817e8e9ff846d5ff1377c44de57128
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/7_loops_for-while/7.3.frequent scenarios/13.py
621
3.921875
4
""" На вход программе подается натуральное число n, а затем n различных натуральных чисел, каждое на отдельной строке. Напишите программу, которая выводит наибольшее и второе наибольшее число последовательности. """ n = int(input()) max_total = 0 total = 0 for _ in range(n): num = int(input()) if num >= max_total: total = max_total max_total = num elif num > total: total = num print(max_total) print(total)
1a6542e8a847b22143eb494632276ac2c2285ac8
junwanghust/PythonCrashCourse-Exercises
/3/name_list_3_1.py
299
3.984375
4
# 将一些朋友的姓名存储在一个列表中,并将其命名为names。依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来。 names = ['kat', 'lily', 'jack', 'peter', 'bob'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4])
f2fd092c2e0dc6aa84a741a619f3ec2ed19f861b
vicchu/leetcode_101
/数据结构/6-树/树.py
10,604
3.828125
4
#%% class TreeNode: def __init__(self, val=0, left=None, right=None) -> None: self.val = val self.left = left self.right = right class Tree: def __init__(self) -> None: self.root = None def add(self, item): node = TreeNode(item) if self.root is None: self.root = node else: q = [self.root] while q: point = q.pop(0) if point.left is None: point.left = node return if point.right is None: point.right = node return else: q.append(point.left) q.append(point.right) def travel(self, root: TreeNode): if root is None: return [] arr = [] q = [] q.append(root) while q: point = q.pop(0) arr.append(point.val) if point.left: q.append(point.left) if point.right: q.append(point.right) return arr #%% def tree_test(): tree = Tree() arr = [1, 2, 3, 4, 5] for val in arr: tree.add(val) print(tree.travel(tree.root)) tree_test() # %% def max_depth(root: TreeNode) -> int: if root is None: return 0 l_high = max_depth(root.left) r_high = max_depth(root.right) deep = max(l_high, r_high) + 1 return deep # %% def max_depth_test(): tree = Tree() arr = [1, 2, 3, 4, 5] for val in arr: tree.add(val) res = max_depth(tree.root) print(res) max_depth_test() # %% [markdown] # 110. 平衡二叉树 # https://leetcode-cn.com/problems/balanced-binary-tree/ def is_balanced(root: TreeNode) -> bool: def height(root) -> int: if not root: return 0 l_height = height(root.left) r_height = height(root.right) if l_height == -1 or r_height == -1 or abs(l_height, r_height) > 1: return -1 return 1 + max(l_height, r_height) return height(root) >= 0 # %% [markdown] # 543. 二叉树的直径 # https://leetcode-cn.com/problems/diameter-of-binary-tree/ #%% def diameter_of_binary_tree(root: TreeNode) -> int: maxtemp = 1 def dfs(node: TreeNode): if not node: return 0 L = dfs(node.left) R = dfs(node.right) nonlocal maxtemp maxtemp = max(L + R, maxtemp) return max(L, R) + 1 dfs(root) return maxtemp #%% def diameter_of_binary_tree_test(): tree = Tree() arr = [1, 2, 3, 4, 5] for val in arr: tree.add(val) result = diameter_of_binary_tree(tree.root) print(result) diameter_of_binary_tree_test() # %% [markdown] # 437. 路径总和 III # https://leetcode-cn.com/problems/path-sum-iii/ #%% def path_sum(root: TreeNode, sum: int) -> int: if not root: return 0 def dfs(node: TreeNode, sum: int): if not node: return 0 if node.val is None: node.val = 0 sum -= node.val count = 1 if sum == 0 else 0 count += dfs(node.left, sum) count += dfs(node.right, sum) return count return dfs(root, sum) + path_sum(root.left, sum) + path_sum(root.right, sum) #%% def path_sum_test(): tree = Tree() root = [10, 5, -3, 3, 2, None, 11, 3, -2, None, 1] for val in root: tree.add(val) targetSum = 8 result = path_sum(tree.root, targetSum) print(result) path_sum_test() # %% [markdown] # 101. 对称二叉树 # https://leetcode-cn.com/problems/symmetric-tree/ #%% def is_symmetric(root: TreeNode): def check(p: TreeNode, q: TreeNode): if p is None and q is None: return True if p is None or q is None: return False return (p.val is q.val) and check(p.left, q.right) and check(p.right, q.left) return check(root, root) #%% def is_symmetric_test(): tree = Tree() root = [1, 2, 2, 3, 4, 4, 3] for val in root: tree.add(val) result = is_symmetric(tree.root) print(result) is_symmetric_test() # %% [markdown] # 1110. 删点成林 # https://leetcode-cn.com/problems/delete-nodes-and-return-forest/ #%% def delete_nodes(root: TreeNode, to_delete: list[int]) -> list[TreeNode]: if not root: return None mapper = set(to_delete) ans = [] if root.val in mapper else [root] def dfs(node, parent, direction): if not node: return dfs(node.left, node, "left") dfs(node.right, node, "right") if node.val in mapper: if node.left: ans.append(node.left) if node.right: ans.append(node.right) if direction == "left": parent.left = None if direction == "right": parent.right = None dfs(root, None, None) return ans #%% def delete_nodes_test(): tree = Tree() arr = [1, 2, 3, 4, 5, 6, 7] for val in arr: tree.add(val) to_delete = [3, 5] result = delete_nodes(tree.root, to_delete) for item in result: print(tree.travel(item)) delete_nodes_test() # %% [markdown] # 637. 二叉树的层平均值 # https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/ #%% def average_of_levels(root: TreeNode): totals = [] counts = [] def dfs(node, depth): if node is None or node.val is None: return # 递归下一次第一个元素 if depth >= len(totals): totals.append(node.val) counts.append(1) # 递归下一次非第一个元素 else: totals[depth] += node.val counts[depth] += 1 dfs(node.left, depth + 1) dfs(node.right, depth + 1) dfs(root, 0) return [total / count for total, count in zip(totals, counts)] #%% def average_of_levels_test(): tree = Tree() arr = [3, 9, 20, None, None, 15, 7] for val in arr: tree.add(val) result = average_of_levels(tree.root) print(result) average_of_levels_test() # %% [markdown] # 105. 从前序与中序遍历序列构造二叉树 # https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ #%% def build_tree(pre_order: list[int], in_order: list[int]) -> TreeNode: if not pre_order or not in_order: return None root = TreeNode(pre_order[0]) idx = in_order.index(pre_order[0]) root.left = build_tree(pre_order[1 : 1 + idx], in_order[:idx]) root.right = build_tree(pre_order[1 + idx :], in_order[idx + 1 :]) return root #%% def build_tree_test(): pre_order = [3, 9, 20, 15, 7] in_order = [9, 3, 15, 20, 7] tree = Tree() result = build_tree(pre_order, in_order) print(tree.travel(result)) build_tree_test() # %% [markdown] # 144. 二叉树的前序遍历 # https://leetcode-cn.com/problems/binary-tree-preorder-traversal/ #%% def preorder_traversal(root: TreeNode) -> list[int]: def preorder(root: TreeNode): if not root: return res.append(root.val) preorder(root.left) preorder(root.right) res = list() preorder(root) return res #%% def preorder_traversal_test(): tree = Tree() arr = [1, 2, 3, 4, 5, 6, 7] for val in arr: tree.add(val) result = preorder_traversal(tree.root) print(result) preorder_traversal_test() # TBD # %% [markdown] # 99. 恢复二叉搜索树 # https://leetcode-cn.com/problems/recover-binary-search-tree/ # steps: # 1. 中序遍历,生成数组 # 2. 遍历结果,找出可能错误得交换点 # 3. 如果错误得交换点不为空,交换 #%% def recover_tree(root: TreeNode): # 中序遍历二叉树,将遍历结果保存到列表中 node = [] def dfs(root): if root == None: return dfs(root.left) node.append(root) dfs(root.right) dfs(root) x, y = None, None pre = node[0] # 循环遍历,找到错误交换的x,y for i in range(1, len(node)): if pre.val > node[i].val: y = node[i] # 记录第一个出现的交换值 if not x: x = pre pre = node[i] # 将找到的x和y进行交换 if x and y: x.val, y.val = y.val, x.val #%% def recover_tree_test(): tree = Tree() arr = [7, 2, 6, 1, 3, 5, 4] for val in arr: tree.add(val) recover_tree(tree.root) print(tree.travel(tree.root)) recover_tree_test() # %% [markdown] # 669. 修剪二叉搜索树 # https://leetcode-cn.com/problems/trim-a-binary-search-tree/ #%% def trim_BST(root, L, R) -> TreeNode: def trim(node): if not node or node.val is None: return None elif node.val > R: return trim(node.left) elif node.val < L: return trim(node.right) else: node.left = trim(node.left) node.right = trim(node.right) return node return trim(root) #%% def trim_BST_test(): tree = Tree() arr = [3, 0, 4, None, 2, None, None, None, None, 1, None] for val in arr: tree.add(val) result = trim_BST(tree.root, 1, 3) print(tree.travel(result)) trim_BST_test() # %% [markdown] # 208. 实现 Trie (前缀树) # https://leetcode-cn.com/problems/implement-trie-prefix-tree/ #%% class Trie: def __init__(self): self.children = [None] * 26 self.isEnd = False def __searchPrefix(self, prefix: str) -> "Trie": node = self for ch in prefix: ch = ord(ch) - ord("a") if not node.children[ch]: return None node = node.children[ch] return node def insert(self, word: str) -> None: node = self for ch in word: ch = ord(ch) - ord("a") if not node.children[ch]: node.children[ch] = Trie() node = node.children[ch] node.isEnd = True def search(self, word: str) -> bool: node = self.__searchPrefix(word) return node is not None and node.isEnd def startsWith(self, prefix: str) -> bool: return self.__searchPrefix(prefix) is not None #%% def trie_test(): trie = Trie() trie.insert("apple") r1 = trie.search("apple") r2 = trie.search("app") r3 = trie.startsWith("app") trie.insert("app") r4 = trie.search("app") print(r1, r2, r3, r4) trie_test() # %%
797ec2be8f9a66fed8a91bbe3c1413e1ca37e555
Wolffoner/7541-Algoritmos-y-Programacion-II
/Clases/11-Menu-C-Python/menu.py
1,363
3.625
4
contador=0 class Juego: def __init__(self): self.contador = 0 class Comando: def __init__(self, nombre, doc, funcion): self.nombre=nombre self.documentacion=doc self.ejecutar=funcion def mostrar_documentacion(self): print("Esta es mi documentacion") print(self.documentacion) print("Ya se crearon las clases Juego y Comando") class Menu: def __init__(self): self.nombre = "" self.comandos = {} def agregar_comando(self, comando): self.comandos[comando.nombre] = comando def ejecutar_comandos(self, linea): if linea in self.comandos: comando = self.comandos[linea] comando.ejecutar("molesto") else: print('No te entendi') def incrementar(argumento): print('Incremento el contador ', argumento) global contador contador += 1 def decrementar(): print('Decremento el contador') global contador contador -= 1 def mostrar(): print('Contador: ', contador) menu = Menu() menu.agregar_comando(Comando('I', 'Incrementar el contador', incrementar)) menu.agregar_comando(Comando('D', 'Decrementar el contador', decrementar)) menu.agregar_comando(Comando('P', 'Mostrar el contador', mostrar)) linea="" while(linea != "quit"): linea = input('> ') menu.ejecutar_comandos(linea)
8a0266c185f4e4775aab7a0c4d44e75b8368022b
yoovraj/deeplearning
/Machine Learning A-Z/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/cnn_network.py
1,758
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 14 14:47:36 2017 @author: yoovrajshinde """ # Part 1 - Building the CNN #importing keras libraries from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # initialize CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Convolution2D(filters=32, kernel_size=(3,3), data_format="channels_last", input_shape=(64,64,3), activation='relu')) # Stem 2 - Pooling classifier.add(MaxPooling2D(pool_size=(2,2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full Connection classifier.add(Dense(units=128, activation='relu')) classifier.add(Dense(units=1, activation='sigmoid')) classifier.summary() # Compiling CNN classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Part 2 - Fitting the CNN to image from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary') test_set = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary') classifier.fit_generator( training_set, steps_per_epoch=8000, epochs=25, validation_data=test_set, validation_steps=2000)
23e9e3949977bff5ae76f92be4212e23b0aa60af
taesookim0412/Python-Algorithms
/2020_/06/LeetCodeJuneChallenge/04E_ReverseString.py
369
3.75
4
from typing import List #28.48% faster runtime class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ n = len(s) - 1 for i in range(len(s)//2): s[i], s[n-i] = s[n-i], s[i] print(s) print(Solution().reverseString(["h","e","l","l","o"]))
b4209da298c976726250a5032a6c2ff6109a6ee5
SilveryM/studypython
/first_stage/practice/practice_98.py
441
3.875
4
#从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。 ''' #!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == ' __main__ ' fp = open ( ' test.txt ' , ' w ' ) string = raw_input ( ' please input a string: \n ' ) string = string . upper ( ) fp . write ( string ) fp = open ( ' test.txt ' , ' r ' ) print fp . read ( ) fp . close ( ) '''
f025aba9c5f0812d3610b1fa0922d5ce49a0bb56
StephenRaymond/COMPETITIVE-PROGRAMMING
/Beginner/CountNumericChar.py
83
3.515625
4
n=input() count=0 for x in n: if x.isnumeric(): count+=1 print(count)
8a6e6d3c7c9a7ecd3c56efd32d3bf9b4ce31ae49
Rohitha92/Python
/Sorting/MergeSort.py
812
4.0625
4
#Merge sort -> recursive sort def merge_sort(arr): if len(arr)>1: mid = len(arr)//2 #integer. not float left_half = arr[:mid] right_half = arr[mid:] #divide into single units merge_sort(left_half) merge_sort(right_half) i=0 #left_half index j=0 #right_half index k=0 # arr index #sorting and merging while(i<len(left_half) and j<len(right_half)): if(left_half[i]< right_half[j]): arr[k] = left_half[i] i=i+1 else: arr[k]= right_half[j] j=j+1 k=k+1 while(i<len(left_half)): arr[k] = left_half[i] i=i+1 k=k+1 while(j<len(right_half)): arr[k] = right_half[j] j=j+1 k= k+1 return arr a =[10,2,4,44,23,-2,8,12] print(merge_sort(a))
0f8923f61c8098f13a32d913e0fd587042c0f373
funktor/stokastik
/LeetCode/RecoverBST.py
2,327
3.765625
4
# 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 swap(self, node1, node2): if node1 is not None and node2 is not None: temp = node1.val node1.val = node2.val node2.val = temp def get_min_max(self, root): has_defect, last_defect = 0, (None, None) if root.left is not None: min_left, max_left, has_defect_left, last_defect_left = self.get_min_max(root.left) else: min_left, max_left, has_defect_left, last_defect_left = None, None, 0, (None, None) if root.right is not None: min_right, max_right, has_defect_right, last_defect_right = self.get_min_max(root.right) else: min_right, max_right, has_defect_right, last_defect_right = None, None, 0, (None, None) if max_left is not None and max_left.val > root.val: last_defect_left = (root, max_left) has_defect_left = 1 has_defect, last_defect = 1, last_defect_left if min_right is not None and min_right.val < root.val: last_defect_right = (root, min_right) has_defect_right = 1 has_defect, last_defect = 1, last_defect_right if has_defect_left == 1 and has_defect_right == 1: self.swap(last_defect_left[1], last_defect_right[1]) has_defect, last_defect = 0, (None, None) elif has_defect_left == 1: has_defect, last_defect = 1, last_defect_left elif has_defect_right == 1: has_defect, last_defect = 1, last_defect_right a = root if min_left is not None and a.val > min_left.val: a = min_left if min_right is not None and a.val > min_right.val: a = min_right b = root if max_left is not None and b.val < max_left.val: b = max_left if max_right is not None and b.val < max_right.val: b = max_right return a, b, has_defect, last_defect def recoverTree(self, root): a, b, has_defect, last_defect = self.get_min_max(root) if has_defect == 1: self.swap(last_defect[0], last_defect[1])
9530ceb7cd4e1998e84df184bdbb514fd6378be5
beginstudy/python_newstudy
/pets.py
130
3.609375
4
pets = ['猫','狗','蛇','龟','狗','狗','狗','狗',] print(pets) while '狗' in pets: pets.remove('狗') print(pets)
28e782eb90caaf77d1feba8decc389f9372b71f8
ucsb-cs8-f17/cs8-f17-lecture-code
/lec12/ic04.py
2,624
4
4
import pytest def maskedPassword(pw): ''' takes one parameter `pw` and returns a string consisting of the first three characters contained in the variable `pw` followed by 'x's instead of the remaining characters in `pw`. The length of the returned value should be the same as the length of the parameter passed in. If the length of `pw` is less than 3 return `pw` without any modification (YOU MAY ASSUME `pw` is of type `str`) ''' if len(pw)<=3: return pw result1 = pw[0:3] # Trying to get the first three letters result2 = '' for i in range((len(pw)-3)): result2= result2.lower() result2 = result2 +'x'# Trying to generate N 'x's return result1+result2 def test_maskedPassword_0(): assert(maskedPassword("hello") =="helxx" ) def test_maskedPassword_1(): assert(maskedPassword("hi") == "hi" ) def test_maskedPassword_2(): assert(maskedPassword("password123") == "pasxxxxxxxx") def test_maskedPassword_3(): assert(maskedPassword("hie") == "hie" ) def isValidPassword(pw): ''' takes a parameter `pw` and returns True if the variable `pw` is of type `str` and is a valid **password**, according to the following rules: it must consist of at least 8 characters, include one of the special characters `*` or `#` and terminate with a numeric digit (`0`-`9`) ''' return True def minOfTwoLists(alist, blist): ''' takes two lists as parameters: `alist` and `blist`. The functions returns a new list where each element in the new list is the minimum of the corresponding elements in `alist` and `blist`. The function should raise a `ValueError` exception with an appropriate message, if either `alist` or `blist` is not a list or if either of them contains anything other than numbers (either int or float) or if they are not of the same length ''' if type(alist)!=list: raise ValueError("first parameter is not a list") if type(blist)!=list: raise ValueError("second parameter is not a list") if len(alist)!=len(blist): raise ValueError("length of lists are not equal") result=[] for i in range(len(alist)): if not (type(alist[i])==int or type(alist[i])==float): #alist[i] is not a number raise ValueError("alist has a non-numeric element) if alist[i]<blist[i]: result.append(alist[i]) else: result.append(blist[i]) #blah blah blah return result def test_minOfTwoLists_0(): assert(minOfTwoLists([1, 3, 5], [20, 7, 2.5])==pytest.approx([1,3,2.5])) def test_minOfTwoLists_1(): assert(minOfTwoLists([1, 30, 5], [20, 7, 2.5])==pytest.approx([1,7,2.5]))
b33256a4995aacddb4ec5a8bd5296b22b0bf602e
Samk208/Udacity-Data-Analyst-Python
/Lesson_3_data_structures_loops/nearest_squares.py
851
4.40625
4
# Implement the nearest_square function. The function takes an integer argument limit, and returns the largest square # number that is less than limit. A square number is the product of an integer multiplied by itself, for example 36 # is a square number because it equals 6*6. # There's more than one way to write this code, but I suggest you use a while loop! def nearest_square(limit): i = 1 square_number = 0 while square_number < limit: square_number = i ** 2 i += 1 if i ** 2 >= limit: break return square_number # Here is a test case you can copy to test your code. Feel free to write additional tests too! test1 = nearest_square(40) print("expected result: 36, actual result: {}".format(test1)) test2 = nearest_square(200) print("expected result: 196 actual result: {}".format(test2))
64bfca61954360e923e808e1141c6514ba45cd94
zzgkly/Mytest
/Python/Stu.py
744
4.0625
4
name = ["jidao" ,"jirui" , "ji" , "xdd" , "rui"] print("这是原来的列表:") print(name) print("-"*50 + "\n") print("这是append操作的列表:") name.append("jidao") print(name) print("-"*50 + "\n") print("这是insert操作的列表") name.insert(0 , "jidao") print(name) print("-"*50 + "\n") print("这是del操作的列表") del(name[0]) print(name) print("-"*50 + "\n") print("这是remove操作的列表") name.remove("jidao") print(name) print("-"*50 + "\n") print("这是pop操作的列表") name.pop(1) print(name) print("-"*50 + "\n") print("这是sort操作的列表") name.sort(reverse = False) print("降序排序:" + str(name)) name.sort(reverse = True) print("升序排序:" + str(name)) print("-"*50 + "\n")
b8ceabe1af9f24f1acb694641f32f61c05ca34a6
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/dice_simulation.py
2,603
4.53125
5
# In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function that simulates rolling # a pair of six-sided dice. Your function will not take any parameters. It will return the total that was rolled on # two dice as its only result. # Write a main program that uses your function to simulate rolling two six-sided dice 1,000 times. As your program runs, # it should count the number of times that each total occurs. Then it should display a table that summarizes this data. # Express the frequency for each total as a percentage of the total number of rolls. Your program should also display # the percentage expected by probability theory for each total. Sample output is shown below from random import randint def dice_simulation(): # Create a blank dictionary my_dict = {} # Fill the dictionary with the possible total as keys for i in range(2, 13): my_dict.update({str(i): 0}) # Initialize variables to count the occurrences of each total v_2, v_3, v_4, v_5, v_6, v_7, v_8, v_9, v_10, v_11, v_12 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 # Simulate 2 dices rolling for i in range(1000): dice1 = randint(1, 6) dice2 = randint(1, 6) # Increase each variable according to the total obtained if dice1 + dice2 == 2: v_2 += 1 if dice1 + dice2 == 3: v_3 += 1 if dice1 + dice2 == 4: v_4 += 1 if dice1 + dice2 == 5: v_5 += 1 if dice1 + dice2 == 6: v_6 += 1 if dice1 + dice2 == 7: v_7 += 1 if dice1 + dice2 == 8: v_8 += 1 if dice1 + dice2 == 9: v_9 += 1 if dice1 + dice2 == 10: v_10 += 1 if dice1 + dice2 == 11: v_11 += 1 if dice1 + dice2 == 12: v_12 += 1 # Filling the dictionary with a list as value my_dict.update({"2": [v_2 / 1000 * 100, 2.78]}) my_dict.update({"3": [v_3 / 1000 * 100, 5.56]}) my_dict.update({"4": [v_4 / 1000 * 100, 8.33]}) my_dict.update({"5": [v_5 / 1000 * 100, 11.11]}) my_dict.update({"6": [v_6 / 1000 * 100, 13.89]}) my_dict.update({"7": [v_7 / 1000 * 100, 16.67]}) my_dict.update({"8": [v_8 / 1000 * 100, 13.89]}) my_dict.update({"9": [v_9 / 1000 * 100, 11.11]}) my_dict.update({"10": [v_10 / 1000 * 100, 8.33]}) my_dict.update({"11": [v_11 / 1000 * 100, 5.56]}) my_dict.update({"12": [v_12 / 1000 * 100, 2.78]}) # Print the table print(f"Total\tSimulated\tExpected") print(f"\t\tPercent\t\tPercent") for k, v in my_dict.items(): print(f"{k}\t\t{format(v[0], '.2f')}\t\t{v[1]}") if __name__ == '__main__': dice_simulation()
168abd8544f28641d70fa975ef208cf064d69658
RobinRojowiec/log-linear-sentiment-classifier
/tokenizer.py
2,077
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import nltk from nltk import word_tokenize from nltk.stem.porter import PorterStemmer nltk.download('punkt') class Tokenizer: def __init__(self, stop_word_file): """set of stop word tokens to filter""" self.stopwords = set() # pattern matches all word characters [a-zA-Z_] self.word_pattern = re.compile('^\w+$') # loads the stopwords by line from a file self.load_stopwords(stop_word_file) self.stemmer = PorterStemmer() def create_bow_from_file(self, file_path): with open(file_path, encoding='utf-8', mode='r') as f: tokens = word_tokenize(f.read()) return self.create_bag_of_words(tokens) def create_bow_per_token(self, text): tokens = word_tokenize(text) bow_per_token: [] = [] for token in tokens: bow_per_token.append([token, self.create_bag_of_words([token])]) return bow_per_token def create_bag_of_words(self, tokens, lowercase=True, stem=True): """Reads the content of a file, tokenize it and collects all types except those filtered by the filter method""" bag_of_words = [] for token in tokens: filtered_token = self.filter(token, stem, lowercase) if filtered_token is not None: bag_of_words.append(filtered_token) return bag_of_words def load_stopwords(self, file): """loads all stopwords into a set""" with open(file) as f: for row in f: self.stopwords.add(row.replace("\n", "").lower()) def filter(self, token, stem=True, lowercase=True): """filters all stopwords and characters that are not relevant and returns the token""" if token.lower() not in self.stopwords and self.word_pattern.match(token): if stem: token = self.stemmer.stem(token) if lowercase: return token.lower() return token else: return None
45b97a3c321aed11c8edf69d1f0325ab3a8d33e3
GreedM/test
/spell.py
373
3.828125
4
def spell(n): if n==1: return "one" elif n==2: return "two" elif n==3: return "three" elif n==4: return "four" elif n==5: return "five" else: return f"not implemented: spell({n:d})" if __name__ == "__main__": s = input("Enter number: ") i = int(s) print(i, "is written:", spell(int(s)))
2ac05670cd25c3505d5575692354cc1963ce5038
AmenehForouz/leetcode-1
/python/problem-0804.py
1,748
3.734375
4
""" Problem 804 - Unique Morse Code Words International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word. Return the number of different transformations among all words we have. """ from typing import List class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: unique_reps = set() letters = { "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--..", } for word in words: morse_string = "" for letter in word: morse_string += letters[letter] unique_reps.add(morse_string) return len(unique_reps) if __name__ == "__main__": words = ["gin", "zen", "gig", "msg"] print(Solution().uniqueMorseRepresentations(words)) # Should return 2
a0864602b7d294a8c642b009388c1d9f364bc502
rajtyagi2718/tic-tac-toe
/tree.py
2,302
3.578125
4
from transposition import Table from board import Board class Tree: """Game state tree stored as dict map from board hashes to utility values. Root of complete game state tree is empty board. Each action during game step produces child board. Root has nine children. [X _ _] [_ X _] [_ _ X] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [X _ _] [_ X _] [_ _ X] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [_ _ _] [X _ _] [_ X _] [_ _ X] Leaves are terminal boards. Tree stores boards by hash function on board array. Board array equates transpositions (boards with same state but different paths). Hash function equates symmetric boards. This leave three children of root. [X _ _] [_ X _] [_ _ _] [_ _ _] [_ _ _] [_ X _] [_ _ _] [_ _ _] [_ _ _] Tree maps boards to utility values. Given parent board, afterstate values are utility values of child boards. AI searches tree for policy insight. By analyzing afterstate values, best action can be chosen. """ def __init__(self, table=None): if table is None: table = Table() self.table = table ## Search methods ## def get_action_values(self, board): """Return pairs of action, afterstate value.""" result = [] for action in board.get_actions(): board.push(action) value = self.table[board] result.append((action, value)) board.pop() return result def best_actions(self, board, action_values): """Return actions with highest (lowest) value for agent1 (agent2).""" best = max if board.turn() == 1 else min best_val = best(value for _,value in action_values) return [action for action,value in action_values if value == best_val] def norm_action_values(self, board, action_values): """Return values scaled within -1 to 1. Sort pairs by action number.""" return sorted(action_values, key=lambda x: x[0]) def get_best_actions(self, board): return self.best_actions(board, self.get_action_values(board)) def get_norm_actions_values(self, board): return self.norm_action_values(board, self.get_action_values(board))
316db008ce9e1dc9478512575af60749eefaef53
davidposs/FacialRecognition
/detector.py
3,637
3.53125
4
""" Created on Thu Nov 16 16:27:29 2017 @author: David Poss Face Detection Program: reads faces from a web cam in the following steps: 1. Get user's name to create a profile 2. Take 11 pictures, one for each (optional) expression 3. Saves to a data folder with other faces from the yale dataset 4. Automatically resizes all images to 180x180 It is recommended to only have 1 face in view at a time. """ import re import os import cv2 OUT_TYPE = ".jpg" TRAIN_PATH = "../../Data/SmallerTrain/" TEST_PATH = "../../Data/SmallerTest/" PREDICT_PATH = "../../Data/" def main(): """ This function can be used to train the face recognizer by gathering data for a user. Press 'q' to quit, Press 's' to save a face """ name = input("Enter your name: ") predict = input("Save an image for prediction? (y/n): ") cascades = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") video_capture = cv2.VideoCapture(0) labels = os.listdir(TRAIN_PATH) labels = [re.findall(r'[^/]*$', i)[0].split(".")[0] for i in labels] #while name in labels: # print("That name is taken: choose another") # name = input("Enter your name: ") for i in range(20, 40): print("taking picture {}".format(i)) while True: _, frame = video_capture.read() # grayed = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = cascades.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5) # Get x, y coordinates and width and height of face x_pos, y_pos, width, height = None, None, None, None for (x_pos, y_pos, width, height) in faces: cv2.rectangle(frame, (x_pos, y_pos), (x_pos + width, y_pos + height), (0, 255, 255), 2) # RGB values and thickness of detection box cv2.imshow('Webcam', frame) key_press = cv2.waitKey(1) # Press 's' to save detected face if key_press & 0xFF == ord('q'): break elif key_press & 0xFF == ord('s'): if x_pos is None or y_pos is None or width is None or height is None: print("No face detected") break face_to_save = frame[y_pos:y_pos + height, x_pos:x_pos + width] # Crop the face to 180 x 180 face_to_save = cv2.resize(face_to_save, (180, 180), interpolation=cv2.INTER_AREA) # Convert to gray scale face_to_save = cv2.cvtColor(face_to_save, cv2.COLOR_BGR2GRAY) cv2.imshow("Save this?", face_to_save) # Separate into training and testing folders using 80-20 split if predict == "y": print("Saving to {}".format(PREDICT_PATH + name + "." + str(454) + OUT_TYPE)) cv2.imwrite(PREDICT_PATH + name + "." + str(i) + OUT_TYPE, face_to_save) video_capture.release() cv2.destroyAllWindows() return if i < 26: print("Save to {}".format(TEST_PATH + name + "." + str(i) + OUT_TYPE)) cv2.imwrite(TEST_PATH + name + "." + str(i) + OUT_TYPE, face_to_save) else: print("Save to {}".format(TRAIN_PATH + name + "." + str(i) + OUT_TYPE)) cv2.imwrite(TRAIN_PATH + name + "." + str(i) + OUT_TYPE, face_to_save) break # Stop recording and close windows video_capture.release() cv2.destroyAllWindows() if __name__ == "__main__": main()
6521a3e4330b3be36c88f0f29b303ba700125abe
amitdshetty/PycharmProjects
/PythonSandbox/01 Args and KWArgs/02_KWArgs.py
772
4.28125
4
# Using the dynamic dictionary to retrieve specific key value pairs def callPrint3(key, **kwargs): # Get dictionary keys print(kwargs.get(key)) # Get dictionary key value pairs for oneKey,value in kwargs.items(): print(oneKey + " " + value) # Define both the key and value to specify which argument to use # Prevents the need for method overloading def callPrint2(**kwargs): for key,value in kwargs.items(): print(f'{key} and {value}') # Shows how a dictionary is used to pass dynamic key value paors to the function def callPrint(**kwargs): print(f'The Arguemnt here are {kwargs} as {type(kwargs)}') def main(): a = 'Amit' b = 'Shetty' callPrint3('test1', test1 = a, test2 = b) if __name__ == '__main__': main()
d530bd709ec2183377269a193199fea47180f967
sandeepks23/pythonassignment
/Set1/assignment5.py
132
3.71875
4
tup=(1,2,3,4,5,6,7,8,9,10) lst=[] even_tup=() for i in tup: if i%2==0: lst.append(i) even_tup=tuple(lst) print(even_tup)
a038c63dd3698c4c64d67577fae72ebef1ecf7ad
jtpils/mankei
/mankei/__init__.py
1,335
3.703125
4
"""Collection of mankei functions.""" from ._hillshade import _hillshade def hillshade( elevation, resolution, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0 ): """ Calculate hillshade from elevation data. Parameters ---------- elevation : 2-dimensional array Input elevation data. resolution : float Elevation ground resolution. azimuth : float Vertical sun angle in degrees. (default: 315) altitude : float Sun height in degrees. (default: 45) z : float Vertical elevation exaggeration factor. (default: 1) scale : float Factor between ground resolution and elevation measurement units. If elevation value unit is meter and the ground resolution unit degrees (as in e.g. EPSG 4326), the scale factor is recommended to be 112000. (default: 1) """ if elevation.ndim != 2: raise ValueError("elevation array must be 2-dimensional") if not 0 <= azimuth <= 360: raise ValueError("azimuth has to be between 0 and 360") if not z >= 0: raise ValueError("z value has to be greater 0") if not scale >= 0: raise ValueError("scale has to be greater 0") return _hillshade( elevation.astype("float"), resolution, azimuth, altitude, z, scale ).astype("uint8")
8a777377c466a1e6bf99b85c186d7f939f151c93
kanuos/python-programs
/Logic 1/sorta_sum.py
306
3.953125
4
# Given 2 ints, a and b, return their sum. However, sums in the range 10..19 # inclusive, are forbidden, so in that case just return 20. def sorta_sum(a, b): result = 20 if 19 >= a + b >= 10 else a + b print(f"sorta_sum({a}, {b}) -> {result}") sorta_sum(3, 4) sorta_sum(9, 4) sorta_sum(10, 11)
2d93798ed9126f997954d5bf5ff38af5a40e3c23
waltonb7944/CTI110
/M6T2_FeetToInches.py
451
4.25
4
# Converting feet to inches # 11/10/17 # M6T2_FeetToInches # Brittani Alvarez # Global constant INCHES_PER_FOOT = 12 #main function def main(): #Get the number of feet from the user. feet = int(input('Enter a number of feet: ')) # Convert that to inches. print(feet, 'equals', feet_to_inches(feet), 'inches.') # Function def feet_to_inches(feet): return feet * INCHES_PER_FOOT # Call the main function main ()
b0dd03c794cb31f3c1dec891f9eb8dcd4f5b1fa3
Aasthaengg/IBMdataset
/Python_codes/p03385/s632474056.py
143
3.578125
4
s = input() t1 = s.count('a') t2 = s.count('b') t3 = s.count('c') if t1 == 1 and t2 == 1 and t3 == 1: print('Yes') else: print('No')
817f35820644c2a928183cf04163592e9ecd64f8
mutoulovegc/gaochuang123
/桌面/day.5/while.py
105
3.671875
4
i = 1 while i <= 5: u = 1 if u <= i: print(("*"),end="") u = u + 1 print("")
6507d04e65dc5ae382bb07ad0300df6095cf1066
daki0607/AutomateBoringStuff
/guessinggame.py
702
4.1875
4
import random secretNumber = random.randint(1, 20) print("I have a number between 1 and 20") # Give the player 7 guesses for guessesRemaining in range(7, -1, -1): guess = int(input("Take a guess: ")) if guess > secretNumber: print("Your guess was too high") elif guess < secretNumber: print("Your guess was too low") # Must have guessed correctly else: break if guessesRemaining > 0: print(f"You have {guessesRemaining} guesses remaining!") else: print("That was your last guess!") if guess == secretNumber: print("Good job! You guessed my number!") else: print(f"Sorry, the number I was thinking of was {secretNumber}")
4d8aef9c24e35aa861903f09c3ee7863c6106756
proghead00/hacktoberfest2020-6
/LCM.py
368
3.921875
4
''' Input : two integer with space in between OutPut : LCM of the number ''' a, b = input().split(" ") a = int(a) b = int(b) assert (a >= 0 and b >= 0), "a,b should be >= 0" def lcm(a, b): if (a > b): for i in range(a, a * b + 1): if (i % a == 0 and i % b == 0): best = i return best print (lcm(a, b))
1fd638122437800eb9f03a8f926916d6b8e9b207
devanshu06/LearingCodes
/DSA_Algo/BinarySearch.py
2,021
4.375
4
#Binary Search Algorithm def bs(db, value): #Starting the binary search function start = 0 #String Pointer value is 0 end = db[-1] #End Pointer value is the last value of the list middle = int((start + end)/2) #creating middle value print("Start: ", start, "Middle:", middle, "End:", end) while not(value == middle) and start <= end: #not(value == middle) ----> not(False) ----> True if value > middle: #start pointer will be noe (middle + 1)th position start = middle + 1 middle = int((start + end)/2) print("Start: ", start, "Middle:", middle, "End:", end) else: # if user value is less than the middle value end = middle - 1 #then end pointer will now (middle - 1)th position middle = int((start + end)/2) print("Start: ", start, "Middle:", middle, "End:", end) if value == middle: #if the user value is equivalent to middle value then we have found the required value print("We have Found.") else: #if the value is not present in the list then we are unable to find the value print("Not Found.") print("Start: ", start, "Middle:", middle, "End:", end) #Calling the Binary Search Algorithm bs(list(range(11)), 25) bs(list(range(11)), 6) #The time complexity of the binary search algorithm is O(log n). #The best-case time complexity would be O(1) #The worst-case scenario could be the values at either extremity of the list or values not in the list.
b78eb3219f2d2941183e80d1cdbfa45f3ac915c2
rexayt/Meu-Aprendizado-Python
/Aula10/Ex31.py
271
3.609375
4
n=float(input('Digite a distância da sua viagem: ')) v=n*0.50 m=n*0.45 if n <= 200: print('Sua viagem tem {:.0f} KMs e o valor cobrado será R$ {:.2f}.'.format(n, v)) else: print('Sua viagem tem {:.0f} KMs e o valor cobrado será R$ {:.2f}'.format(n, m))
91a4ab77329cb47a41438d53d010cd7b6ff503a3
iamanobject/Lv-568.2.PythonCore
/HW_7/Taras_Smaliukh/multiples.py
131
3.75
4
def solution(number): sum_0f_numbers = sum([i for i in range(1,number) if i % 3 == 0 or i % 5 == 0]) return sum_0f_numbers
0ff4af764a0c4833f90e1b5860d26a37f7f72fc0
myliu/python-algorithm
/leetcode/palindrome_pairs_v2.py
1,038
3.640625
4
class Solution(object): def palindromePairs(self, words): """ :type words: List[str] :rtype: List[List[int]] """ # Because the index of the word is returned, we need a map to store the word to index mapping idx = {} for i, w in enumerate(words): idx[w] = i results = [] for i, word in enumerate(words): for j in range(len(word)+1): prefix = word[:j] suffix = word[j:] # Without idx[prefix[::-1]] != i, self-palindrome like `s` or `aba` would match itself if prefix[::-1] in idx and suffix == suffix[::-1] and idx[prefix[::-1]] != i: results += [i, idx[prefix[::-1]]], # j != 0 is to avoid the double counting, e.g, `abcd/dcba` should only be counted once if suffix[::-1] in idx and prefix == prefix[::-1] and idx[suffix[::-1]] != i and j != 0: results += [idx[suffix[::-1]], i], return results