blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
323fa5abed4d11fb7a19fadd15c233c638974cba
babiswas/pythonlessons
/setter_getter.py
638
3.921875
4
class A: def __init__(self,a,b): self.a=a self.b=b def __str__(self): return f"{self.a} and {self.b}" @property def seta(self): return self.a @property def setb(self): return self.b @seta.setter def seta(self,a): self.a=a @setb.setter def setb(self,b): self.b=b if __name__=="__main__": a=A(4,5) print(a) print(a.seta) print(a.setb) print(a.__dict__) a.seta=12 a.setb=13 print(a.__dict__) setattr(a,'d',100) print(a.__dict__) if hasattr(a,'b'): print("The attribute b is there in the object")
d6b8ecce9a6c4c5ac1f590c3ec58e3e8796c6804
TYalison/Python
/shellsort.py
592
3.84375
4
List=[] def ShellSort(List): print("输入对应12个月的需要排序的数据:") for i in range(12): List.append(int(input())) mid=6 while mid>=1: for m in range(mid,12): tmp=List[m] pos=m for n in range(m-mid,-1,-mid): if List[n]>tmp: List[n+mid]=List[n] pos=n List[pos]=tmp mid=int(mid/2) print("输入的数据按从小到大排序为:") for j in range(12): print("%d"%List[j]) return ShellSort(List)
8519046f530ba6b8d9f264802f416883f44d28fe
caioboffo/python-playground
/classmethod.py
875
4.125
4
class Date: def __init__(self, day, month, year): self.day = day self.month = month self.year = year def __str__(self): return 'Date({}, {}, {})'.format(self.year, self.month, self.day) def set_date(self, y, m, d): self.year = y self.month = m self.day = d @classmethod def from_str(cls, date_str): '''creates an abstract method that can be used as a static factory method for the date class''' year, month, day = map(int, date_str.split('-')) return cls(year, month, day) class A(object): def foo(self, x): print("executing foo(%s, %s)" % (self, x)) @classmethod def class_foo(cls, x): print("executing class_foo(%s, %s)" % (cls, x)) @staticmethod def static_foo(x): print("executing static_foo(%s)" % x) a = A()
8a31413b7a91c0293bae3efd36ce91c61aa128e9
SafonovMikhail/python_000577
/001383WiseplatMarathPyBegin/day6_igra-kamen-nozhnicy-bumaga.py
1,510
3.921875
4
igrok1 = 0 igrok2 = 0 win = 0 draw = 0 lose = 0 list_choises = ['Камень', 'Ножницы', 'Бумага'] print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 1, введите ваш номер:") igrok1 = int(input()) while 1 < igrok1 > 3: print("Введен некорректный номер") print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 1, введите ваш номер:") igrok1 = int(input()) if igrok1 == 1: print('Игрок 1 выбрал %s' % list_choises[1 - igrok1]) elif igrok1 == 2: print('Игрок 1 выбрал %s' % list_choises[1 - igrok1]) elif igrok1 == 3: print('Игрок 1 выбрал %s' % list_choises[1 - igrok1]) print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 2, введите ваш номер:") igrok2 = int(input()) while 1 < igrok2 > 3: for i in range(3): print("Введен некорректный номер") print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 1, введите ваш номер:") igrok2 = int(input()) print("Вы три раза ввели неверное число. Вы проиграли!") break if igrok2 == 1: print('Игрок 2 выбрал %s' % list_choises[1 - igrok2]) elif igrok2 == 2: print('Игрок 2 выбрал %s' % list_choises[1 - igrok2]) elif igrok2 == 3: print('Игрок 2 выбрал %s' % list_choises[1 - igrok2])
462e1ea2f4b9e6a5cd9c96116956a0eeeb82b7bc
DracoKali/python_demo
/comparing-list.py
515
4.21875
4
list_one = [1, 2, 5, 6, 2] list_two = [1, 2, 5, 6, 2] if list_one == list_two: print "The lists are the same" else: print "The lists are not the same" list_one = [1, 2, 5, 6, 5] list_two = [1, 2, 5, 6, 5, 3] if list_one == list_two: print "The lists are the same" else: print "The lists are not the same" list_one = ['celery', 'carrots', 'bread', 'milk'] list_two = ['celery', 'carrots', 'bread', 'cream'] if list_one == list_two: print "The lists are the same" else: print "The lists are not the same"
d9ba4fc31c0e707892981632d53b948374aa5416
amancer34/new_wordstatis
/new_wf.py
4,182
3.515625
4
# coding=gbk import os import sys import re import operator import argparse #1ͳƵʸ def total_words1(filename): with open(filename,encoding='utf-8') as f: str1 = f.read() str1 = re.sub('[^a-zA-Z]',' ',str1) #sub ĸÿո str2 = str1.lower().split() #еʱΪСдͳ words_dic = {} total = 0 for word in str2: if word in words_dic: words_dic[word] += 1 #ظĵʼһ else: words_dic[word] = 1 #ظĵдwords_dicֵ total += 1 #ͳƵʸ print("total " + str(total)) #ͳƵʸֵ words_order = sorted(words_dic.items(),key=lambda words_dic : words_dic[1],reverse=True) for key,value in words_order: print(key + " : " + str(value)) f.close() #2ͳƵʸ def total_words(filename): with open(filename,encoding='utf-8') as f: str1 = f.read() str1 = re.sub('[^a-zA-Z]',' ',str1) #sub ĸÿո str2 = str1.lower().split() #еʱΪСдͳ words_dic = {} total = 0 for word in str2: if word in words_dic: words_dic[word] += 1 #ظĵʼһ else: words_dic[word] = 1 #ظĵдwords_dicֵ total += 1 #ͳƵʸ print("total " + str(total) + " words") #ͳƵʸֵ words_order = sorted(words_dic.items(),key=lambda words_dic : words_dic[1],reverse=True) for key,value in words_order: print(key + " : " + str(value)) f.close() #3ͳƵʸ def total_words3(filename): with open(filename,encoding='utf-8') as f: str1 = f.read() str1 = re.sub('[^a-zA-Z]',' ',str1) #sub ĸÿո str2 = str1.lower().split() #еʱΪСдͳ words_dic = {} total = 0 if(len(str2)<10): for word in str2: if word in words_dic: words_dic[word] += 1 #ظĵʼһ else: words_dic[word] = 1 #ظĵдwords_dicֵ total += 1 #ͳƵʸ print("total " + str(total) + " words") #ͳƵʸֵ words_order = sorted(words_dic.items(),key=lambda words_dic : words_dic[1],reverse=True) for key,value in words_order: print(key + " : " + str(value)) else: for word in str2: if word in words_dic: words_dic[word] += 1 #ظĵʼһ else: words_dic[word] = 1 #ظĵдwords_dicֵ total += 1 #ͳƵʸ print("total " + str(total) + " words") #ͳƵʸֵ words_order = sorted(words_dic.items(),key=lambda words_dic : words_dic[1],reverse=True) for i in range(10): key,value = words_order[i] print(key + " : " + str(value)) f.close() #4ͳƵʸ ºض def total_word(content): str3 = content.lower().split() word_dic = {} total_1 = 0 for word1 in str3: if word1 in word_dic: word_dic[word1] += 1 else: word_dic[word1] = 1 total_1 += 1 print("total " + str(total_1) + " words") words_order1 = sorted(word_dic.items(),key=lambda word_dic : word_dic[1],reverse=True) for key1,value1 in words_order1: print(key1 + " : " + str(value1)) #3ļ def files_dic(files): files_list = os.listdir(files) #ȡļб for file in files_list: index = file.rfind('.') file1 = file[:index] print("\n" + file1) if not os.path.isdir(file): total_words3(file) def main(argv): #4 һ if(len(argv)==1): str = input() str = re.sub('[^a-zA-Z]',' ',str) total_word(str) #1͹4 elif sys.argv[1] == '-s': #1 if(len(argv) == 3): total_words1(sys.argv[2]) #4 ض elif(len(argv) == 2): redirect_words = sys.stdin.read() #ȡ redirect_words = re.sub('[^a-zA-Z]',' ',redirect_words) total_word(redirect_words) #3 elif os.path.isdir(sys.argv[1]): #жļ files_dic(sys.argv[1]) #2 else: total_words(sys.argv[1] + '.txt') #ú if __name__ == "__main__": main(sys.argv[0:])
455e712cc5f8e584180ba6e7e73597152c344b80
Nandhacse94/python-training
/day-4/Exception_handling.py
2,269
4.09375
4
# Exception Handling in python # try # except ''' try: n1 = int(input("Enter num1: ")) # ValueError: if value is not int n2 = int(input("Enter num2: ")) result = n1/n2 # Possibilty of ZeroDivisionError print(result) except ZeroDivisionError: print("You can not divide a number by zero") except ValueError: print("Invalid Input") ''' # finally ''' try: n1 = int(input("Enter num1: ")) # ValueError: if value is not int n2 = int(input("Enter num2: ")) result = n1/n2 # Possibilty of ZeroDivisionError print(result) except: print("Invalid value") finally: print("Bye!") ''' # User defined Exception # Guess the number game import random class SmallError(Exception): pass class LargeError(Exception): pass class Success(Exception): pass def randomUser(list1): usr = random.choice(list1) return usr # initial inputs from the Players print("*---------GUESS THE NUMBER------------*") print("Press '1' to start game\nPress '2' to exit") ch = int(input("Enter choice:")) playcount = int(input("Enter number of players:")) playerlist = [] for i in range(0,playcount): playerlist.append(input("Enter player name:")) start = int(input("Enter start value:")) stop = int(input("Enter stop value:")) print("Picking 1 random number between %i and %i\n . . . . . . . Done!!"%(start,stop)) number = random.randint(start,stop) tries = [0,0,0] while True: print("------------------------------------------------------") player = randomUser(playerlist) num = int(input("Hey !! %s \nGuess the Number:::"%player)) tries[playerlist.index(player)] += 1; try: if num < number: raise SmallError elif num>number: raise LargeError else: raise Success except SmallError: print("Your number is SMALL !! Please guess the Bigger Number") except LargeError: print("Your number is BIG !! Please guess the Smaller Number") except Success: print("Congratulations!! %s Won the game"%player) print("The Correct Number is ",num) print("Total attempts:",tries[playerlist.index(player)]) print("------------------------------------------------------") break
7b89c4859c8a6abd4948b75691ea764f3b7d7d8b
thaisnat/LP1
/TST/unidade5/vida_collatz/vida_collatz.py
294
3.9375
4
# coding: utf-8 # Unidade 5 - Vida Collatz # Thaís Nicoly - UFCG 2015.2 - 11/04/2016 num = int(raw_input()) antec = num-1 valor = [] valor.append(num) while True: if num % 2 == 0: num = num / 2 valor.append(num) else: num = 3*num + 1 valor.append(num) if num == 1: break print len(valor)
f815e1e778961daa2da1d66a41d5e4dc9fcf882a
AlinGeorgescu/Problem-Solving
/Python/1614_maximum_nesting_depth_of_the_parentheses.py
341
3.84375
4
#!/usr/bin/env python3 def main() -> None: s = input("Enter s: ") depth = 0 max_depth = 0 for c in s: if c == "(": depth += 1 if depth > max_depth: max_depth = depth elif c == ")": depth -= 1 print(max_depth) if __name__ == "__main__": main()
35bfb74ba02d5b706088a4dedd7fe7c18f2f8c49
alforsii/Learn_Python_Basics
/try-catch.py
1,006
4.34375
4
# To handle an error # sometimes in our program when something goes wrong it will break the code # and will give us an error # to prevent that we can use try to catch if any error and not to break our code # 1. try: number = int(input('Enter a number: ')) print(number) except: print('Invalid input') # now if we enter not a number console will print 'Invalid input' # so our code will not break, will handle the error and will execute print('------end #1.----------') # 2. We can also specify the error that we want to handle try: number = int(input('Enter a number: ')) value = 10 / number print(value) except ZeroDivisionError: print('You cannot divide by zero') except ValueError: print('Invalid input') print('------end #2.----------') # 3. It's good practice to catch specific error try: number = int(input('Enter a number: ')) value = 10 / number print(value) except ZeroDivisionError as err: print(err) except ValueError as err: print(err)
b25255fa566cf1d428d97c000bef9c2f61df4d7e
adil-ahmed/learrnPython
/hello.py
1,313
4.21875
4
''' print("hello") number1 = 10 number2 = 11.4 number3 = "Good" #printing print(number1, number2, number3) #checking types print(type(number1)) #casting a = 12 b = 15.5 result = a+b print(result) #Taking input name = input("Enter your name: ") print("Welcome dear", name) #python automatically takes input as string number1 = input("Enter number 1: ") number2 = input("Enter number 2: ") result = number1+number2 #Answer will be string: concating number1 & number2 print("Ans: ",result) #We can convert it using int() number1 = input("Enter number 1: ") number1 = int(number1) number2 = input("Enter number 2: ") number2 = int(number2) result = number1+number2 print("Ans: ",result) #arithmetic operations print("5+2 ",5+2) print("5-2 ",5-2) print("5*2 ",5*2) print("5/2 ",5/2) print("Division only integer part 5/2: ",5//2) print("Square of 5: ",5**2) print("5%2: ",5%2) #comparison operator a = 50 b = 80 print("a==b", a==b) print("a!=b", a!=b) print("a>b", a>b) print("a>=b", a>=b) print("a<b", a<b) print("a<=b", a<=b) print("not(a==b)", not(a==b)) #Basic gates x = 30 y = 60 print("x and y are even", x%2==0 and y%2==0) print("y>70 or y<100", y>70 or y<100) ''' #List numbers = [1,2,3,4,5] print(numbers) print(numbers[2]) # checking whether a number belongs to the list or not print(6 in numbers)
da5d91d184bd7753e960b191b98bcd9d18def120
jaymulins65/Udacity-Data-Structures-and-Algorithms
/2_ShowMeTheDataStructures/SolutionsAndExplanations/problem_2_FileRecursion.py
1,466
4.15625
4
import os def find_files_using_walk(suffix, path): for root, dirs, files in os.walk(path): for file in files: if file.endswith(suffix): print(os.path.join(root, file)) return None def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if suffix == '': return [] # Base condition if len(os.listdir(path)) == 0: return [] path_elements = os.listdir(path) path_files = [file for file in path_elements if ('.' + suffix) in file] path_folders = [folder for folder in path_elements if '.' not in folder] for folder in path_folders: path_files.extend(find_files(suffix=suffix, path=path + '/' + folder)) return path_files def main(): # find_files_using_walk('.c', 'testdir') # Tests path_base = os.getcwd() + '/testdir' # Testcase 1 print(find_files(suffix='c', path=path_base)) # Testscase 2 print(find_files(suffix='h', path=path_base)) # Testcase 3 print(find_files(suffix='x', path=path_base)) if __name__ == '__main__': main()
d094108fd16744850c880aa77cfcde0a0cd6c212
lekasankarappan/PythonClasses
/Day5/listassignmenton zip.py
329
3.9375
4
#pop(),remove(),c;lear() oldlist=["Rose","Jasmine","lily","lotus","Hibiscus","Tulip","bluebell","sunflower","Poppy","Daffodil","Snowdrop","cherrybz"] newlist=["carrot","cabbage","Beans","Tomato","Turnip","cucumber","Brocoli","cauliflower","yam","Spinach"] print(oldlist) print(newlist) for z in zip(oldlist,newlist): print(z)
3c7b9e8107c67f63a3afa484437f362e1cd891d4
kingtvarshin/pythonprac
/python_assignments/assignment2/getbinarystring.py
494
3.78125
4
def printAllCombinations(pattern, i=0): if i == len(pattern): print(''.join(pattern), end =" ") return # if the current character is '?' if pattern[i] == '?': for ch in "01": # replace '?' with 0 and 1 pattern[i] = ch # recur for the remaining pattern printAllCombinations(pattern, i + 1) # backtrack pattern[i] = '?' else: printAllCombinations(pattern, i + 1) a = int(input()) #pattern = "1?11?00?1?" pattern = input() printAllCombinations(list(pattern))
a358818e25e28aa5c400483d6ab0a6a60fa19887
shay-d16/Python-Projects
/6. Tkinter and Sqlite/encapsulation_example.py
1,069
4
4
# Python: 3.9.4 # # Author: Shalondra Rossiter # # Purpose: The purpose of ENCAPSULATION is to wrap your code in one single unit that # restricts access from functions and variables from being directly changed # or modified by accident within a class. # Protected is prefixed with a single underscore. It doesn't actually change # the behavior of anything though. You could still nodify your methods and # properties within a class. It acts more as a warninng to other developers # and basically states that "this is protects - don't use outside of this class" # without the need for commenting or making it harder to modify your objects. class Protected: def __init__(self): self._protectedVar = 0 obj = Protected() obj.protectedVar = 34 print(obj.protectedVar) class Protected: def __init__(self): self.__privateVar = 12 def getPrivate(self): print(self.__privateVar) def setPrivate(self, private): self.__privateVar = private obj = Protected() obj.getPrivate() obj.setPrivate(23) obj.getPrivate()
a20704620541a99b3f84e1dbb41df01887c2aa59
codeAligned/Leet-Code
/src/P-169-Majority-Element.py
825
3.671875
4
''' P-169 - Majority Element Given an array of sizen, find the majority element. The majority element is the element that appears more than&lfloor; n/2 &rfloor;times. You may assume that the array is non-empty and the majority element always exist in the array. Credits:Special thanks to@tsfor adding this problem and creating all test cases. Tags: Divide and Conquer, Array, Bit Manipulation ''' class Solution: # @param num, a list of integers # @return an integer def majorityElement(self, num): m = {} if len(num) == 1: return num[0] for c in num: if c in m: m[c] += 1 if m[c] > len(num) / 2: return c else: m[c] = 1 s = Solution() print s.majorityElement([1,])
db3bfa997b8e90cd404da1e778a1dbf03d6987bb
jhn--/sample-python-scripts
/python3/doctest_example1.py
113
3.578125
4
def multiply(a, b): """ >>> multiply(4,3) 12 >>> multiply('a',3) 'aaa' """ return a*b
f5b55f399d2c0a3c3862147e051cb3611c53047b
akyare/Python-Students-IoT
/1-python-basics/1-baby-steps/1-start/MutableInmutable.py
790
4.5
4
# Reserving memory space: x = 420 # Lets lookup the memory location: print(f'memory address of variable x: {id(x)}, value: {x}') # String, boolean and Integers are immutable so the python interpreter # will allocate a new memory location if we alter the value of a variable: x = 42 print(f'memory address of variable x: {id(x)}, value: {x}', '\n') # Lists however are mutable objects: list_numbers = [1, 2, 3] print(f'memory address of variable list_numbers: {id(list_numbers)}, value: {list_numbers}') # Lets see what our memory address is after some changes: list_numbers.append(4) print(f'memory address of variable list_numbers: {id(list_numbers)}, value: {list_numbers}') # BONUS PART # Learn more: # Memory management in Python: https://www.youtube.com/watch?v=F6u5rhUQ6dU
1d5ddb8e0fc055fa9b2dc2b2f52f47957ada7901
arnabs542/Data-Structures-And-Algorithms
/Backtracking/Generate all Parentheses II.py
1,344
4.0625
4
""" Generate all Parentheses II Problem Description Given an integer A pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*A. Problem Constraints 1 <= A <= 20 Input Format First and only argument is integer A. Output Format Return a sorted list of all possible paranthesis. Example Input Input 1: A = 3 Input 2: A = 1 Example Output Output 1: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] Output 2: [ "()" ] Example Explanation Explanation 1: All paranthesis are given in the output list. Explanation 2: All paranthesis are given in the output list. """ class Solution: # @param A : integer # @return a list of strings def generate(self, A, cur_idx, open, close, cur_set, ans): if cur_idx == 2*A: ans.append("".join(cur_set)) if open > 0: cur_set.append('(') self.generate(A, cur_idx+1, open-1, close, cur_set, ans) cur_set.pop() if close > open: cur_set.append(')') self.generate(A, cur_idx+1, open, close-1, cur_set, ans) cur_set.pop() def generateParenthesis(self, A): open = A close = A ans = [] cur_set = [] self.generate(A, 0, open, close, cur_set, ans) return ans
e4169a0ff7e20ddb31f276141c2055acfe53b6ee
novayo/LeetCode
/0114_Flatten_Binary_Tree_to_Linked_List/try_1.py
914
3.984375
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 flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ def recr(node): if not node: return left = recr(node.left) right = recr(node.right) node.left = None if left: tmp = left while tmp and tmp.right: tmp = tmp.right tmp.right = right node.right = left else: node.right = right return node recr(root)
e0c2718b65bf4fc2ddf3053f58d8aa85e576f46b
MaciejZawierzeniec/BlackJack
/BlackJack.py
3,457
3.734375
4
import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} playing = True class Card(): def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return f"{self.suit} of {self.rank}" class Deck: def __init__(self): self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) def __str__(self): return f"{self.deck}" def shuffle(self): random.shuffle(self.deck) def deal(self): return self.deck.pop() class Hand: def __init__(self): self.cards = [] self.value = 0 self.aces = 0 def add_card(self,card): self.cards.append(card) self.value += values[card.rank] def adjust_for_ace(self): if self.value > 21: self.value -= 9 class Chips: def __init__(self): self.total = 100 self.bet = 0 def win_bet(self): self.total = self.total + 2*self.bet self.bet = 0 def lose_bet(self): print("Your chips: {}".format(self.total)) def take_bet(): bet = Chips() bet.bet = input("Type your bet: ") def hit(deck,hand): hand.add_card(deck.deal()) hand.adjust_for_ace() def hit_or_stand(deck,hand): hors = input("\nWould you like to (h)it or (s)tand? ") if hors == "s": pass elif hors == "h": hit(deck, hand) def show_some(player,dealer): print("\nPlayer's cards:") for card in player.cards: print(card) print("\nDealer's cards:") for card in dealer.cards: print(card) print("Hidden card") break def show_all(player,dealer): print("\nPlayer's cards:") for card in player.cards: print(card) print("\nDealer's cards:") for card in dealer.cards: print(card) def player_busts(): global playing playing = False print("You lose") def player_wins(): global playing playing = False print("You won") def push(): pass while True: deck = Deck() deck.shuffle() player = Hand() player.add_card(deck.deal()) player.add_card(deck.deal()) dealer = Hand() dealer.add_card(deck.deal()) dealer.add_card(deck.deal()) player_chips = Chips() take_bet() show_some(player,dealer) while playing: hit_or_stand(deck,player) show_some(player,dealer) if player.value > 21: player_busts() break while dealer.value < 17: dealer.add_card(deck.deal()) show_all(player,dealer) if dealer.value > player.value: player_busts() player_chips.lose_bet() elif dealer.value < player.value: player_wins() player_chips.win_bet() else: print("Draw") again = input("Would you like to play again(y/n)? ") if again == "y": playing = True else: break
bc8e9825708cdd25db65a89159f9500a7d965da3
roboto100/ShufflingTest
/ShuffleTest.py
8,282
4.09375
4
import random class deck: ''' A class for simulating deck shuffling __init__: Initializes the deck. Creates a sorted list of numbers 1-52; sets the number of times sorted to 0 sort: Replaces the list with a new one, with range 1-52; increases the timesSorted variable by 1 shuffle_once: applies one round of the overhand shuffle save_probabilities: updates the occurrences variable to show how often each card appears in each position shuffle_save: applies the shuffling and then saves the probabilities to the occurrences variable get_standard_deviation: Converts occurrences to probabilities, then gets the standard deviation of those probabilities ''' def __init__(self): # Initializes the deck # Create a new list from 1-52 self.lst = [] for card in range(1, 53): self.lst.append(card) # Reset occurrences self.occurrences = [] for i in range(52): self.occurrences.append([0] * 52) # Set the times sorted to 0. Used to calculate standard deviation. self.timesSorted = 0 def sort(self): # Sorts the deck - Resets the list so that it's 1-52. # Resets the list self.lst = [] for card in range(1, 53): self.lst.append(card) # Increment the timesSorted by 1. self.timesSorted += 1 def shuffle_once(self, minTake, maxTake, minPlace, maxPlace): ''' Shuffles the deck once with the overhand method :param minTake: Sets the minimum number of cards we can take from the back :param maxTake: Sets the maximum number of cards we can take from the back :param minPlace: Sets the minimum number of cards we can place at the front :param maxPlace: Sets the maximum number of cards we can place at the front :return: Nothing ''' # Decide how many cards we take from the back takeFromBack = random.randint(minTake, maxTake) # Seperate the deck into our two new decks newList = self.lst[-takeFromBack:] for i in range(takeFromBack): self.lst.pop() # While our new deck is not empty while (len(newList) > 0): # Make sure we're not crossing (minSelect<maxSelect) minSelect = minPlace maxSelect = min(maxPlace, len(newList)) # If len(newList)<minPlace, then we might get an error temp = minSelect minSelect = min(temp, maxSelect) maxSelect = max(temp, maxSelect) # Decide however many we can put back, then put that at the front of the old deck and remove it from the new deck. putBack = random.randint(minSelect, maxSelect) self.lst = newList[:putBack] + self.lst newList = newList[putBack:] def save_probabilities(self): # Save the number of times the cards appear in each position # For each position in the deck for i in range(len(self.lst)): # Select which card number was at that position, and increment that position in our occurrences variable. self.occurrences[i][self.lst[i] - 1] += 1 def shuffle_save(self, minTake, maxTake, minPlace, maxPlace, shuffles): ''' Shuffle the deck multiple times and save the occurrences. :param minTake: Minimum number of cards we can take from the back :param maxTake: Maximum number of cards we can take from the back :param minPlace: Minimum number of cards we can place at the front :param maxPlace: Maximum number of cards we can place at the front :param shuffles: Number of times we apply the shuffle :return: None ''' for shuffleNum in range(shuffles): self.shuffle_once(minTake, maxTake, minPlace, maxPlace) self.save_probabilities() def get_standard_deviation(self): # Calculates the probabilities each card is in each position and calcualte standard deviation # return: standard deviation sum = 0 # For each position for line in self.occurrences: # For each card that could be there for val in line: # Calculate the sum sum += ((1 / 52) - val/self.timesSorted) ** 2 # Divide by N and sqrt it sum = sum / (52 * 52 - 1) sum = (sum) ** 0.5 return sum def test_selections(minTakes_, maxTakes_, maxTests): ''' Runs the code that checks how changing the selections affects the efficiency of shuffling :param minTakes_: Minimum cards we can take from the back :param maxTakes_: Maximum cards we can take from the back :param maxTests: Maximum number of tests we apply :return: ''' # Create scores, stores the standard deviation. scores = [] for i in range(52): scores.append([''] * 52) # Test all values from 1-minTakes_ for minTakes in range(1,minTakes_): # Used to check how long the code will take to run #print(minTakes) # Test all values from minTakes-maxTakes for maxTakes in range(minTakes, maxTakes_): # Create a new deck myDeck = deck() # Test however many times specified for testRun in range(maxTests): myDeck.shuffle_save(minTakes,maxTakes,3,10,5) myDeck.sort() # Save the standard deviation of the tested decks scores[minTakes-1][maxTakes-1]=myDeck.get_standard_deviation() # Print the standard deviation in a way that's easy to import to excel for line in scores: print(str(line)[1:-1].replace("'","")) def test_replacements(minReplace, maxReplace, maxTests): ''' Runs the code that checks how changing the replacements affects the efficiency of shuffling :param minReplace: Minimum cards we can place at the front :param maxReplace: Maximum cards we can place at the front :param maxTests: Maximum number of tests we apply :return: ''' # Create scores, stores the standard deviation. scores = [] for i in range(52): scores.append([''] * 52) # Test all values from 1-minReplace for minPuts in range(1, minReplace): # Used for checking how long the code takes to run #print(minPuts) # Test all values from minReplace-maxReplace for maxPuts in range(minPuts, maxReplace): # Create a new deck myDeck = deck() # Test however many times specified for testRun in range(maxTests): myDeck.shuffle_save(17, 26, minPuts, maxPuts, 5) myDeck.sort() # Save the standard deviation of the tested decks scores[minPuts - 1][maxPuts - 1] = myDeck.get_standard_deviation() # Print the standard deviation in a way that's easy to import to excel for line in scores: print(str(line)[1:-1].replace("'", "")) def test_max_shuffles(minTest, maxTest, maxTests): ''' Runs the code that checks how changing the shuffling number affects the efficiency of shuffling :param minTest: Minimum number of shuffles we try :param maxTest: Maximum number of shuffles we try :param maxTests: Maximum number of tests we apply :return: None ''' # Create a list to store the standard deviations scores = [] # For every valid number of shuffles we need to try for maxShuffles in range(minTest, maxTest): # Used to test the time it takes to run the code #print(maxShuffles) # Create a new deck myDeck = deck() # For each test we need to run for testRun in range(maxTests): # Shuffle, save, and sort myDeck.shuffle_save(17, 26, 3, 10, maxShuffles) myDeck.sort() # Store the standard deviation to print later scores.append(myDeck.get_standard_deviation()) # Print all the standard deviations print(str(scores)[1:-1])
f67392cdac896371fcb643f20e21432e1afb5f99
CharonAndy/scikit-fda
/examples/plot_explore.py
2,216
3.84375
4
""" Exploring data ============== Explores the Tecator data set by plotting the functional data and calculating means and derivatives. """ # Author: Miguel Carbajo Berrocal # License: MIT import skfda import matplotlib.pyplot as plt import numpy as np ############################################################################### # In this example we are going to explore the functional properties of the # :func:`Tecator <skfda.datasets.fetch_tecator>` dataset. This dataset measures # the infrared absorbance spectrum of meat samples. The objective is to predict # the fat, water, and protein content of the samples. # # In this example we only want to discriminate between meat with less than 20% # of fat, and meat with a higher fat content. dataset = skfda.datasets.fetch_tecator() fd = dataset['data'] y = dataset['target'] target_feature_names = dataset['target_feature_names'] fat = y[:, np.asarray(target_feature_names) == 'Fat'].ravel() ############################################################################### # We will now plot in red samples containing less than 20% of fat and in blue # the rest. low_fat = fat < 20 fd[low_fat].plot(c='r', linewidth=0.5) fd[~low_fat].plot(c='b', linewidth=0.5, alpha=0.7) ############################################################################### # The means of each group are the following ones. skfda.exploratory.stats.mean(fd[low_fat]).plot(c='r', linewidth=0.5) skfda.exploratory.stats.mean(fd[~low_fat]).plot(c='b', linewidth=0.5, alpha=0.7) fd.dataset_label = fd.dataset_label + ' - means' ############################################################################### # In this dataset, the vertical shift in the original trajectories is not very # significative for predicting the fat content. However, the shape of the curve # is very relevant. We can observe that looking at the first and second # derivatives. fdd = fd.derivative(1) fdd[low_fat].plot(c='r', linewidth=0.5) fdd[~low_fat].plot(c='b', linewidth=0.5, alpha=0.7) plt.figure() fdd = fd.derivative(2) fdd[low_fat].plot(c='r', linewidth=0.5) fdd[~low_fat].plot(c='b', linewidth=0.5, alpha=0.7)
7091fac3cb984a79d965995a8a5cdc77c2078e7f
amonik/pythonnet
/fib.py
1,850
3.53125
4
"""" def main(): print(cal(8)) def cal(n): if n > 0: n += cal(n - 1) return n if __name__ == '__main__': main() class Person: def __init__(self): self.__name = "" def set_name(self, name): self.__name = name def get_name(self): return self.__name class Patient(Person): def __init__(self, name, sickness): self.__sickness = sickness Person.__init__(name) def set_sickness(self, sickness): self.__sickness = sickness def get_sickness(self): return self.__sickness class InvalidInput(ValueError): def __init__(self, my_input): super().__init__(f"You enter in incorrect value ${my_input}") """ from tkinter import * from tkinter import messagebox class WidgetDemo(): def __init__(self): window = Tk() window.title("Widget Demo!") frame1 = Frame(window) frame1.pack() button1 = Button(window, text="The Button", command=self.processButton()) button1.pack() window.mainloop() def processButton(self): my_message = messagebox.showinfo("Welcome") return my_message WidgetDemo() """ class InvalidInput(ValueError): def __init__(self, my_input): super().__init__(f"You enter in incorrect value {my_input}") self.my_input = my_input class Area: def __init__(self): self.x = 0 def set_x(self, n): if n <= 0: raise InvalidInput(n) else: self.x = n def __str__(self): return str(self.x) def main(): a = Area() input_value = int(input("Enter in a value greater than 0: ")) a.set_x(input_value) if input_value <= 0: print("Invalid input entered") else: print(a) if __name__ == '__main__': main() """
e02d59b22803b11a426f2fb1e4bef65588a05591
RichardYang58/test
/backup/hello1.py
123
3.59375
4
print('hello world') print('what is your name') myName= input() print('nice to meet you'+ myName) print(len(myName))
28c335649243750024c45399ad856897c2ec7a52
daniel-reich/turbo-robot
/qTmbTWqHNTtDMKD4G_19.py
2,364
4.21875
4
""" It's been a long day for Matt. After working on Edabit for quite a bit, he decided to go out and get a beer at the local bar a few miles down the road. However, what Matt didn't realise, was that with too much drinks you can't find the way home properly anymore. Your goal is to help Matt get back home by telling him how long the path to his house is if he drives the optimal route. Matt lives in a simple world: there is only dirt (represented by a dot), a single house (Matt's house, represented by the letter "h") and there are trees (represented by the letter "t") which he obviously can't drive through. Matt has an unlimited amount of moves and each move he can go north, north-east, east, south-east, south, south-west, west and north-west. There will only be one Matt and one house, which is Matt's. The world is given to you as a comma-delimited string which represents the cells in the world from top-left to bottom-right. A 3x3 world with Matt on the top-left and his house on the bottom-right, with a tree in the middle would be represented as: m,.,.,.,t,.,.,.,h The answer to this world would be 3: Matt would first move east, then south- east, then south (or south > south-east > east). The function call related to this example would be the following: get_path_length("m,.,.,.,t,.,.,.,h", 3, 3) If Matt is unable to get home from his current location, return `-1`, otherwise return the amount of moves Matt has to make to get home if he follows the optimal path. You are given the world, it's width and it's height. **Good luck!** """ dirs = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)] ​ def on_grid(width, height, r, c): return r >= 0 and c >= 0 and r < height and c < width def get_path_length(world, width, height): world = [[world.split(',')[r*width + c] for c in range(width)] for r in range(height)] que = [] for r in range(height): for c in range(width): if world[r][c] == 'm': que.append((r, c)) world[r][c] = 0 break while que: r, c = que.pop(0) for dir in dirs: r2, c2 = r+dir[0], c+dir[1] if on_grid(width, height, r2, c2): if world[r2][c2] == '.': world[r2][c2] = world[r][c] + 1 que.append((r2, c2)) elif world[r2][c2] == 'h': return world[r][c] + 1 return -1
ac6da67bb7824e2bf0a7c86cbf761fa9b0aa78e0
DeanDro/monopoly_game
/cards_classes/cards.py
774
3.96875
4
"""Super class for all cards in the game""" import pygame class Cards: """Name, owner and saleable will be available across all cards""" def __init__(self, name, saleable, board_loc, owner=None): self.name = name self.board_loc = board_loc self.saleable = saleable self.owner = owner # Method to assign owner to a card if it is purchased def assign_owner(self, new_owner): self.owner = new_owner # Check who is the property owner def check_ownership(self): return self.owner def return_name(self): """In order for this method to return the name value for all children classes, each child class must have a global variable named self.name """ return self.name
223e1113031d71df8d6892e7419c3045684df352
wenziyue1984/python_100_examples
/006斐波那契数列.py
464
4
4
# -*- coding:utf-8 -*- __author__ = 'wenziyue' ''' 斐波那契数列。 斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、…… ''' def fb(n): if n == 0: return 0 if n == 1: return 1 if n >= 2: return fb(n-1)+fb(n-2) if __name__=="__main__": fb_list = [] for i in range(20): fb_list.append(fb(i)) print(fb_list) ''' 还可以用迭代器实现 '''
48760640600abea47d0ee0a7e96bb7b161476f4b
guswns1659/Algorithm
/lec11_ArrayStack & LinkedListStack ADT.py
1,224
4.15625
4
""" 배열리스트와 연결리스트로 스택의 추상적 자료구조 구현하기 연산의 정의 -길이 얻어내기 : size() -비었는지 확인하기 : isEmpty() -push 하기 : push() -pop 하기 : push() -peek 하기 : peek() """ class ArrayStack: def __init__(self): self.data = [] def size(self): return len(self.data) def isEmpty(self): return self.size() == 0 def push(self, item): return self.data.append(item) def pop(self): return self.data.pop() def peek(self): return self.data[-1] #폴더 내 모듈 중 import 하려면 폴더에 __init__파일 필요. from DoubleLinkedList_ADT import Node from DoubleLinkedList_ADT import DoublyLinkedList class LinkedListStack: def __init__(self): self.data = DoublyLinkedList() def size(self): return self.data.getLength() def isEmpty(self): return self.size() == 0 def push(self, item): node = Node(item) self.data.insertAt(self.size()+1, node) #self.size()에 삽입은 마지막 전에 삽입 def pop(self): return self.data.popAt(self.size()) def peek(self): return self.data.getAt(self.size()).data
efaac95909bd0bedd728c00b3246f87e8aa743f7
daniel-reich/ubiquitous-fiesta
/yiEHCxMC9byCqEPNX_6.py
430
3.859375
4
def is_palindrome(p, r = None, i = None): if r == None: symbols = list('/?,.><@#-_!$%^~\';:') for symbol in symbols: p = p.replace(symbol, '') p = p.lower().replace(' ', '') r = ''.join(list(reversed(p))) i = 0 return is_palindrome(p, r, i) elif i == len(p) - 1: return p[i] == r[i] else: if p[i] == r[i]: i += 1 return is_palindrome(p, r, i) else: return False
fe5b4441e80c30872bba4bebf14b219f3e71409c
tesschinakoo/Blob
/findTheBlobPart1Template.py
3,530
3.65625
4
import Myro from Myro import * from Graphics import * from random import * #init("sim") width = 500 height = 500 sim = Simulation("Maze World", width, height, Color("gray")) #outside walls sim.addWall((10, 10), (490, 20), Color("black")) sim.addWall((10, 10), (20, 490), Color("black")) sim.addWall((480, 10), (490, 490), Color("black")) sim.addWall((10, 480), (490, 490), Color("black")) #blue spot poly = Circle((50, 50), 45) poly.bodyType = "static" poly.color = Color("blue") poly.outline = Color("black") sim.addShape(poly) #red spot poly = Circle((450, 50), 45) poly.bodyType = "static" poly.color = Color("red") poly.outline = Color("black") sim.addShape(poly) #green spot poly = Circle((50, 450), 45) poly.bodyType = "static" poly.color = Color("green") poly.outline = Color("black") sim.addShape(poly) #yellow spot poly = Circle((450, 450), 45) poly.bodyType = "static" poly.color = Color("yellow") poly.outline = Color("black") sim.addShape(poly) #begin simulation and sets robot's position makeRobot("SimScribbler", sim) sim.setPose(0, width/2, height/2, 0) sim.setup() # 1-RED # 2-GREEN # 3-BLUE # 4-YELLOW #The following is a helper function #Inputs: A picture and a color represented by the list above #Returns the average x location of the color in the picture or -1 if the robot has found the color spot def findColorSpot(picture, color): xPixelSum = 0 totalPixelNum = 0 averageXPixel = 0 show(picture) for pixel in getPixels(picture): if(color == 1 and getRed(pixel) > 150 and getGreen(pixel) < 50 and getBlue(pixel) < 50): xPixelSum += getX(pixel) totalPixelNum += 1 elif(color == 2 and getRed(pixel) < 50 and getGreen(pixel) > 100 and getBlue(pixel) < 50): xPixelSum += getX(pixel) totalPixelNum += 1 elif(color == 3 and getRed(pixel) < 50 and getGreen(pixel) < 50 and getBlue(pixel) > 150): xPixelSum += getX(pixel) totalPixelNum += 1 elif(color == 4 and getRed(pixel) > 200 and getGreen(pixel) > 150 and getBlue(pixel) < 50): xPixelSum += getX(pixel) totalPixelNum += 1 if(totalPixelNum != 0): averageXPixel = xPixelSum/totalPixelNum #Handles the case where robot has found the spot if it is near it #If necessary adjust the value if(totalPixelNum/(getWidth(picture)*getHeight(picture)) > 0.21): averageXPixel = -1 return averageXPixel # Use the following integers for colors: # 1-RED # 2-GREEN # 3-BLUE # 4-YELLOW ######################Code Starts Here################################## y=0 answer=askQuestion("Which blob would you like to find, or would you prefer a random one?",["Red", "Green", "Blue", "Yellow", "Random"]) if (answer=="Red"): y=1 if (answer=="Green"): y=2 if (answer=="Blue"): y=3 if (answer=="Yellow"): y=4 if (answer=="Random"): y=randrange(1,4) #FIND THE BLOB turnBy(randrange(30,60)) pic=takePicture() show(pic) x=findColorSpot(pic,y) while (x==0): turnBy(randrange(30,60)) pic=takePicture() show(pic) x=findColorSpot(pic,y) #WE NEED SOME SORT OF UNTIL while (0 < x < 90): turnBy(10) pic=takePicture() show(pic) x=findColorSpot(pic,y) while (150 < x < 256): turnBy(350) pic=takePicture() show(pic) x=findColorSpot(pic,y) if (90 < x <150): forward(2,3) pic=takePicture() x=findColorSpot(pic,y) if (x ==-1): print ("You found the blob!")
150a7e972731ead21c282973a0fd0905b5199baa
alkudakaev/MyHomework
/MyCalendar/my_function/my_calendar_function.py
1,162
3.53125
4
def choice_of_action(number): number = int(number) if number == 1: view_task_list() elif number == 2: add_new_task() elif number == 3: edit_task() elif number == 4: finish_task() elif number == 5: restart_task() elif number == 6: calendar_exit() # 1. Вывести список задач def view_task_list(): print('Выводит список всех задач со статусом выполнения за указанный день') # 2. Добавить задачу def add_new_task(): print('Добавить новую задачу') # 3. Отредактировать задачу def edit_task(): print('Редактируем задачу по ID') # 4. Завершить задачу def finish_task(): print('Меняет статус задачи на "Завершена"') # 5. Начать задачу сначала def restart_task(): print('Меняет статус задачи на "Не выполнено"') # 6. Выход def calendar_exit(): print('Выход из приложения ежедневника')
72f9c774423a1ebfde372c61fef376eba006d47b
houziershi/study
/python/py/02.cookbook/0102/exp.py
742
3.625
4
# coding=utf-8 print ord('a') # 97 print chr(97) # a print ord(u'\u2020') # 8224 print repr(unichr(8224)) # u'\u2020' print map(ord, 'ciao') # [99, 105, 97 111] print ''.join(map(chr, range(97,100))) # abc #将Unicode转换成普通的Python字符串:"编码(encode)" unicodestring = u"Hello world" utf8string = unicodestring.encode("utf-8") asciistring = unicodestring.encode("ascii") isostring = unicodestring.encode("ISO-8859-1") utf16string = unicodestring.encode("utf-16") #将普通的Python字符串转换成Unicode: "解码(decode)" plainstring1 = unicode(utf8string, "utf-8") plainstring2 = unicode(asciistring, "ascii") plainstring3 = unicode(isostring, "ISO-8859-1") plainstring4 = unicode(utf16string, "utf-16")
fec7c3461925245a1024778b64d8a7236c20033e
fanliu1991/LeetCodeProblems
/23_Merge_k_Sorted_Lists.py
3,169
4.03125
4
''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 ''' import sys, optparse, os class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ ''' Merge with Divide And Conquer: 1.Pair up k lists and merge each pair. 2.After the first pairing, k\text{k}k lists are merged into k/2 lists with average 2N/k length, then k/4, k/8 and so on. 3.Repeat this procedure until we get the final sorted linked list. Thus, we'll traverse almost N nodes per pairing and merging, and repeat this procedure about log_{2}{k} times. ''' lists_len = len(lists) print lists_len if lists_len == 0: return [] elif lists_len == 1: return lists[0] elif lists_len == 2: l1, l2 = lists[0], lists[1] head = point = ListNode(0) i, j = 0,0 while l1 and l2: if l1.val <= l2.val: point.next = l1 l1 = l1.next else: point.next = l2 l2 = l2.next point = point.next if not l1: point.next = l2 else: point.next = l1 return head.next else: left = self.mergeKLists(lists[:lists_len/2]) print "left", left right = self.mergeKLists(lists[lists_len/2:]) print "right", right ans = self.mergeKLists([left, right]) return ans # linked list method: ''' def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ amount = len(lists) interval = 1 while interval < amount: for i in range(0, amount - interval, interval * 2): lists[i] = self.merge2Lists(lists[i], lists[i + interval]) interval *= 2 return lists[0] if amount > 0 else lists def merge2Lists(self, l1, l2): head = point = ListNode(0) while l1 and l2: if l1.val <= l2.val: point.next = l1 l1 = l1.next else: point.next = l2 l2 = l2.next point = point.next if not l1: point.next=l2 else: point.next=l1 return head.next ''' lists = [[1, 3, 5, 7, 9, 11], [0, 2, 4, 6, 8, 10], [-5, -4, -3, -2, -1, 12, 13, 14, 15, 16], [0.5, 1.5, 2.5, 3.5]] solution = Solution() result = solution.mergeKLists(lists) print result ''' Complexity Analysis Time complexity : O(n*log_{2}{k}), where k is the number of linked lists. We can merge two sorted linked list in O(n) time where n is the total number of nodes in two lists. Sum up the merge process and we can get O(n*log_{2}{k}) Space complexity : O(1). We can merge two sorted linked lists in O(1) space. '''
ff3aeee5c342bc376eb7d32abe0950b58b287bf8
0siris7/Think-python-repo
/mysqrt.py
496
4.0625
4
from math import sqrt def mysqrt(a): x = 3 y = (x + (a/x)) / 2 while True: if abs(y - x) < 0.0000001: return y else: x = y y = (x + (a/x)) / 2 def test_square_root(): a = int(input("Enter the number (a): >")) print("a\tmysqrt(a)\tmath.sqrt(a)\tdiff".center(30)) for i in range(1, a + 1): #i = float(i) print(f"{i}\t{mysqrt(i)}\t{sqrt(i)}\t{abs(mysqrt(i) - sqrt(i))}".center(30)) test_square_root()
daa99cfd149d8bbbdc1ba2e8548317a0b9978b5e
kathrinari/python-internship
/python-internship/trivia.py
12,929
3.890625
4
#trivia animation #mini game for the final project #the following code is written by Naomi Reichmann #except for the Button class, which I borrowed from Tech With Tim (YouTube channel) import pygame, sys, random from pygame.locals import * pygame.init() score = 0 #variable to track the score the user achieves, which decides whether they can open the door or not fpsClock = pygame.time.Clock() FPS = 30 #frames per second #window set up DISPLAYSURF = pygame.display.set_mode((900, 600), 0, 32) pygame.display.set_caption("final project") #caption of the window WHITE = (255, 255, 255) #color of the bar PURPLE = (50, 0, 50) #background color BLACK = (0, 0, 0) #text color class button(): def __init__(self, color, x, y, width, height, text = ""): self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text def draw(self, DISPLAYSURF, outline=None): #call this method to draw the button on the screen if outline: pygame.draw.rect(DISPLAYSURF, outline, (self.x-2, self.y-2, self.width+4, self.height+4), 0) pygame.draw.rect(DISPLAYSURF, self.color, (self.x, self.y, self.width, self.height), 0) if self.text != "": font = pygame.font.SysFont("freesansbold.ttf", 20) text = font.render(self.text, 1, (0, 0, 0)) DISPLAYSURF.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2))) def isOver(self, pos): #pos is the mouse position or a tuple of (x, y) coordinates if pos[0] > self.x and pos[0] < self.x + self.width: if pos[1] > self.y and pos[1] < self.y + self.height: return True return False #parameters color x y width height text button1 = button(WHITE, 10, 300, 100, 50, "") button2 = button(WHITE, 10, 360, 100, 50, "") button3 = button(WHITE, 10, 420, 100, 50, "") button4 = button(WHITE, 10, 480, 100, 50, "") buttonQuit = button(WHITE, 450, 350, 100, 50, "") buttonAgain = button(WHITE, 300, 350, 100, 50, "") font1 = pygame.font.Font("freesansbold.ttf", 65) #font for the text in the game font2 = pygame.font.Font("freesansbold.ttf", 20) text1 = font1.render("", True, BLACK, WHITE) #the text is an empty string for now, it will be inserted later textSurfaceObj = font2.render("", True, BLACK, WHITE) textrect1 = text1.get_rect() textRectObj = textSurfaceObj.get_rect() textrect1 = (260, 170) textrect2 = (310, 250) textRectObj = (10, 250) #x and y coordinates of the upper left corner of the rectangle DISPLAYSURF.blit(textSurfaceObj, textRectObj) x = 0 running=True while running: #main loop DISPLAYSURF.fill(PURPLE) #filling the background with purple for event in pygame.event.get(): #ending the game if event.type == QUIT: #the window closes when the user presses the x button ### KB: I added the text for context, since I changed the game to play the Lava_Schollen_Spiel automatically after either winning, losing or quitting print("\n\nSo you changed your mind and you would rather search for the key? Alright...\n") running=False #pygame.quit() #sys.exit() elif event.type == K_ESCAPE: #the window closes when the user presses the escape button #pygame.display.quit() ### KB: I added the text for context, since I changed the game to play the Lava_Schollen_Spiel automatically after either winning, losing or quitting print("\n\nSo you changed your mind and you would rather search for the key? Alright...\n") running=False #pygame.quit() #sys.exit() elif event.type == KEYDOWN and x == 7 and score >= 4: #when the user wins they can press any key and Friederike's game will start print("\n\nYOU DID IT! Now you can walk through the door.\n") #importing Friederike's game #import Lava_Schollen_Spiel running=False #pygame.quit() #sys.exit() pos = pygame.mouse.get_pos() #mouse position if event.type == pygame.MOUSEBUTTONDOWN: if button1.isOver(pos) and x == 2: #print("score + 1") #I used the print statement just to make sure that the commands were working score += 1 #the answer is correct, so 1 is added to the score x += 1 #adding 1 to x, so that the next question is displayed after the user clicked on the display elif button1.isOver(pos) and x == 4: #print("score + 1") score += 1 x += 1 elif button2.isOver(pos) and x == 0: #print("score + 1") score += 1 x += 1 elif button2.isOver(pos) and x == 3: #print("score + 1") score += 1 x += 1 elif button2.isOver(pos) and x == 6: #print("score + 1") score += 1 x += 1 elif button3.isOver(pos) and x == 1: #print("score + 1") score += 1 x += 1 elif button4.isOver(pos) and x == 5: #print("score + 1") score += 1 x += 1 elif buttonQuit.isOver(pos): #quitting my game #user can change to hangman game #import Lava_Schollen_Spiel ### KB: I added the text for context, since I changed the game to play the Lava_Schollen_Spiel automatically after either winning, losing or quitting print("\n\nSo you changed your mind and you would rather search for the key? Alright...\n") running=False #pygame.quit() #sys.exit() elif buttonAgain.isOver(pos): #if the user presses the play again button, the game restarts x = 0 #x is set to 0 again, so that the first question is displayed again score = 0 #the score is set to 0 because the game starts over else: #print("score = 0") score += 0 #the answer wasn't correct, so the score stays the same x += 1 #1 is added to x to move on to the next question if x == 0: #question 1 textSurfaceObj = font2.render("Question 1: Which 200-year old brand of bourbon is the largest selling in the world?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "Blanton's") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "Jim Beam") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "Knob Creek") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "W.L. Weller") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 1: #question 2 textSurfaceObj = font2.render("Question 2: What is the most spoken language in the world?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "Spanish") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "English") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "Chinese") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "Hindi") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 2: #question 3 textSurfaceObj = font2.render("Question 3: What is the longest river in the world?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "Amazon") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "Mississippi") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "Río Grande") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "Volga") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 3: #question 4 textSurfaceObj = font2.render("Question 4: The Earth's air is composed of about what percentage of CO2?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "0.52%") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "0.04%") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "0.2%") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "0.98%") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 4: #question 5 textSurfaceObj = font2.render("Question 5: What is the largest country based on surface area?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "Russia") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "USA") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "Canada") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "China") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 5: #question 6 textSurfaceObj = font2.render("Question 6: What is the northernmost country in Europe?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "Sweden") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "United Kingdom") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "Finland") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "Norway") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 6: #question 7 textSurfaceObj = font2.render("Question 7: Which country is closest to Africa?", True, BLACK, WHITE) button1 = button(WHITE, 10, 300, 100, 50, "Greece") #answer 1 button1.draw(DISPLAYSURF, BLACK) button2 = button(WHITE, 10, 360, 100, 50, "Spain") #answer 2 button2.draw(DISPLAYSURF, BLACK) button3 = button(WHITE, 10, 420, 100, 50, "Malta") #answer 3 button3.draw(DISPLAYSURF, BLACK) button4 = button(WHITE, 10, 480, 100, 50, "France") #answer 4 button4.draw(DISPLAYSURF, BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) elif x == 7: if score < 4: #user loses #game over screen text1 = font1.render("YOU LOST", True, BLACK, WHITE) textSurfaceObj = font2.render("the door remains closed", True, BLACK, WHITE) DISPLAYSURF.blit(text1, textrect1) DISPLAYSURF.blit(textSurfaceObj, textrect2) #quit and play other minigame buttonQuit = button(WHITE, 450, 350, 100, 50, "find the key") buttonAgain.draw(DISPLAYSURF, BLACK) #play again buttonAgain = button(WHITE, 300, 350, 100, 50, "play again") buttonQuit.draw(DISPLAYSURF, BLACK) elif score >= 4: #player wins and moves 1 step forward text1 = font1.render("YOU WON!", True, BLACK, WHITE) font2 = pygame.font.Font("freesansbold.ttf", 28) textSurfaceObj = font2.render("now you can open the door", True, BLACK, WHITE) #when the player presses the key, Friederike's game starts text3 = font2.render("press a key to exit", True, BLACK, WHITE) textRectObj = (250, 250) textrect3 = (600, 500) DISPLAYSURF.blit(text1, textrect1) DISPLAYSURF.blit(textSurfaceObj, textRectObj) DISPLAYSURF.blit(text3, textrect3) pygame.display.update() fpsClock.tick(FPS) ### KB: Close pygame window after escaping the loop by either winning, losing or quitting pygame.quit() ### KB: Play the second minigame import Lava_Schollen_Spiel
2bce9f4b860cbd1306c5ba53ecd06f2e4d35d76f
stoneflyop1/fluent_py
/ch02/bisect_test.py
659
3.59375
4
import bisect import sys HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30] # ordered list NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31] # values to find def demo(bisect_fn): for needle in reversed(NEEDLES): position = bisect_fn(HAYSTACK, needle) print (position) offset = position * ' |' print('{0:2d} @ {1:2d} {2}{0:<2d}'.format(needle, position, offset)) if __name__ == '__main__': if sys.argv[-1] == 'left': fn = bisect.bisect_left else: fn = bisect.bisect print('DEMO:', fn.__name__) print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK)) demo(fn)
e261949bff60587a9afd753cdeb0a74a5e1eed06
sirmarcius/Media_Escolar_Python
/MediaEscolar.py
698
3.859375
4
print('##### Bem-vindo ao sistema de media escolar #####') for a in range(1,5): nome = str(input('\nAluno n°{} '.format(a))) nota1 = float(input('Entre com a nota n°{} '.format(1))) nota2 = float(input('Entre com a nota n°{} '.format(2))) nota3 = float(input('Entre com a nota n°{} '.format(3))) nota4 = float(input('Entre com a nota n°{} '.format(4))) media = (nota1 + nota2 + nota3 + nota4) / 4 print('A média do aluno {}'.format(a), 'é:',media) if media >=7: print('Aluno nº{}'.format(a),nome,'aprovado(a)!') else: print('Aluno nº{}'.format(a),nome,'reprovado(a)!') print('\nObrigado por utilizar nosso sistema!')
325db5e73be987d2984c6d80d6b0b3ed723e656d
gaojk/LeetCode_Answer
/strStr.py
708
3.59375
4
# coding=utf-8 # author='Shichao-Dong' # create time: 2018/8/30 ''' 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。 如果不存在,则返回 -1。 当 needle 是空字符串时我们应当返回 0 注意两个都为空的情况 ''' class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if haystack != "": return haystack.find(needle) else : if needle=="": return 0 else: return -1
0648cd2115fc9599c05d6217674336a363d7c716
jaxonjames123/Budgeting-Program
/Classes/bank.py
2,710
3.890625
4
from Database.db_functions import insert_bank, check_bank_exists, update_bank, load_bank class Bank: # Must change location to address, city, state, zip def __init__(self, name, location, bank_id=0): self._name = name self._location = location self._bank_id = bank_id def __str__(self): return f'\nBank: {self._name}\nLocation: {self._location}\nID: {self._bank_id}\n' @property def name(self): return self._name @property def location(self): return self._location @name.setter def name(self, name): self._name = name @location.setter def location(self, location): self._location = location @property def bank_id(self): return self._bank_id @bank_id.setter def bank_id(self, value): self._bank_id = value def new_bank(): bank_name = input('Bank Name: ').strip().upper() location = input('City: ').strip().upper() bank = Bank(bank_name, location) if not check_bank_exists(bank)[0]: insert_bank(bank) return bank else: print(f'The bank: {bank} has already been created') def change_bank_name(bank): updated_bank = Bank("", "") new_name = input('What is the bank\'s new name?: ').strip().upper() updated_bank.name = new_name updated_bank.location = bank.location updated_bank.bank_id = bank.bank_id update_bank(updated_bank) return updated_bank def change_bank_location(bank): updated_bank = Bank("", "") location = input('What is the new location of this bank? ').strip().upper() updated_bank.name = bank.name updated_bank.location = location updated_bank.bank_id = bank.bank_id update_bank(updated_bank) return updated_bank def get_bank(): knows_id = input('Do you know your bank\'s id? (Yes/No) ').strip().upper() if knows_id == 'YES' or knows_id == 'Y': bank_id = int(input('What is your bank\'s id? ')) bank_info = load_bank(bank_id) bank = Bank(bank_info[0], bank_info[1], bank_info[2]) return bank else: bank_name = input('What is your bank name? ').strip().upper() bank_location = input('Where is your bank located? ').strip().upper() bank = Bank(bank_name, bank_location) bank_info = check_bank_exists(bank)[1] if check_bank_exists(bank)[0]: bank = Bank(bank_info[0], bank_info[1], bank_info[2]) return bank else: print(f'{bank_name} with {bank_location} does not exist, please create a bank with these parameters.') def print_banks(banks): for _ in banks: bank = Bank(_[0], _[1], _[2]) print(bank)
08fed683f9ec31fdbf5667a9bf0572279474d59b
binarioGH/hotkeyspanish
/hotkeyspanish.py
975
3.53125
4
#-*-coding: utf-8-*- from keyboard import add_hotkey, wait, write import ctypes def CAPSLOCK_STATE(): hllDll = ctypes.WinDLL ("User32.dll") VK_CAPITAL = 0x14 return hllDll.GetKeyState(VK_CAPITAL) def spanishy(letter, dot=False): result = "" if letter == "a": result = "á" elif letter == "e": result = "é" elif letter == "i": result = "í" elif letter == "o": result = "ó" elif letter == "u": if dot: result = "ü" else: result = "ú" elif letter == "n": result = "ñ" if CAPSLOCK_STATE(): result = result.upper() print(result) write(result) def main(): add_hotkey("shift+a", spanishy, args=("a")) add_hotkey("shift+e", spanishy, args=("e")) add_hotkey("shift+i", spanishy, args=("i")) add_hotkey("shift+o", spanishy, args=("o")) add_hotkey("shift+u", spanishy, args=("u")) add_hotkey("shift+:+u", spanishy, args=("u", True)) add_hotkey("shift+n", spanishy, args=("n")) wait() if __name__ == '__main__': main()
730892d610b92cf5ad1a30fd05e6aba06a98abbf
eminkartci/PythonLectures
/Lecture1.py
231
3.984375
4
# print("Hello World") # x = "12" # y = 150 # print(x,y+y,sep="\n") # x = 50 # print(x,x**2) # i = 12 # for i in [1,3,5,6]: # print(i) # print(i) num1 = int(input("num1: ")) num2 = int(input("num2: ")) print(num1 + num2)
f9157203a4ba826e38826d6b898b6754e456a445
yanglinjie8823857/android-app-advertisement-spider-with-xposed
/android-app-advertisement-spider-with-xposed/android_mobile_creative_monitor.git 2/scripts/open.py
1,083
3.609375
4
#!/usr/bin/env python2 #-*-encoding:utf-8-*- import os,sys def listdir(dir,myfile): #myfile.write(dir + '\n') fielnum = 0 list = os.listdir(dir) #列出目录下的所有文件和目录 for line in list: filepath = os.path.join(dir,line) if os.path.isdir(filepath): #如果filepath是目录,则再列出该目录下的所有文件 #myfile.write(' ' + line + '//'+'\n') print "dir:"+filepath listdir(filepath, myfile) #for li in os.listdir(filepath): #if li.count('$') == 0: #myfile.write(dir+'//'+li + '\n') #fielnum = fielnum + 1 elif os.path: #如果filepath是文件,直接列出文件名 if line.count('$') == 0: print "file:"+line print myfile.write(dir+'/'+line + '\n') #fielnum = fielnum + 1 #myfile.write('all the file num is '+ str(fielnum)) dir = raw_input('please input the path:') myfile = open(dir+"/"+'list.txt','a') listdir(dir,myfile)
af0ec45b03cfc57a8082e0b69afaf66092366f35
noelis/coding_challenges
/decoder.py
656
4.28125
4
def decode(code): """ Decode the given string. A valid code is a sequence of numbers and letters. Each number tells you how many characters to skip before finding a valid letter. >>> decode("0h") 'h' >>> decode("0h1ae2bcy") 'hey' >>> decode("2hbc") 'c' """ decoded_word = "" for i in xrange(len(code)): if code[i].isdigit(): num = int(code[i]) decoded_word += code[i + num + 1] return decoded_word if __name__ == '__main__': import doctest print result = doctest.testmod() if not result.failed: print "All test cases passed." print
f6807454c0a8dec29d723647438207e1188a6d19
KoeusIss/holbertonschool-machine_learning
/supervised_learning/0x13-qa_bot/1-loop.py
388
3.78125
4
#!/usr/bin/env python3 """QA Bot module""" EXIT_KEYWORD = ('bye', 'goodbye', 'quit', 'exit') if __name__ == "__main__": while True: print('Q:', end=' ') question = input() if question.lower() in EXIT_KEYWORD: answer = 'Goodbye' print('A: {}'.format(answer)) break answer = '' print('A: {}'.format(answer))
6d5ce9574759c4b46beccfd8641c0a6ddce7f4a1
crl0636/Python
/code/MajorityElementII.py
526
3.6875
4
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ dict = {} for num in nums: if num not in dict: dict[num] = 1 else: dict[num] += 1 ans = [] for key, val in dict.iteritems(): if val > len(nums)//3: ans.append(key) return ans if __name__ == '__main__': so =Solution() print so.majorityElement([3,2,3])
0614e5184382f4215c6f350592b4de7f1e946d15
Lokhi-Torano/Projects
/Shuffler for Games.py
2,302
4
4
import random player_list=["lokhi","satheesh","ramya","aadhi","nithya","kishore","praveen","bharat"] print(" LUDO TALENT SHUFFLER") print(" THE PLAYERS ARE : \n") for name in range(0,len(player_list)): print(name+1,player_list[name],"\n") def add_players(): num_mem_add=int(input("enter number of players you wanna add (in numbers) : ")) for mem in range(0,num_mem_add): player=str(input("please enter the name(s) : ")) player_list.append(player) print("players added succesfully") shuffle() def print_players(team_1,team_2): print(" ") print("first team :\n") for i in range(0,len(team_1)): print("-+-+-",i+1,". ",team_1[i],"-+-+-\n") print("second team :\n") for j in range(0,len(team_2)): print("-+-+-",j+1,". ",team_2[j],"-+-+-\n") def remove_players(): num_mem_delete=int(input("enter number of players you wanna delete (in numbers) : ")) for mem in range(0,num_mem_delete): print(player_list) player=str(input("please enter the name(s) : ")) player_list.remove(player) print("players removed successfully") print(player_list) shuffle() def shuffle(): #check_list for 8 members if len(player_list)==8: #team should have 4 members #team_1_empty_list team_1=[] #team_2_empty_list team_2=[] #shuffling players random.shuffle(player_list) #adding team members to team_list for i in range(0,int(len(player_list)/2)): team_1.append(player_list[i]) for j in range(int(len(player_list)/2),int(len(player_list))): team_2.append(player_list[j]) print_players(team_1,team_2) if len(player_list)<8: player_req=8-len(player_list) print("please add ",player_req," for shuffling ....") add_players() if len(player_list)>8: excess_player=len(player_list)-8 print("please remove ",excess_player,"for shuffling .....") remove_players() print("Options :") print("1 . Shuffle") print("2 . Add players") print("3 . Delete players\n") mem_query=int(input("do you wanna Shuffle or Add players or Delete players? ")) if mem_query==1: shuffle() if mem_query==2: add_players() if mem_query==3: remove_players()
05a2d8e4d5ecc98c5c0b45e349e69f9611a9d268
sughosneo/dsalgo
/src/sorting/QuickSort.py
970
3.96875
4
# Still there is some problem which needs to be sorted out. # Ref : https://www.youtube.com/watch?v=SLauY6PpjW4 def quickSortWrapper(arr): quickSort(arr,0,len(arr)-1) def partition(arr,low,high,pivot): print(arr) while (low <= high) : while(arr[low] < pivot) : low += 1 while(arr[high] > pivot): high -= 1 if low <= high: arr[low],arr[high] = arr[high],arr[low] low += 1 high -= 1 # This is the further partition index. return low def quickSort(arr,start,end): # If left overlaps with right then stop it. if start < end : middle = (start + end) // 2 pivot = arr[middle] print(pivot) pi = partition(arr,start,end,pivot) quickSort(arr,start,pi-1) quickSort(arr,pi,end) if __name__ == '__main__': arr = [1,4,2,9,3,5] #arr = [9,2,6,4,3,5,1] quickSortWrapper(arr) print(arr)
ec878857dc1a5119c5a4e22edb11f095cf5e345b
tianweidut/CookBook
/algo/plan21/w3/lru_self_146.py
1,970
3.6875
4
class Deque: class Node: def __init__(self, key=0, val=0, prev=None, next=None): self.key = key self.val = val self.prev = prev self.next = next def __init__(self): self.head = Deque.Node() self.tail = Deque.Node() self.head.next = self.tail self.tail.prev = self.head self.size = 0 def remove(self, node): node.prev.next = node.next node.next.prev = node.prev self.size -= 1 def appendleft(self, key, val): node = Deque.Node(key=key, val=val) next = self.head.next self.head.next = node node.prev = self.head node.next = next next.prev = node self.size += 1 return node def pop(self): if self.size <= 0: raise Exception("deque is empty") prev = self.tail.prev self.remove(prev) return prev class LRUCache: def __init__(self, capacity: int): self.deque = Deque() self.map = {} self.capacity = capacity def get(self, key: int) -> int: if key not in self.map: return -1 self.deque.remove(self.map[key]) node = self.deque.appendleft(key, self.map[key].val) self.map[key] = node return node.val def put(self, key: int, value: int) -> None: if key in self.map: self.deque.remove(self.map[key]) node = self.deque.appendleft(key, value) self.map[key] = node return if len(self.map) >= self.capacity: rk = self.deque.pop() del self.map[rk.key] node = self.deque.appendleft(key, value) self.map[key] = node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
7c188aec7bd1e40304f27fbf7733be6148d83e75
jackmartin12/Projects
/Projects/Hypothesis testing.py
7,265
3.53125
4
#!/usr/bin/env python # coding: utf-8 # Jack Martin # # I399, Spring 2021 # # Independent Data Project, Part 2 # Overview: Counties in the United States are given a NCHS urbanization code based on their population. Lagest to smallest classes: Large Central Metro, Large fringe metro, medium metro, small metro, micropolitan, and non-core. # # #### Alpha = .01 for all 3 hypothesis # # Below is each hypothesis with the tests following it. # # ### Hypothesis #1 # # H0: The differences between the confirmed COVID-19 cases per 100,000 of a "Large central metro" county and the confirmed COVID-19 cases per 100,000 of a "Small metro" county are due to random chance. # # H1: The differences between the confirmed COVID-19 cases per 100,000 of a "Large central metro" county and the confirmed COVID-19 cases per 100,000 of a "Small metro" county are not due to random chance alone. # In[16]: import pandas as pd, numpy as np, seaborn as sns #read in the data data = pd.read_csv("1_county_level_confirmed_cases.csv") data.head() # In[17]: #find the mean of the cases per 100,000 of a Large Central Metro lcm = np.mean(data[data['NCHS_urbanization']=='Large central metro']['confirmed_per_100000']) #find the mean of the cases per 100,000 of a small metro sm = np.mean(data[data['NCHS_urbanization']=='Small metro']['confirmed_per_100000']) print("Mean confirmed cases per 100,000 for 'Large central metro' counties:", lcm) print("Mean confirmed cases per 100,000 for 'Small metro' counties::",sm) print() #get the difference which is our sample statistic statistic = sm - lcm print("Our sample statisic is:", statistic) # In[18]: #create function def simulate(): global data #shuffle the NCHS urbanuzation column nchs_shuffle = np.random.permutation(data['NCHS_urbanization']) data['NCHS Shuffled'] = nchs_shuffle #getting the confirmed cases per 100,000 from data, where the NCHS class is a Large central Metro mean_lcm = np.mean(data[data['NCHS Shuffled']=='Large central metro']['confirmed_per_100000']) #getting the confirmed cases per 100,000 from data, where the NCHS class is a Small Metro mean_sm = np.mean(data[data['NCHS Shuffled']=='Small metro']['confirmed_per_100000']) return mean_sm - mean_lcm # In[19]: sims = [] #run the function 10,000 times for i in range(10000): sims.append(simulate()) #what proportion of the sims yield a difference in averages >= the test statistic sims = np.array(sims) print("Our p-value is",len(sims[sims >= statistic])/10000) sns.histplot(sims) # ### Conclusion #1 # # Since our p-value is higher than our aplha value of .01, we accept the null hypothesis. The differences between the confirmed COVID-19 cases per 100,000 of a "Large central metro" county and the confirmed COVID-19 cases per 100,000 of a "Small metro" county are due to random chance. # ### Hypothesis #2 # # H0: The differences between the confirmed COVID-19 Deaths per 100,000 of a "Large central metro" county and the confirmed COVID-19 Deaths per 100,000 of a "Small metro" county are due to random chance. # # H1: The differences between the confirmed COVID-19 Deaths per 100,000 of a "Large central metro" county and the confirmed COVID-19 Deaths per 100,000 of a "Small metro" county are not due to random chance alone. # In[20]: #find the mean of the deaths per 100,000 of a Large Central Metro lcm = np.mean(data[data['NCHS_urbanization']=='Large central metro']['deaths_per_100000']) #find the mean of the deaths per 100,000 of a small metro sm = np.mean(data[data['NCHS_urbanization']=='Small metro']['deaths_per_100000']) print("Mean confirmed deaths per 100,000 for 'Large central metro' counties:", lcm) print("Mean confirmed deaths per 100,000 for 'Small metro' counties::",sm) print() statistic = sm - lcm print("Our sample statisic is:", statistic) # In[21]: #create function def simulate2(): global data #shuffle the NCHS urbanuzation column nchs_shuffle = np.random.permutation(data['NCHS_urbanization']) data['NCHS Shuffled'] = nchs_shuffle #getting the confirmed deaths per 100,000 from data, where the NCHS class is a Large central Metro mean_lcm = np.mean(data[data['NCHS Shuffled']=='Large central metro']['deaths_per_100000']) #getting the confirmed deaths per 100,000 from data, where the NCHS class is a small metro mean_sm = np.mean(data[data['NCHS Shuffled']=='Small metro']['deaths_per_100000']) return mean_sm - mean_lcm # In[22]: sims = [] #run the function 10,000 times for i in range(10000): sims.append(simulate2()) #what proportion of the sims yield a difference in averages >= the test statistic sims = np.array(sims) print("Our p-value is",len(sims[sims >= statistic])/10000) sns.histplot(sims) # ### Conclusion #1 # # Since our p-value is higher than our aplha value of .01, we accept the null hypothesis. The differences between the confirmed COVID-19 Deaths per 100,000 of a "Large central metro" county and the confirmed COVID-19 Deaths per 100,000 of a "Small metro" county are due to random chance. # ### Hypothesis #3 # # H0: The differences between the total COVID-19 Deaths of a "Large central metro" county and the total COVID-19 deaths of a "Non-core" county are due to random chance. # # H1: The differences between the total COVID-19 Deaths of a "Large central metro" county and the total COVID-19 deaths of a "Non-core" county are not due to random chance alone. # In[23]: #find the mean of the total deaths of a Large Central Metro lcm = np.mean(data[data['NCHS_urbanization']=='Large central metro']['deaths']) #find the mean of the total deaths of a Non-core nc = np.mean(data[data['NCHS_urbanization']=='Non-core']['deaths']) print("Mean total deaths for 'Large central metro' counties:", lcm) print("Mean total deaths for 'Non-core' counties::",nc) print() statistic = lcm - nc print("Our sample statisic is:", statistic) # In[24]: #create function def simulate3(): global data #shuffle the NCHS urbanuzation column nchs_shuffle = np.random.permutation(data['NCHS_urbanization']) data['NCHS Shuffled'] = nchs_shuffle #getting the total deaths from data, where the NCHS class is a Large central Metro mean_lcm = np.mean(data[data['NCHS Shuffled']=='Large central metro']['deaths']) #getting the total deaths from data, where the NCHS class is a Non-core mean_nc = np.mean(data[data['NCHS Shuffled']=='Non-core']['deaths']) return mean_lcm - mean_nc # In[26]: sims = [] #run simulation 10,000 times for i in range(10000): sims.append(simulate3()) #what proportion of the sims yield a difference in averages >= the test statistic sims = np.array(sims) print("Our p-value is",len(sims[sims >= statistic])/10000) sns.histplot(sims) # ### Conclusion #3 # # Our p-value is very small, but it is not 0 according to the histogram above. Since our p-value is smaller than our alpha value of .01, we reject our null hypothesis. The differences between the total COVID-19 Deaths of a "Large central metro" county and the total COVID-19 deaths of a "Non-core" county are not due to random chance alone. # In[ ]:
28e4e6e5d6df14d86bd6c6c565de3246f480969d
zeldaxlov3/Python4Fun
/guess.py
360
4.15625
4
#### What's the Number ? #### import random number = random.randrange(1, 100) your_answer = int(input("Your Answer: ")) if your_answer == number: print("You've guessed it right") else: print(f"Right answer is {number}, your answer {your_answer}") if your_answer > 100: print("The number is not in range, please type a number less than 100")
28694205fe4078a5466764b4b591ccb7fc02cc7e
qq76049352/python_workspace
/day05/字典的嵌套.py
278
3.734375
4
dic = { "name":"汪峰", "age":58, "wife": { "name":"国际章", "salay":"180000", "age":37 }, "children":[ {"name":"老大","age":18}, {"name":"老二","age":18} ] } # print(dic) print(dic["children"][1]["name"])
4d03ac0738f0d94462e8dcfebfa179c34b070fb2
cpt-nem0/leetcode
/shuffle_the_array.py
286
3.78125
4
def shuffle(nums, n): result = [] for i in range(n): result.append(nums[i]) result.append(nums[i+n]) return result if __name__ == "__main__": nums = list(map(int, input('> ').split())) n = int(input('> ')) print(shuffle(nums, n))
3b9ee581a4e0bb614151a6a17788e927c4fd0c95
client95/s.p.algorithm
/week_2/00_00클래스기본.py
561
3.53125
4
class JSS: def __init__(self): self.name = input("이름 : ") self.age = input("나이 : ") def show(self): print("나의 이름은 {}, 나이는 {}세입니다.".format(self.name, self.age)) a = JSS() a.show() class JSS2(JSS): def __init__(self): super().__init__() self.gender = input('성별 : ') def show(self): print("나의 이름은 {}, 성별은 {}, 나이는 {}세입니다.".format(self.name, self.gender, self.age)) a = JSS2() # a --> self __init__ 안에있는 내용 실행 a.show()
b0668b0b65baf37d236e072a9b70d55cca413c27
IoanaIlinca/University
/Fundamentals of programming/exam prep/exam.py
146
3.65625
4
a = lambda x: [x+1] b = a(5) # b = [2] print (b) c = lambda x: x + b d = c([1, 2]) a = 1 b = 3 print (a, b, c(4), d[2]) # 1, 3, 7, 2 print (d)
aea9b526917cfd144e682e610acce9676629ad37
zouyuanrenren/Leetcode
/src/Problems/Linked_List_Cycle.py
824
3.859375
4
''' Created on 17 Nov 2014 @author: zouyuanrenren ''' ''' Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? ''' ''' Can be done with two pointers: 1. one fast pointer; 2. one slow pointer; 3. the list has a cycle iff fast == slow at some point ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): fast = head slow = head if head == None: return False while fast != None and fast.next != None: fast = fast.next.next slow = slow.next if fast == slow: return True return False
be6490ae123de2d17c92923cda233f0b5ac3a9b0
bachns/LearningPython
/exercise12.py
238
4.375
4
# Write a Python program to print the calendar of a given month and year. # Note : Use 'calendar' module. import calendar year = int(input("Enter the year: ")) month = int(input("Enter the month: ")) print(calendar.month(year, month))
f64821f8624afe05127e4ec3356c31f31d775371
nastiakuzminih2011/macarrioni
/HW2.py
210
3.765625
4
a = int ( input() ) b = int ( input() ) c = int ( input() ) if ( a * b == c ) : print ( "YES" ) else : print ( "NO" ) if ( a // b == c ) : print ( "yes" ) else : print ( "no" )
37e3ebf9114af9da47aa037792c357411b1616a9
DabicD/Studies
/The_basics_of_scripting_(Python)/Exercise1.py
1,124
3.921875
4
# Exercise description: # # "Napisz funkcję, która znajdzie i zapisze do pliku wszystkie liczby z zadanego # przez użytkownika przedziału, których suma cyfr jest liczbą pierwszą." # ################################################################################## # Functions def sumOfDigits(number): sum = 0 while(number > 0): sum = sum + number % 10 number /= 10 number = int(number) return sum def isPrimeNumber(number): sum = sumOfDigits(number) # Check conditions if(sum > 2): for devider in range(2, sum): if((sum%devider) == 0): return False elif(sum == 1 or sum == 2): return True else: return False return True # MAIN try: x1 = int(input("Beginning:")) x2 = int(input("End:")) f = open("prime_number_list.txt", "w"); f.write("Your list:\n") for number in range(x1, x2+1): if(isPrimeNumber(number)): f.write(str(number)+"\n") print(number) f.close() except: print("Wrong input")
17a953c45b45c0c9a8ee553da337a932fcfc451e
MohammedFerozHussain/guvi1
/123.py
87
3.59375
4
#gfghghghg n1,m2=input().split() if(n1.find(m2)==-1): print("no") else: print("yes")
101d90eb09257f6f370482d008721916fb8ac56e
k4bir/PythonLab
/Lab_1/qn5.py
1,019
4.125
4
""" A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of students in each class, print the smallest possible number of desks that can be purchased. The program should read three integers: the number of students in each of the three classes, a, b and c respectively. In the first test there are three group. The first group has 20 students and thus needs 10 desks. The second group has 21 students, so they can get by with no fewer than 11 desks. 11 desks are also enough for the third group of 22 students. So, we need 32 desks in total. """ students_a=int(input("Enter the number of student in class a:")) students_b=int(input("Enter the number of student in class b:")) students_c=int(input("Enter the number of student in class c:")) if (students_b+students_c+students_a)%2!=0: bencha=(students_a+students_b+students_c)//2+1 print(f"the bench{bencha}") else: benchb=(students_a+students_b+students_c)//2 print(f"the bench required is {benchb}")
310491698c07cc8df6ce7bbad138a41ec0b5d378
zhaozongzhao/learngit
/Basic_grammar/高阶函数/闭包装饰器/常用的装饰器.py
3,992
3.9375
4
# 日志打印装饰器 def logger(func): """ :param func: 这是装饰器函数,参数 func 是被装饰的函数 :return: 返回内部函数的函数名 """ def wrapper(*args, **kw): print('主人,我准备开始执行:{} 函数了:'.format(func.__name__)) # 真正执行的是这行。 func(*args, **kw) print('主人,我执行完啦。') return wrapper @logger def add(x, y): print('{} + {} = {}'.format(x, y, x + y)) add(1, 3) # 时间计时器 import time def timer(func): def wrapper(*args, **kw): t1 = time.time() # 这是函数真正执行的地方 func(*args, **kw) t2 = time.time() # 计算下时长 cost_time = t2 - t1 print("花费时间:{}秒".format(cost_time)) return wrapper @timer def add_time(x, y): print('{} + {} = {}'.format(x, y, x + y)) add_time(1, 3) # 带参数的装饰器 def say_hello(contry): # contry装饰器的参数 def wrapper(func): # 传入装饰器的类 def deco(*args, **kwargs): if contry == "china": print("你好!") elif contry == "america": print('hello.') else: return # 真正执行函数的地方 func(*args, **kwargs) return deco return wrapper # 小明,中国人 @say_hello("china") def xiaoming(): pass # jack,美国人 @say_hello("america") def jack(): pass xiaoming() jack() # 不带参数的类装饰器 class logger(object): def __init__(self, func): # 函数在初始化操作触发,通过此方法我们可以定义一个对象的初始操作 self.func = func def __call__(self, *args, **kwargs): # 创建类并返回这个类的实例 print("[INFO]: the function {func}() is running..." \ .format(func=self.func.__name__)) return self.func(*args, **kwargs) @logger def say(something): print("say {}!".format(something)) say("hello") # 带参数的类装饰器: class logger1(object): def __init__(self, level='INFO'): # 接收传入参数 self.level = level def __call__(self, func): # 接受函数 def wrapper(*args, **kwargs): print("[{level}]: the function {func}() is running..." \ .format(level=self.level, func=func.__name__)) func(*args, **kwargs) return wrapper # 返回函数 @logger @logger1(level='WARNING') def say1(something): print("say {}!".format(something)) say1(123) # 使用偏函数与类实现装饰器 import functools class DelayFunc: def __init__(self, duration, func): self.duration = duration self.func = func def __call__(self, *args, **kwargs): print('Wait for {} seconds...'.format(self.duration)) time.sleep(self.duration) return self.func(*args, **kwargs) def eager_call(self, *args, **kwargs): print('Call without delay') return self.func(*args, **kwargs) def delay(duration): """ 装饰器:推迟某个函数的执行。 同时提供 .eager_call 方法立即执行 """ # 此处为了避免定义额外函数, # 直接使用 functools.partial 帮助构造 DelayFunc 实例 return functools.partial(DelayFunc, duration) @delay(duration=4) def add_delay(a, b): return a + b print(add_delay(3, 4)) # 装饰类的装饰器 instances = {} def singleton(cls): def get_instance(*args, **kw): cls_name = cls.__name__ print('===== 1 ====') if not cls_name in instances: print('===== 2 ====') instance = cls(*args, **kw) instances[cls_name] = instance return instances[cls_name] return get_instance @singleton class User: _instance = None def __init__(self, name): print('===== 3 ====') self.name = name User()
b7cb4d6cd00fc48acceb988733a0d3532263a330
pvargos17/pat_vargos_python_core
/week_03/labs/07_lists/Exercise_01.py
318
3.984375
4
''' Take in 10 numbers from the user. Place the numbers in a list. Using the loop of your choice, calculate the sum of all of the numbers in the list as well as the average. Print the results. ''' def user_sum(l): sum = 0 for n in l: sum += n print(sum) print(user_sum([1,2,3,4,5,6,7,8,9,10]))
09a24b889002640693c994c5df0edc31b3077071
AndreAmarante/user_management_sr
/user_management_platform_corrected.py
7,827
3.9375
4
import getpass import os class WrongFormatException(Exception): pass DATABASE = "private_users_database.txt" USER_LOGIN_ERR_MSG = "Username or password is incorrectw!" def create_account(): print("-------------Creating User-------------") username = input("Username: ") password = getpass.getpass(prompt="Password: ") password_repeat = getpass.getpass(prompt="Repeat password: ") if len(username)<3 or len(password)<3: print("Username or password too short!") elif ":" in username: print("Username contains invalid characters") elif ":" in password: print("Password contains invalid characters") elif password != password_repeat: print("Passwords don't match!") else: #Valid values inserted db_users = [] database_users = open(DATABASE, "r+") lines = database_users.readlines() for line in lines: db_user = line.split(":")[0] db_users.append(db_user) if username not in db_users: to_write = username + ":" + password + ":" + "0" + "\n" database_users.write(to_write) print("Username created successfully!") else: print("Username not available!") print("--------------------------") print() def do_login(): print("-------------Login-------------") username = input("Username: ") password = getpass.getpass(prompt="Password: ") success_in_login = False username_to_return = "" password_to_return = "" admin_to_return = False db_users = [] db_passwords = [] db_admins = [] database_users = open(DATABASE, "r") lines = database_users.readlines() for line in lines: line_pieces = line.strip("\n").split(":") db_user = line_pieces[0] db_pass = line_pieces[1] admin = line_pieces[2] db_users.append(db_user) db_passwords.append(db_pass) db_admins.append(admin) if username in db_users: index = db_users.index(username) if password != db_passwords[index]: print(USER_LOGIN_ERR_MSG) else: admin_value = db_admins[index] success_in_login = True username_to_return = username password_to_return = password if "1" in admin_value: admin_to_return = True print("Login done successfully!") else: print(USER_LOGIN_ERR_MSG) print("--------------------------") print() return success_in_login, username_to_return, password_to_return, admin_to_return def delete_user(): print("-------------Deleting user-------------") username = input("Username of user to delete: ") db_users = [] database_users = open(DATABASE, "r") lines = database_users.readlines() for line in lines: line_pieces = line.split(":") db_user = line_pieces[0] db_users.append(db_user) database_users.close() if username not in db_users: print("Username doesn't exist!") else: index = db_users.index(username) lines = lines[:index] + lines[index+1:] database_users = open(DATABASE, "w") for line in lines: database_users.write(line) print(username, " deleted from database!") def make_user_admin(): print("-------------Making user admin-------------") username = input("Username of user to make admin: ") db_users = [] db_admins = [] database_users = open(DATABASE, "r") lines = database_users.readlines() for line in lines: line_pieces = line.strip("\n").split(":") db_user = line_pieces[0] if(line_pieces[2]=="1"): db_admins.append(db_user) db_users.append(db_user) database_users.close() if username not in db_users: print("Username doesn't exist!") elif username in db_admins: print("User is already admin!") else: index = db_users.index(username) line_to_change = lines[index] line_to_change = line_to_change.strip("\n") line_to_change = line_to_change[:len(line_to_change)-1] line_to_change+="1\n" lines[index] = line_to_change database_users = open(DATABASE, "w") for line in lines: database_users.write(line) database_users.close() print(username, " is now admin!") def change_my_password(username, current_password,privilege): result = False print("-------------Changing password-------------") password = getpass.getpass(prompt="New password: ") password_repeat = getpass.getpass(prompt="Repeat new password: ") if len(password)<3: print("New password too short") elif password != password_repeat: print("Passwords don't match!") elif password == current_password: print("Password inserted is current password!") elif (":" in password): raise WrongFormatException("Password format invalid") else: found_user = False database_users = open(DATABASE, "r") lines = database_users.readlines() index_count = 0 for line in lines: line_pieces = line.strip("\n").split(":") db_user = line_pieces[0] if db_user == username: found_user = True line_to_change = db_user + ":" + password + ":" + line_pieces[2] + "\n" index_to_change = index_count break index_count+=1 database_users.close() if not found_user: print("User not found!") else: lines[index_to_change]=line_to_change database_users = open(DATABASE, "w") for line in lines: database_users.write(line) database_users.close() print("Password changed successfully!") result = True return result, password if __name__ == "__main__": option = "-1" list_of_options = ["0","1","2","3","4","5","6"] list_of_privileged_options = [] print("-------------Welcome-------------") print("-------Management Platform-------") current_available_options = [] logged_user = "" logged_user_pass = "" login = False privilege_granted = False #True for admins or temporarily for any user in the process of change password not_leave = True while(not_leave): while option not in list_of_options: if login: if privilege_granted: print("------Admin Options------") print("Create account - 1") print("Change my password - 3") print("Logout - 4") print("Delete a user - 5") print("Make user admin - 6") current_available_options = ["0","1","3","4","5","6"] else: print("------Options------") print("Change my password - 3") print("Logout - 4") current_available_options = ["0","3","4"] else: print("------Options------") print("Create account - 1") print("Login - 2") current_available_options = ["0","1","2"] print("Leave - 0") option = input("Selected option: ") print() if option not in current_available_options: print("Option not currently available") elif option == "0": print("Bye!") not_leave = False elif option == "1": create_account() elif option == "2": success, username, password_logged_user, admin = do_login() if success: login = True logged_user = username logged_user_pass = password_logged_user privilege_granted = admin print("Welcome ", logged_user, "!") elif option == "3": password = getpass.getpass(prompt="Current password: ") if password != logged_user_pass: print("Incorrect password!") else: if not privilege_granted: try: # Raise privilege privilege_granted = True success, new_pass = change_my_password(logged_user,logged_user_pass,privilege_granted) # Lower privilege privilege_granted = False except WrongFormatException as e: success = False print("Exception generated: ", e) # Lower privilege to prevent privilieges management vulnerability privilege_granted = False else: try: #Admin success, new_pass = change_my_password(logged_user,logged_user_pass,privilege_granted) except Exception as e: print("Exception generated: ", e) if success: logged_user_pass = new_pass elif option == "4": login = False privilege_granted = False logged_user = "" logged_user_pass = "" print("Logout sucessfull!") elif option == "5": delete_user() elif option == "6": make_user_admin() option="-1"
55083d7e224025491c47ac161debca9851e16de6
eternalseptember/CtCI
/04_trees_and_graphs/11_random_node/random_node_sol_1.py
1,900
3.78125
4
# Option 6 # O(log N), where N is the number of nodes. from random import * class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right self.size = 1 def get_random_node(self): if self.left is None: left_size = 0 else: left_size = self.left.size # Java's nextInt(n) returns a random number # between 0 (inclusive) and n (exclusive). # randint in inclusive for both boundaries. random_index = randint(0, self.size-1) # Testing """ print('Current node:\n\t', end='') print(self) print('Random index: {0}'.format(random_index)) """ if random_index < left_size: return self.left.get_random_node() elif random_index == left_size: return self else: return self.right.get_random_node() def insert_in_order(self, item): if item <= self.data: if self.left is None: self.left = Node(item) else: self.left.insert_in_order(item) else: if self.right is None: self.right = Node(item) else: self.right.insert_in_order(item) self.size += 1 def find(self, item): if item == self.data: return self elif item <= self.data: if self.left is not None: return self.left.find(item) else: return None elif item > self.data: if self.right is not None: return self.right.find(item) else: return None return None def __str__(self): left = None right = None if self.left is not None: left = self.left.data if self.right is not None: right = self.right.data return 'data: {0} left: {1} right: {2} size: {3}'\ .format(self.data, left, right, self.size) def print_tree(head): queue = [head] while len(queue) > 0: head_node = queue.pop(0) print(head_node) if head_node.left is not None: queue.append(head_node.left) if head_node.right is not None: queue.append(head_node.right)
bf261c126c95112a7553e1ac682ce3b603b0396e
vincesanders/cs-module-project-iterative-sorting
/src/iterative_sorting/iterative_sorting.py
4,547
4.15625
4
import random # TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr)): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) # Your code here for j in range(cur_index + 1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j # TO-DO: swap # Your code here if smallest_index is not cur_index: smallest_value = arr[smallest_index] arr[smallest_index] = arr[cur_index] arr[cur_index] = smallest_value return arr # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): swapped = True index = 0 swaps = 0 last_element = len(arr) - 1 while swapped: if index < last_element: # if we're not at the last element # compare item at index with index after if arr[index] > arr[index + 1]: # if item at index is larger, swap largerValue = arr[index] arr[index] = arr[index + 1] arr[index + 1] = largerValue # increment swaps swaps += 1 #increment index index += 1 else: # last index # decrement last element # we know the last element doesn't have to be checked again, # because we know it's the largest last_element -= 1 # if no swaps, swapped is False if swaps is 0: swapped = False else: index = 0 swaps = 0 return arr #Space complexity of bubble and selection sort are O(n), time complexity is (O)n^2 / 2, which is further simplified to O(n)^2 # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): # currently O(4n+k) # find k(maximum) while creating sorted_array sorted_array = [] for i in range(len(arr)): # O(n) sorted_array.append(0) if arr[i] > maximum: maximum = arr[i] elif arr[i] < 0: return "Error, negative numbers not allowed in Count Sort" # make count array with values of 0 count = [0 for x in range(maximum + 1)] # count number of occurances of each for i in range(len(arr)): # O(n) count[arr[i]] += 1 # get running sum for i in range(len(count)): #O(k) if i > 0: count[i] += count[i - 1] # placement for i in range(len(arr)): # O(n) sorted_array[count[arr[i]] - 1] = arr[i] count[arr[i]] -= 1 # copy sorted array to original array. # This step is only necessary if you want to modify the original array. for i in range(len(arr)): # O(n) arr[i] = sorted_array[i] # if you want to return a sorted copy of the origial array, # you can return sorted_array return arr def insertion_sort(arr): last_sorted_index = 0 while last_sorted_index < len(arr) - 1: if arr[last_sorted_index + 1] < arr[last_sorted_index]: # already sorted value = arr[last_sorted_index + 1] for i in range(0, last_sorted_index + 1): if value < arr[i]: new_value = arr[i] arr[i] = value arr[last_sorted_index + 1] = new_value value = new_value last_sorted_index += 1 return arr def count_sort_ver2(arr): # currently O(2n+2k) # make count array with values of empty array count = [] # count number of occurances of each # find k(maximum) while creating sorted_array for i in range(len(arr)): # O(n + k) if arr[i] < 0: return "Error, negative numbers not allowed in Count Sort" if arr[i] > len(count) - 1: # if number being added is out of range difference = arr[i] - len(count) for j in range(difference + 1): # Add difference empty arrays to count count.append([]) count[arr[i]].append(arr[i]) # add the arr[i] to the array that corresponds to its value sorted_array = [] # get running sum for i in range(len(count)): #O(n) # cycle through count adding all the values within the array at the current index to the sorted array. # This means if there were repeats of the same value, they would be added together. sorted_array.extend(count[i]) # O(k) return sorted_array
85db9d90fdd9e8e74615b918f3043a6f7abb7817
qiujiandeng/-
/python1基础/day02/if_express.py
186
3.75
4
# if_express.py # 商场促销,满100减20 money = int(input("请输入商品总金额:")) pay = money - 20 if money >=100 else money print("您需要支付:",pay,'元')
e4816c83a06d2b7cf951144816c2b0af69bc0a43
deadpool10086/love-python
/Tensorflow2.0/CheckCode/generater.py
2,935
3.53125
4
""" makeVerification.py 文件""" import random import os from PIL import Image,ImageDraw,ImageFont,ImageFilter # 设置图片宽高 width = 60 height = 20 """ """ def getRandomColor(is_light = True): """ 生成随机颜色 :param is_light: 为了设置浅色和深色 :return: (r, g, b) """ r = random.randint(0, 127) +int(is_light)* 128 g = random.randint(0, 127) +int(is_light)* 128 b = random.randint(0, 127) +int(is_light)* 128 return (r, g, b) # 这里全部数据 def getRandomChar(): random_num = str(random.randint(0, 9)) # 数字 0~9 random_lower = chr(random.randint(97, 122)) # 小写字母a~z random_upper = chr(random.randint(65, 90)) # 大写字母A~Z random_char = random.choice([random_num, random_upper, random_lower]) return random_char def drawLine(draw): """ 随机生成4个干扰线,然后每个设置随机颜色 """ for i in range(4): x1 = random.randint(0, width) x2 = random.randint(0, width) y1 = random.randint(0, height) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=getRandomColor(is_light=True)) def drawPoint(draw): """ 随机生成80个干扰点,然后每个设置随机颜色 """ for i in range(80): x = random.randint(0, width) y = random.randint(0, height) draw.point((x,y), fill=getRandomColor(is_light=True)) def createImg(folder): # 随机生成一个颜色为背景色颜色 bg_color = getRandomColor(is_light=True) # 创建一张随机背景色的图片 img = Image.new(mode="RGB", size=(width, height), color=(255,255,255)) # 获取图片画笔,用于描绘字 draw = ImageDraw.Draw(img) # 修改字体 font = ImageFont.truetype(font="arial.ttf", size=18) # 保存图片的名字 file_name = '' # 这里生成4位数字,就循环4次 for i in range(4): # 随机生成4种字符+4种颜色 random_txt = getRandomChar() txt_color = getRandomColor(is_light=False) # 避免文字颜色和背景色一致重合 while txt_color == bg_color: txt_color = getRandomColor(is_light=False) # 根据坐标填充文字 draw.text((2 + 15 * i, 0), text=random_txt, fill=txt_color, font=font) file_name +=random_txt # 画干扰线和点 # drawLine(draw) drawPoint(draw) print(file_name) # 打开图片操作,并保存在当前文件夹下 with open("./{}/{}.png".format(folder,file_name), "wb") as f: img.save(f, format="png") if __name__ == '__main__': # 创建num张验证码 num = 1000 # 创建train和test文件夹 os.path.exists('train') or os.makedirs('train') os.path.exists('test') or os.makedirs('test') # 每个文件夹创建num个 for i in range(num): createImg('train') createImg('test')
f5c65c801a38e696976db85ca3a79fbb30aeecb1
canattofilipe/python3
/basico/dicionarios/dicionarios_pt2.py
566
4.28125
4
""" Exemplos de dicionários em Python3. """ # criando um dicionario. pessoa = {'nome': 'Alberto', 'idade': 43, 'cursos': [ 'React', 'Python']} # sobreescreve um valor da lista. pessoa['idade'] = 44 # adiciona um elemento a valor do tipo lista. pessoa['cursos'].append('Angular') print(pessoa) # le um valor do dicionario e remove do dicionario. print(pessoa.pop('idade')) print(pessoa) # adiciona pares no dicionario. pessoa.update({'idade': 40, 'Sexo': 'M'}) print(pessoa) # remove um par de chave ({ }) do dicionario. del pessoa['cursos'] print(pessoa)
06302ea5d820b1a609bdffb3084f02a6be39d528
takayuk/basset
/lib/wordlist.py
985
3.6875
4
#!/home/takayuk/local/bin/python # encoding: utf-8 # coding: utf-8 class Wordlist(object): def __init__(self): self.wordlist = {} self.__wordid = 1 def __iter__(self): for word, info in self.wordlist.items(): yield (word, info) def keys(self): return self.wordlist.keys() def append(self, word): if not word in self.wordlist: #self.wordlist.setdefault(word, [self.__wordid, 1]) self.wordlist.setdefault(word, self.__wordid) self.__wordid += 1 def wordid(self, word): try: return self.wordlist[word] except KeyError: return None if __name__ == "__main__": import sys args = sys.argv wordlist = Wordlist() wordlist.append("a") wordlist.append("b") wordlist.append("c") wordlist.append("d") print(wordlist.wordid("a")) print(wordlist.keys()) for word in wordlist: print(word)
2b1e27585d2bc7ef169a4834af46037b87f1f802
ShakarSaleem/Python-Tic-Tac-Toe-Game
/main.py
1,278
3.765625
4
from gameboardfixed_st import GameBoardFixed from player_st import Player def main(): gboard = GameBoardFixed(3) p1 = Player("X", gboard) # create player 1 object p2 = Player("O", gboard) # create player 2 object # place players 1 and 2 in tuple for turn based game. players_lst = (p1, p2) winner = False gboard.show_board_fixed() # show empty grid at the beginning of the game while (winner == False): # This is to allow players to take turns. # The game begins with the player at index zero in the tuple, # When the player completes its turn, the next player in the tuple will be asked to play. # If there is no winner, this continue until reaching the end of the players list, and then we start again # from teh begging of the list. for p in players_lst: p.play() gboard.show_board_fixed() # After each move, the board is shown on the screen winner = gboard.check_winner() # The board will check after each move, if any player has won the game if winner == True: # Show current player's symbol as Winner, # and terminate the game print() print ("Player %s is the Winner!" % p.get_player_symbol()) break # end the game and announce the winner. main()
8d79491262717a5820d209d56d8ed1457d849722
iammateus/challenges
/challenge.3.py
1,944
3.765625
4
# Largest Triple Products # You're given a list of n integers arr[0..(n-1)]. You must compute a list output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive), output[i] is equal to the product of the three largest elements out of arr[0..i] (or equal to -1 if i < 2, as arr[0..i] then includes fewer than three elements). # Note that the three largest elements used to form any product may have the same values as one another, but they must be at different indices in arr. # Signature # int[] findMaxProduct(int[] arr) # Input # n is in the range [1, 100,000]. Each value arr[i] is in the range [1, 1,000]. # Output # Return a list of n integers output[0..(n-1)], as described above. # Example 1 # n = 5 arr = [1, 2, 3, 4, 5] output = [-1, -1, 6, 24, 60] # The 3rd element of output is 3*2*1 = 6, the 4th is 4*3*2 = 24, and the 5th is 5*4*3 = 60. # Example 2 # n = 5 arr = [2, 1, 2, 1, 2] output = [-1, -1, 4, 4, 8] # The 3rd element of output is 2*2*1 = 4, the 4th is 2*2*1 = 4, and the 5th is 2*2*2 = 8. def findMaxProduct(arr): result = [] for count in range(len(arr)): if count < 2: result.append(-1) continue biggestDual = [] for countPassed in range(count): for countBiggest in range(len(biggestDual)): biggest = biggestDual[countBiggest] if countPassed != biggest and arr[countPassed] > arr[biggest]: if countBiggest == 0: if len(biggestDual) < 2: biggestDual.append(biggest) elif arr[biggest] > arr[biggestDual[1]]: biggestDual[1] = biggest biggestDual[countBiggest] = countPassed else: if len(biggestDual) < 2: biggestDual.append(countPassed) elif arr[countPassed] > arr[biggestDual[1]]: biggestDual[1] = countPassed break else: biggestDual.append(countPassed) result.append((arr[count] * arr[biggestDual[0]] * arr[biggestDual[1]])) return result print( str( findMaxProduct( [1, 2, 3, 4, 5] ) ) )
0c4d06fd38ab304c074bbb6dfff27f57d8cb00e1
sparshg05/Testing
/question2b.py
289
3.6875
4
n=int(input('enter a number between 5-10: ')) l=[] for i in range(0,n): l.append(input()) #for k in range(0,n): # print(l[k]) count=0 for j in range(0,n): if (l[j] == 5): count=count+1 print('The number 5 is',count,'times in the above list.')
bfef0b3ce417960debe1c650fc4b16918d8bb518
CharlieButterworth/kennel2
/customers/request.py
911
3.953125
4
CUSTOMERS = [ { "email": "cb@gmail.com", "password": "cb", "name": "chuck Butters", "id": 1 }, { "email": "t@gmail.com", "password": "cam", "name": "Tyler tyler", "id": 2 }, { "email": "cv@df", "password": "dfdf", "name": "cb cv", "id": 3 } def get_all_locations(): return CUSTOMERS # Function with a single parameter def get_single_customer(id): # Variable to hold the found location, if it exists requested_customer = None # Iterate the LOCATIONS list above. Very similar to the # for..of loops you used in JavaScript. for customer in CUSTOMERS: # Dictionaries in Python use [] notation to find a key # instead of the dot notation that JavaScript used. if customer["id"] == id: requested_customer = customer return requested_customer
e6dd8cf1d683f6d6d3ffebe46e9cb602f8ef5e8e
tharinduHND/HDCN181P022
/hw.py
549
4.25
4
total = 0.0 # Loop continuously using while loop while True: # Get the input using input. number = input("Enter number here :") # If the user press enter without put value if number == '': # ...break the loop. break # Else try to add the number to the total. try: # This is the same as total = total + float(number) total = total + float(number) # But if input was not valid except ValueError: # ...continue the loop. continue print("Total is", total)
f3922815b296e63ea3f9d53e52fbebda549aec59
jrother91/Mensaauskunft
/mensapagescraper/mensapagescraper.py
5,696
3.546875
4
# -*- coding: utf-8 -*- import requests, bs4, codecs, json import codecs import os import glob from datetime import datetime, timedelta def mensa_download(url): """ Grabs the html code of this week's mensa plan returns it as a bs4 object """ response = requests.get(url) html = response.text htmlSoup = bs4.BeautifulSoup(html, 'lxml') return htmlSoup def getDiv(htmlSoup): """ returns the main div of a html object """ #print(htmlSoup) divElem = htmlSoup.select('div')[35] return divElem def getNextWeek(divElem): """ takes the main div of the original website extracts the html for next week's site, grabs it and returns the soup """ #Öffnungszeiten #time = divElem.select('p')[1] #Link für die nächste Woche return ("http://www.studierendenwerk-bielefeld.de" + divElem.select('a')[93].get("href")) def extractInfo(divElem): """ takes the main div of a mensa page extracts all needed info: dates that have food, names of the food applies some formatting returns information as dictionary """ #Wochentage (diese Woche) days = divElem.select('h2')[1:6] #Liste mit den Daten der aktuellen Woche (amerikanische Schreibweise) dates = [] for i in days: date = str(i).split()[2] dates.append(date[-4:] + '-' + date[3:5] + '-' + date[0:2]) #alle Informationen zu den Menüs (5 Tage, Montag - Freitag) mensaPlan = divElem.find_all('div', class_='mensa plan')[:5] #Listen mit Tagesmenü und vegetarisches Menü menu = [] beilagen = [] menuveg = [] beilagenveg = [] menu_vit = [] for i in range(5): menus = mensaPlan[i].find_all('tbody')[0] menu.append(menus.find_all('tr', class_='odd')[0].find_all('p')[1]) beilagen.append(menus.find_all('tr', class_='odd')[0].find_all('p')[3]) menuveg.append(menus.find_all('tr', class_='even')[0].find_all('p')[1]) beilagenveg.append(menus.find_all('tr', class_='even')[0].find_all('p')[3]) menu_vit.append(menus.find_all('tr', class_='odd')[1].find_all('p')[1]) #Dictionary mit den Tagen als key und die Menüs als Value food = dict() #Dictionary of Dictionaries (key: Datum -> key: Tagesmenü -> value: Gericht Tagesmenü | key: Datum -> key: vegMenü -> value: Gericht vegetarisches Menü) for i in range(5): food[dates[i]] = {} m = menu[i].encode('utf-8') mveg = menuveg[i].encode('utf-8') b = beilagen[i].encode('utf-8') bveg = beilagenveg[i].encode('utf-8') mvit = menu_vit[i].encode('utf-8') m = bs4.BeautifulSoup(m, 'lxml') mveg = bs4.BeautifulSoup(mveg, 'lxml') b = bs4.BeautifulSoup(b, 'lxml') bveg = bs4.BeautifulSoup(bveg, 'lxml') mvit = bs4.BeautifulSoup(mvit, 'lxml') for tag in m.find_all('sup'): tag.decompose() for tag in mveg.find_all('sup'): tag.decompose() for tag in b.find_all('sup'): tag.decompose() for tag in bveg.find_all('sup'): tag.decompose() for tag in mvit.find_all('sup'): tag.decompose() food[dates[i]]['main_menu'] = m.find('p').getText() food[dates[i]]['veg_menu'] = mveg.find('p').getText() beilage = b.find('p').getText().replace(' oder', ',').split(',') beilage_veg = bveg.find('p').getText().replace(' oder', ',').split(',') food[dates[i]]['side_dishes'] = list(set(beilage + beilage_veg)) food[dates[i]]['mensa_vit'] = mvit.find('p').getText() return(food) def saveToJson(date, food): """ saves the food dictionary as a json file """ with codecs.open(date + '.json', 'w', 'utf-8') as fp: json.dump(food, fp, sort_keys = True) def loadFromJson(date): """ loads the food dictionary from a json file """ with codecs.open(date + '.json', 'r', 'utf-8') as fp: food = json.load(fp) return food def findTime(food): """ finds the earliest day in the food dictionary """ keys = sorted(food.keys()) return keys[0] def loadNewestJson(): """ finds the name of the newest json file """ try: newest = max(glob.iglob('*.[Jj][Ss][Oo][Nn]'), key=os.path.getctime) return newest except: pass def nDaysAgo(): """ finds the date of the last monday """ n = datetime.now().weekday() date_N_days_ago = datetime.now() - timedelta(days=n) date_N_days_ago = str(date_N_days_ago).split()[0] return date_N_days_ago def getMensaInfo(): """ grabs the mensa plans for the current and next week from the website returns a dictionary that contains the main menus for each day that has them (date (main_menu: name, veg_menu:name)) """ date = nDaysAgo() if(date + '.json' == loadNewestJson()): food = loadFromJson(date) return food else: mensa = mensa_download('http://www.studierendenwerk-bielefeld.de/essen-trinken/essen-und-trinken-in-mensen/bielefeld/mensa-gebaeude-x.html') div_this_week = getDiv(mensa) food_this_week = extractInfo(div_this_week) mensa_next_url = getNextWeek(mensa) mensa_next = mensa_download(mensa_next_url) div_next_week = getDiv(mensa_next) food_next_week = extractInfo(div_next_week) food = dict(food_this_week.items() + food_next_week.items()) date = findTime(food) saveToJson(date, food) return food if __name__ == '__main__': #print(type(getMensaInfo()['2017-09-14']['veg_menu'])) print(getMensaInfo())
bdd4ec7412db67f93412281f1121ddac29916d60
AYYYang/little-games
/mars_rover.py
638
3.578125
4
import sys """ This is a game to explore Mars. Mars is represented in an nxn grid/matrix. At some coordiates (x,y), where x,y is {0,n-1}; there are some special sites for exploration. The main character is a rover that can: 1. move A units in 4 directions 2. explore and find out whether the destination is an exploration site Rules: 1. An exploration site becomes a regular site after the rover explores it. 2. the rover has limited fuel, and the game ends when it runs out 3. the game also ends if the rover just gives up triggered by QUIT command at anytime """ class Rover: pass class Mars: pass class Site: pass
445890c285dce6c643a961a2c9b9eb5f7753a448
AndreaCrotti/my-project-euler
/prob_30/prob_30.py
308
4.1875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # The maximum number must be 5 * 9^5 BOUND = 5 * 9**5 def to_power(n): "Return the sum of the 5th power of each digit" digits = (int(x) for x in str(n)) return sum(x**5 for x in digits) print(sum(x for x in range(2, BOUND) if to_power(x) == x))
2e078352482d188e86b590dd9ea551da2f4e825c
lanicow/uch
/magic/python/appendAllFilesWithColHeaders.py
2,160
3.5625
4
# Purpose: reads all .txt files in a folder to create a single data file to be imported into a SQL table. # Author: randy suinn # python: v3.x # Notes: # -- assumes the 1st line (ie line 1) of each input file is the column header. # -- only .txt files will be read. import os the_input_file_list = [] the_folder_path = r'C:\rsuinn\projects\meditechMagic\output\HR' # the full path to the folder containing the .txt files to be read. def get_file_list(): the_file_list = os.listdir(the_folder_path) # get a list of files and folder names for the_file in the_file_list: the_full_path = os.path.join(the_folder_path, the_file) if os.path.isdir(the_full_path): continue # ignore the folders if the_file.endswith('.txt'): the_input_file_list.append(the_full_path) return the_input_file_list # end function the_input_file_list = get_file_list() if len(the_input_file_list) > 0: # the full path to a .txt file which will contain all the data from the input files. with open(r'C:\rsuinn\projects\meditechMagic\output\HR-sqlImportFile\sqlImport.txt', 'w') as the_output_file: # append all file's data to this single file. the_num_files_read = 0 the_have_column_header = False for the_full_path in the_input_file_list: the_num_files_read += 1 # the_full_path = os.path.join(the_folder_path, the_file) with open(the_full_path, 'r') as the_input_file: the_line_count = 0 for the_line in the_input_file: the_line_count += 1 # ignore the 1st line (the column headers) if it's already been written to the output file. if the_have_column_header and the_line_count == 1: # assumes the 1st line is the column header in every file. continue the_have_column_header = True the_output_file.write( the_line ) print('FILE:', the_full_path, '| LINES READ:', the_line_count) print ('TOTAL FILES READ:', the_num_files_read)
16f4aad06825b2fe75523740c4687954b025b549
vishalpmittal/practice-fun
/funNLearn/src/main/java/dsAlgo/leetcode/P0xx/P015_3Sum.py
1,622
3.75
4
""" Tag: math, array Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [[-1, 0, 1], [-1, -1, 2]] """ class P015_3Sum(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums or len(nums) < 2: return [] res = [] # sort so to skip duplicates nums.sort() for curr in range(len(nums)-2): # Skip for duplicates of curr if curr > 0 and nums[curr] == nums[curr-1]: continue # start two pointers one from curr's immediate right and # one from last element of array l, r = curr+1, len(nums)-1 while l < r: s = nums[curr] + nums[l] + nums[r] if s < 0: l +=1 elif s > 0: r -= 1 else: res.append((nums[curr], nums[l], nums[r])) # Skip for duplicates of l and r while l < r and nums[l] == nums[l+1]: l += 1 while l < r and nums[r] == nums[r-1]: r -= 1 l += 1; r -= 1 return res def test_code(): obj = P015_3Sum() obj.threeSum([-1, 0, 1, 2, -1, -4]) test_code()
5228f50262d6f4b0202cdf329252b174ea836f7f
JeromeEngena/python-prax
/age.py
155
4.21875
4
age = input('How old are you?\n') age = int(age) if age >12 and age <20: print("Teenager") elif age >=20: print("Adult") else: print("Infant")
8651b8ee6fce4286aacad4c3c93d1506d072dc38
daniela2001-png/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
956
4.15625
4
#!/usr/bin/python3 """ define a private instance object and then use raise for errors that can pass """ class Square: """ incilaizo mis instancias en el init """ def __init__(self, size=0): """ evaluo errores con raise """ if (type(size) is not int): raise TypeError("size must be an integer") elif (size < 0): raise ValueError("size must be >= 0") else: self.__size = size """ class Square: def __init__(self, size=0): if (type(size) is int): if (size >= 0): self.__size = size raise ValueError("value error") raise TypeError("TypeError") class Square: def __init__(self, size=0): try: self.__size = size except ValueError: print("error1") except ValueError: print("error2") else: self.__size = size """
126da926361b964f82301ff047a2777961c20d81
AlexaVega-lpsr/class-samples
/drawTriPattern.py
655
3.734375
4
import turtle def drawtriangle(nyeh): nyeh.forward(10) nyeh.right(120) nyeh.forward(10) nyeh.right(120) nyeh.forward(10) nyeh.right(120) def drawTri(papy): hill = 4 while hill > 0: drawtriangle(papy) papy.penup() papy.forward(20) papy.pendown() hill = hill - 1 def drawtripattern1(heeh): o = 0 while o < 3: heeh.penup() heeh.forward(30) heeh.pendown() drawtriangle(heeh) o = o + 1 def drawtripattern(sans): bone = 0 while bone < 6: drawTri(sans) sans.penup() sans.goto(0,0) sans.right(90) sans.pendown() sans.right(30) bone = bone + 1 heh = turtle.Turtle() drawtripattern(heh) turtle.exitonclick()
303762c12176b85421d72a4789f92c8d40902cdc
HallidayJ/comp61542-2014-lab
/src/comp61542/sorter.py
4,554
3.734375
4
class Sorter: def sort_asc(self, data, index): # return data.sort(key=lambda tup: tup[index]) for idx in range(0, len(data)): tmpAuthor = list(data[idx]) # Split the name into an array # print tmpAuthor[0] nameArray = str(tmpAuthor[0]) .split(" ") # print len(nameArray) if len(nameArray) >1: # The name is the first item in the list name = nameArray[0] # Position of surname is the last item in the list surnamePos = len(nameArray) - 1 # Get surname surname = nameArray[surnamePos] # Join the surname+name using "_" toSortName = "_".join([surname,name]) # print toSortName # Make the first entry the newly created joined name nameArray[0] = toSortName # Remove the surname nameArray.pop() # Join the new name tmpAuthor[0] = " ".join(nameArray) data[idx] = tuple(tmpAuthor) # print data[idx][0] data = sorted(data, key=lambda tup: tup[0]) if index != 0: data = sorted(data, key=lambda tup: tup[index]) for idx in range(0, len(data)): tmpAuthor = list(data[idx]) # Split the name using spaces nameArray = str(tmpAuthor[0]).split(" ") # print nameArray # Take the Join surname_name nameSurName = nameArray[0] # Split them using "_" tmpArray = nameSurName.split("_") if len(tmpArray) > 1: # Take surname and name from list surName = tmpArray[0] name = tmpArray[1] # Name takes it's correct position nameArray[0] = name # Surname goes last nameArray.append(surName) # Join the name and place it in the author data tmpAuthor[0] = " ".join(nameArray) data[idx] = tuple(tmpAuthor) # print author return data def sort_desc(self, data, index): for idx in range(0, len(data)): tmpAuthor = list(data[idx]) # print tmpAuthor # Split the name into an array nameArray = str(tmpAuthor[0]).split(" ") # print "after split" if len(nameArray) > 1: # The name is the first item in the list name = nameArray[0] # Position of surname is the last item in the list surnamePos = len(nameArray) - 1 # Get surname surname = nameArray[surnamePos] # Join the surname+name using "_" toSortName = "_".join([surname,name]) # print toSortName # Make the first entry the newly created joined name nameArray[0] = toSortName # Remove the surname nameArray.pop() # Join the new name tmpAuthor[0] = " ".join(nameArray) # print author[0] data[idx] = tuple(tmpAuthor) data = sorted(data, key=lambda tup: tup[0], reverse=True) if index != 0: data = sorted(data, key=lambda tup: tup[index], reverse=True) for idx in range(0, len(data)): tmpAuthor = list(data[idx]) # Split the name using spaces nameArray = str(tmpAuthor[0]).split(" ") # Take the Join surname_name nameSurName = nameArray[0] # Split them using "_" tmpArray = nameSurName.split("_") if len(tmpArray) > 1: # Take surname and name from list surName = tmpArray[0] name = tmpArray[1] # Name takes it's correct position nameArray[0] = name # Surname goes last nameArray.append(surName) # Join the name and place it in the author data tmpAuthor[0] = " ".join(nameArray) # print author[0] data[idx] = tuple(tmpAuthor) return data
3800359a11e37189ddb685b629d00b83b7d856a0
Alex-Beng/ojs
/FuckLeetcode/2. 两数相加.py
1,073
3.625
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: l1_ptr = l1 l2_ptr = l2 res_ptr = None res_head = None carry_in = 0 while True: l1_val = 0 if l1_ptr is None else l1_ptr.val l2_val = 0 if l2_ptr is None else l2_ptr.val t_sum = l1_val + l2_val + carry_in t_node = ListNode(t_sum%10) carry_in = t_sum//10 if res_ptr is None: res_ptr = t_node res_head = t_node else: res_ptr.next = t_node res_ptr = res_ptr.next l1_ptr = l1_ptr.next if not l1_ptr is None else l1_ptr l2_ptr = l2_ptr.next if not l2_ptr is None else l2_ptr if l1_ptr is None and l2_ptr is None and carry_in == 0: break return res_head
f7e80582d30d980d991f0f5fdabc9a83e1053f67
tmaria17/learn_python_the_hard_way
/ex11.py
323
3.984375
4
print("How old are you?", end='') age = input() print("How tall are you?", end= '') height = input() print("How much do you weigh?", end = '') weight = input() print(f"So you're {age} old, {height} tall and {weight} heavy.") print("What is your cat's name?", end='') cat = input() print(f"And your cat's name is {cat}")
a2f8fdc8c4c4cc66b89b8e0c1e82cf8d564f7fd8
kirtigarg11/guvi
/hunter/set11/6.py
176
3.53125
4
a = input() b = input() x = min(len(a), len(b)) for i in range(x): print(b[i]+a[i]) for i in range(x, len(a)): print(a[i]) for i in range(x, len(b)): print(b[i])
7d471985785cba59fe8baab8cdf1f53a3b250cf2
kamata1729/the-cryptopals-crypto-challenges
/set2/c15.py
1,024
3.765625
4
class InvalidPaddingError(Exception): pass def is_valid_padding(input: bytes, max_pad_length: int = 16): pad_size = input[-1] if pad_size >= max_pad_length-1: return True try: for i in range(1, pad_size): if input[-i] != pad_size: raise InvalidPaddingError('invalid padding byte was found') except InvalidPaddingError as e: raise e return True if __name__ == '__main__': sample1 = b'ICE ICE BABY\x04\x04\x04\x04' sample2 = b'ICE ICE BABY\x05\x05\x05\x05' sample3 = b'ICE ICE BABY\x01\x02\x03\x04' print('input: {}'.format(sample1)) try: print(is_valid_padding(sample1)) except InvalidPaddingError: print(False) print('input: {}'.format(sample2)) try: print(is_valid_padding(sample2)) except InvalidPaddingError: print(False) print('input: {}'.format(sample3)) try: print(is_valid_padding(sample3)) except InvalidPaddingError: print(False)
5e911c1db061d043a9ef83ca641616ee3049ba96
carodewig/advent-of-code
/advent-py/2015/day_21.py
2,904
3.578125
4
""" day 21: rpg simulator 20XX """ from collections import namedtuple import itertools Equipment = namedtuple("Equipment", ["cost", "damage", "armor"]) class Character: def __init__(self, hp, damage, armor): self.max_hp = hp self.hp = hp self.damage = damage self.armor = armor def net_damage(self, other_char): return max(1, self.damage - other_char.armor) def reset(self): self.hp = self.max_hp def battle(player, boss): try: # returns bool for whether player wins battle player_damage = player.net_damage(boss) boss_damage = boss.net_damage(player) turn = 0 while player.hp > 0 and boss.hp > 0: if turn % 2 == 0: boss.hp -= player_damage elif turn % 2 == 1: player.hp -= boss_damage turn += 1 return player.hp > 0 finally: player.reset() boss.reset() def equipment_permutations(): for (num_weapons, num_armor, num_rings) in itertools.product([1], [0, 1], [0, 1, 2]): for (weapon, armor, rings) in itertools.product( itertools.permutations(WEAPONS, num_weapons), itertools.permutations(ARMORS, num_armor), itertools.permutations(RINGS, num_rings), ): yield weapon + armor + rings def min_gold_to_win(boss): min_gold = float("inf") for equipment in equipment_permutations(): gold = sum([x.cost for x in equipment]) if gold > min_gold: continue damage = sum([x.damage for x in equipment]) armor = sum([x.armor for x in equipment]) if battle(Character(100, damage, armor), boss): min_gold = gold boss.reset() return min_gold def max_gold_to_lose(boss): max_gold = float("-inf") for equipment in equipment_permutations(): gold = sum([x.cost for x in equipment]) if gold < max_gold: continue damage = sum([x.damage for x in equipment]) armor = sum([x.armor for x in equipment]) if not battle(Character(100, damage, armor), boss): max_gold = gold boss.reset() return max_gold WEAPONS = [Equipment(8, 4, 0), Equipment(10, 5, 0), Equipment(25, 6, 0), Equipment(40, 7, 0), Equipment(74, 8, 0)] ARMORS = [Equipment(13, 0, 1), Equipment(31, 0, 2), Equipment(53, 0, 3), Equipment(75, 0, 4), Equipment(102, 0, 5)] RINGS = [ Equipment(25, 1, 0), Equipment(50, 2, 0), Equipment(100, 3, 0), Equipment(20, 0, 1), Equipment(40, 0, 2), Equipment(80, 0, 3), ] BOSS = Character(109, 8, 2) assert battle(Character(8, 5, 5), Character(12, 7, 2)) assert min_gold_to_win(BOSS) == 111 assert max_gold_to_lose(BOSS) == 188
4d0a8800a9ddb4b90e510f6bb7335ad51d324157
l3e0wu1f/python
/JoshLewis_HolyHandgrenade.py
837
4
4
# INF322 Python # Josh Lewis # Week 1 – How To Defeat the Killer Rabbit of Caerbannog print('Brother Maynard: On what count shalst thy lob the Holy Hand-grenade of Antioch?') print('King Arthur: ') answer = input() while int(answer) != 3: print('Brother Maynard: The correct answer is 3, not ' + str(int(answer)) + '. To ' + str(int(answer) + 1) + ' shalt thou not count. ' + str(int(answer) + 2) + ' is right out! Once the number three, being' + ' the third number, be reached, then, lobbest thou thy Holy Hand Grenade' + ' of Antioch towards thy foe, who, being naughty in My sight, shall snuff it.') print('King Arthur: 1... 2... ' + str(int(answer)) + '!') print('Brother Maynard: Three, sir!') print('Enter 3: ') answer = input() print('King Arthur: Three!') print('BOOM!')
4fd1d8f87d860bf24adcca469ebc9ed51a3bc34f
Uncccle/Learning-Python
/16.py
4,346
3.953125
4
#-----------------学院管理系统-------------- # 存储学员信息的列表 student=[] # 功能界面 def sel_function(): print("请选择功能:") print("1.添加学员") print("2.删除学员") print("3.修改学员信息") print("4.查询学员信息") print("5.显示所有学员") print("6.退出系统") print("-"*20) # 添加学员功能函数: def add_num(): """添加学员函数""" #1. 输入学号,名字,手机号 student_id=input("请输入你的学号:") student_name=input("请输入你的名字:") student_phone = input("请输入你的手机号:") global student # 运用global函数,有全局变量的作用。是为了让刚进来的数据在列表里面存在 # 2.判断这个学员,如果学员存在报错,不存在放入加入列表 for i in student: if student_name == i["Name"]: print("此用户已经存在,请重新输入!") return # return 的作用是 返回值 还有,退出当前函数。 在这里的作用是: 当这个for函数运行完之后,发现跟列表里面的一样。就退出当前函数。 # 如果不加则return后面的代码会运行。会把重复的代码写入进字典(列表)里面。 #2. 将输入的数据 放入字典中,最后加入到列表里 dict_student={} #创建字典 dict_student["ID"]=student_id dict_student["Name"]=student_name dict_student["Phone"]=student_phone # *Tip: 在这里先用字典,然后加入到列表里面是为了起到 这种效果: # [{...}, {...}, {...}] 每一个字典里面都存在每个人的信息,然后最后到一个大列表里面 student.append(dict_student) #将字典,放进列表里 print(student) # 删除学员功能函数 def del_num(): del_student=input("请输入你想删除的名字:") global student# 将去除名字 重申进列表 for i in student: if del_student == i["Name"]: student.remove(i) print("已完成!删除你想删除的名字!") print(student) return else: print("不存在删除的名字,请重试!") print(student) # 修改学员信息 def modify_num(): modify_student = input("请输入你要修改的学员ID:") global student for i in student: if modify_student == i["ID"]: i["Name"] = input("请输入新的学员名字:") i["Phone"] = input("请输入与新的学员手机:") break else: print("未发现此学员信息!请重试") print(student) # 查询学员信息 def search_num(): search_student_ID=input("请输入你要查找的学员ID") global student for i in student: if search_student_ID == i["ID"]: print("'Name':" + i["Name"] + "'Phone':" + i["Phone"]) break else: print("没有改学员的信息!") # 显示学员信息: def appear_num(): print(student) # for i in student: # print(i) # return # 退出系统: def exit_game(): exit() while 1: #while 1 或者while True 其作用是使该while函数不停的循环而不是按一次就停下来了。 # 1.显示功能序号 sel_function() # 2.用户输入功能序号 user_selnum=int(input("请输入功能序号:")) # 3.按照用户输入功能序号的不同,执行不同的功能 # # # 如果用户输入(1),执行添加,输入(2),执行删除...... if user_selnum == 1: print("添加") add_num() elif user_selnum == 2: print("删除") del_num() elif user_selnum == 3: print("修改") modify_num() elif user_selnum == 4: print("查询") search_num() elif user_selnum == 5: print("显示所有学员") appear_num() elif user_selnum == 6: print("退出") exit() else: print("输入的功能序号有误!")
f95269ee7636b5e3d8e30b7675bd55ca459f252c
laggage/rainbow
/MyTkinter程序/棋盘覆盖/BoardCover.py
11,011
3.59375
4
# -*- encoding=utf-8 -*- import math import time import tkinter import tkinter.colorchooser as color from tkinter import * shunxu_cur = 0 class chessboard: def __init__(self, sx, sy, k): self.sx = sx self.sy = sy self.size = pow(2, k) self.chess = [[-1 for i in range(self.size)] for i in range(self.size)] self.shunxu = {} global shunxu_cur shunxu_cur = 0 self.count = [0 for i in range(10)] self.draw(0, 0, self.size, self.sx, self.sy) self.calc_var() self.show() self.pr() def draw(self, m, n, c, x, y): """ @param m,n 棋盘坐上定点横纵坐标 @param x,y: 残缺方格的坐标 @param c: 棋盘尺寸 """ global shunxu_cur if c <= 1: return cm = m - 1 + int(c / 2) cn = n - 1 + int(c / 2) if x <= cm and y <= cn: x1 = cm + 1 y1 = cn x2 = cm y2 = cn + 1 x3 = cm + 1 y3 = cn + 1 self.chess[y1][x1] = 1 self.chess[y2][x2] = 1 self.chess[y3][x3] = 1 self.shunxu[shunxu_cur] = {0: [y1, x1], 1: [y2, x2], 2: [y3, x3]} shunxu_cur += 1 self.draw(m, n, int(c / 2), x, y) self.draw(cm + 1, n, int(c / 2), x1, y1) self.draw(m, cn + 1, int(c / 2), x2, y2) self.draw(cm + 1, cn + 1, int(c / 2), x3, y3) return if x <= cm and y > cn: x1 = cm y1 = cn x2 = cm + 1 y2 = cn x3 = cm + 1 y3 = cn + 1 self.chess[y1][x1] = 3 self.chess[y2][x2] = 3 self.chess[y3][x3] = 3 self.shunxu[shunxu_cur] = {0: [y1, x1], 1: [y2, x2], 2: [y3, x3]} shunxu_cur += 1 self.draw(m, n, int(c / 2), x1, y1) self.draw(cm + 1, n, int(c / 2), x2, y2) self.draw(m, cn + 1, int(c / 2), x, y) self.draw(cm + 1, cn + 1, int(c / 2), x3, y3) return if x > cm and y <= cn: x1 = cm y1 = cn x2 = cm y2 = cn + 1 x3 = cm + 1 y3 = cn + 1 self.chess[y1][x1] = 2 self.chess[y2][x2] = 2 self.chess[y3][x3] = 2 self.shunxu[shunxu_cur] = {0: [y1, x1], 1: [y2, x2], 2: [y3, x3]} shunxu_cur += 1 self.draw(m, n, int(c / 2), x1, y1) self.draw(cm + 1, n, int(c / 2), x, y) self.draw(m, cn + 1, int(c / 2), x2, y2) self.draw(cm + 1, cn + 1, int(c / 2), x3, y3) return if x > cm and y > cn: x1 = cm y1 = cn x2 = cm + 1 y2 = cn x3 = cm y3 = cn + 1 self.chess[y1][x1] = 4 self.chess[y2][x2] = 4 self.chess[y3][x3] = 4 self.shunxu[shunxu_cur] = {0: [y1, x1], 1: [y2, x2], 2: [y3, x3]} shunxu_cur += 1 self.draw(m, n, c / 2, x1, y1) self.draw(cm + 1, n, c / 2, x2, y2) self.draw(m, cn + 1, c / 2, x3, y3) self.draw(cm + 1, cn + 1, c / 2, x, y) return def calc_var(self): """ 计算4种三角板的数量,存在count数组内 """ for i in range(self.size): for j in range(self.size): self.count[self.chess[i][j]] += 1 for i in range(4): self.count[i + 1] = int(self.count[i + 1] / 3) # print(self.count[i + 1]) # def calc_size(k): """ @param k用户输入的棋盘尺寸 k=log2(row_size),一般范围是[1,10],整数。 """ # return pow(2, k) def show(self): # """ @param t 原始生成的棋盘,t[y][x]代表(x,y)的种类 t[y][x]∈【1,4】 11 12 """ for i in range(self.size): for j in range(self.size): print("%d\t" % self.chess[j][i], end="") print("\n") for i in range(4): print(self.count[i + 1]) def pr(self): """ shunxu字典中按显示顺序存储着每次要显示的三个坐标对 shunxu[id][i][0]和shunxu[id][i][1]分别代表第id次画出的第i个格子的纵坐标!!(这里注意一下,先是纵坐标) 和 横坐标 """ for i in range(shunxu_cur): for j in range(3): print(self.shunxu[i][j][1], self.shunxu[i][j][0]) print('类型:{}'.format(self.chess[self.shunxu[i][j][0]][self.shunxu[i][j][1]])) ty = self.chess[self.shunxu[i][j][0]][self.shunxu[i][j][1]] if ty == 1: bg = button1.cget('bg') elif ty == 2: bg = button2.cget('bg') elif ty == 3: bg = button3.cget('bg') elif ty == 4: bg = button4.cget('bg') buttons[self.shunxu[i][j][1]][self.shunxu[i][j][0]].config(bg=bg) buttons[self.shunxu[i][j][1]][self.shunxu[i][j][0]].update() print("===========\n") time.sleep(time_sleep) def button1_event(): current_color = button1.cget('bg') bg = color.askcolor()[1] button1.config(bg=bg) for i in buttons: for j in i: if j.cget('bg') == current_color: j.config(bg=bg) def button2_event(): current_color = button2.cget('bg') bg = color.askcolor()[1] button2.config(bg=bg) for i in buttons: for j in i: if j.cget('bg') == current_color: j.config(bg=bg) def button3_event(): current_color = button3.cget('bg') bg = color.askcolor()[1] button3.config(bg=bg) for i in buttons: for j in i: if j.cget('bg') == current_color: j.config(bg=bg) def button4_event(): current_color = button4.cget('bg') bg = color.askcolor()[1] button4.config(bg=bg) for i in buttons: for j in i: if j.cget('bg') == current_color: j.config(bg=bg) def button5_event(): current_color = button5.cget('bg') bg = color.askcolor()[1] button5.config(bg=bg) for i in buttons: for j in i: if j.cget('bg') == current_color: j.config(bg=bg) def lone(event): button1.config(text='A类形状(0)个') button2.config(text='A类形状(0)个') button3.config(text='A类形状(0)个') button4.config(text='A类形状(0)个') me = event.widget me_text = event.widget['text'] index_x, index_y = me_text.split(',') index_x = int(index_x) index_y = int(index_y) for i in buttons: for j in i: j.config(bg='SystemButtonFace') btn5_color = button5.cget('bg') buttons[index_x][index_y].config(bg=btn5_color) global number # print('index_x:{}'.format(index_x)) # print('index_y:{}'.format(index_y)) # print('number:{}'.format(number)) # print('速度:{}'.format(int_value.get())) s = int_value.get() # s = 0.2 global time_sleep time_sleep = s global shunxu_cur shunxu_cur = 0 cb = chessboard(index_x, index_y, number, ) button1.config(text='A类形状({})个'.format(cb.count[1])) button2.config(text='A类形状({})个'.format(cb.count[2])) button3.config(text='A类形状({})个'.format(cb.count[3])) button4.config(text='A类形状({})个'.format(cb.count[4])) number = 0 time_sleep = 1 def begin(): # 销毁原有的按钮 global buttons for one_group_button in buttons: for one in one_group_button: one.destroy() buttons = [] k_value = entry_k.get() global number number = k_value try: number = int(float(k_value)) except Exception as e: # messagebox.showinfo('提示信息', '请输入整数') return buttons = [] count = int(math.pow(2, number)) row = 0 column = 0 button_group = [] for i in range(count * count): text = '{},{}'.format(row, column) btn = Label(ff, text=text, width=5, height=2, relief='g', bd=2) button_group.append(btn) btn.bind("<Button-1>", lone) btn.grid(row=row, column=column, ) column += 1 if column % count == 0 and column != 0: row += 1 column = 0 buttons.append(button_group) button_group = [] if __name__ == '__main__': win = tkinter.Tk() # 窗口 win.title('南风丶轻语') # 标题 screenwidth = win.winfo_screenwidth() # 屏幕宽度 screenheight = win.winfo_screenheight() # 屏幕高度 width = 800 height = 900 x = int((screenwidth - width) / 2) y = int((screenheight - height) / 2) win.geometry('{}x{}+{}+{}'.format(width, height, x, y)) # 大小以及位置 f = tkinter.Frame() f.pack() f1 = tkinter.Frame(f, bd=1, relief='groove') f11 = tkinter.Frame(f1) f11.pack() Label(f11, text='K').grid(row=0, column=0, ) entry_k = Entry(f11, width=10) # entry_k.insert('0', '2') entry_k.grid(row=0, column=1, padx=10, pady=10) f12 = tkinter.Frame(f1, ) f12.pack(fill=X) button5 = Button(f12, text='空缺颜色', command=button5_event, bg='#0000ff') button5.pack(fill=X) Button(f12, text='开始', command=begin, bg='pink').pack(fill=X) f1.grid(row=0, column=0, ) f2 = tkinter.Frame(f, bd=2, relief='groove') button1 = Button(f2, text='A类形状(0)个', bg='#ff0000', command=button1_event) button1.grid(row=0, column=0, padx=10, pady=10) button2 = Button(f2, text='B类形状(0)个', bg='#ff8040', command=button2_event) button2.grid(row=0, column=1) button3 = Button(f2, text='C类形状(0)个', bg='#ffff00', command=button3_event) button3.grid(row=1, column=0) button4 = Button(f2, text='D类形状(0)个', bg='#00ff00', command=button4_event) button4.grid(row=1, column=1, padx=10, pady=10) f2.grid(row=0, column=1, padx=30) f3 = tkinter.Frame(f, bd=2, relief='groove') int_value = tkinter.IntVar() int_value.set(1) Radiobutton(f3, text='缓慢', variable=int_value, value=3).grid(row=0, column=0) Radiobutton(f3, text='慢', variable=int_value, value=2.5).grid(row=1, column=0, pady=10) Radiobutton(f3, text='适中', variable=int_value, value=2).grid(row=2, column=0, ) Radiobutton(f3, text='快', variable=int_value, value=1.5).grid(row=0, column=1) Radiobutton(f3, text='较快', variable=int_value, value=1).grid(row=1, column=1, pady=10) Radiobutton(f3, text='更快', variable=int_value, value=0.5).grid(row=2, column=1, ) f3.grid(row=0, column=2) buttons = [] ff = Frame(win, bd=2, relief='flat') ff.pack() win.mainloop()
f7735d24d9f7c8b47393fbb9728c10f1c2908603
Kraks/Leetcode
/101_SymmetricTree/Solution.py
844
4.03125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {TreeNode} root # @return {boolean} def isSymmetric(self, root): if root: return self.aux(root.left, root.right) return True def aux(self, left, right): if left == None and right == None: return True if left == None or right == None: return False return left.val == right.val and self.aux(left.left, right.right) \ and self.aux(left.right, right.left) if __name__ == "__main__": s = Solution() t = TreeNode(1) t.left = TreeNode(2) t.right = TreeNode(3) t.left.left = TreeNode(3) t.right.left = TreeNode(2) print s.isSymmetric(t)
c45070eac54770e71969efe51cc3961c0dfc388c
Silencio0/Silencio
/silencio/client/client_network.py
3,773
3.5625
4
import sys import socket import datetime import select class network(object): """This class is designed to handle network message sending and recieving for the client end""" def __init__(self, server_addr, server_port): """ Default constructor for client network. Requires the server address and port number as inputs. Returns false if connection fails.""" def __init__(self, server_addr, server_port, local_port): """ Constructor for client network. Requires the server address, server port, and local port as inputs. Returns false if connection fails.""" if local_port is None: self.local_addr = ('localhost', 7700) else: self.local_addr = ('localhost', local_port) self.server_socket = (server_addr, server_port) self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.bind(self.local_addr) self.message_q = [] self.failed = False try: self.connection.create_connect(server_port) except: sys.stderr.write('failed to connect to server \n') self.failed = True self.connection.close() return None def login(self, input_user, input_pass): """ Function to send the login message to the server. Returns false if incorrect, True if correct. """ self.failed = False try: self.send_message('/login [' + input_user + '] [' + input_pass + ']\r') except: sys.stderr.write('failed to login to server. \n') Self.failed = True return False return True def register(input_user, input_pass): """ Function to send a register message to the server. Returns false if cannot be registered, True if registered. """ try: self.send_message('/register [' + input_user + '] [' + input_pass + ']\r') except: return False sys.stderr.write('failed to register with server. \n') return True def listen(self): """ Function that checks the network port for incoming message and availability. Creates new messages for incoming messages. Appends incoming messages to message table. """ readable, writeable, errored = select.select(self.connection) if self.connection in readable: text = self.read_connection() return text if self.connection in writeable: for message in self.message_q: #attempt message send. sent = self.send_message(message) if not sent: return False self.message_q.remove(message) return True if self.connection in errored: self.disconnect() return 'Connection errored out' return False def send_message(self,input_message): """ Function that sends messages to the server. Calls listen first to make sure port is free. Returns false if it Fails, true otherwise. """ try: self.connection.send('\r' + input_message + '\r') except: sys.stderr.write('failed to send message to server \n') return False return True def read_connection (self): sock = self.connection string = sock.recv(4098) return string def disconnect(self): """ Function that disconnects client form the server. Returns True after successful disconnect.""" self.connection.close() def q_send(send, in_string): """ Function for appending a message to the message queue """ self.message_q.append(in_string)
e4969667a91d91f77c5f6c49b45bf8b6d5ba3a27
jc135210/CP1404_prac
/prac1/menu.py
1,225
3.96875
4
x_value = int(input("enter the X value: ")) y_value = int(input("enter the Y value: ")) print("{:3}. Show the even numbers from {} to {}".format('i', x_value, y_value)) print("{:3}. Show the odd numbers from {} to {}".format('ii', x_value, y_value)) print("{:3}. Show the squares from {} to {}".format('iii', x_value, y_value)) print("{:3}. Exit the program".format('iv')) choice = int(input(">>> ")) while choice != 4: if choice == 1: if x_value % 2 == 0: for i in range(x_value, y_value + 1, 2): print(i, end=' ') else: for i in range(x_value + 1, y_value + 1, 2): print(i, end=' ') choice = int(input("\n>>> ")) elif choice == 2: if x_value % 2 != 0: for i in range(x_value, y_value + 1, 2): print(i, end=' ') else: for i in range(x_value+1, y_value+1,2): print(i, end=' ') choice = int(input("\n>>> ")) elif choice == 3: print("square") for i in range(x_value,y_value+1): print(i*i, end=' ') choice = int(input("\n>>> ")) else: print("incorrect choice. try again") choice = int(input(">>> "))
827d36ae9f113ff83464e01a0d7d11b148edbe50
zhizhin-ik/3semestr
/laboratory_8/task_4.1.py
298
4
4
def function(a): return print(a**2) def print_map(function, iterable): iterator=iterable.__iter__() while True: try: value=iterator.__next__() except StopIteration: break function(value) iterable=[0,1,2,3,4] print_map(function,iterable)
fc746e04b2c09c95e3ef2d9cd058eb950ec108b9
earl-grey-cucumber/Algorithm
/211-Add-and-Search-Word---Data-structure-design/solution.py
1,321
3.953125
4
class TrieNode(object): def __init__(self, c): self.val = c self.children = dict() self.end = False class WordDictionary(object): def __init__(self): self.root = TrieNode("") def addWord(self, word): cur = self.root for c in word: if c not in cur.children: cur.children[c] = TrieNode(c) cur = cur.children[c] cur.end = True def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ def helper(word, index, cur): if index == len(word): return cur.end if word[index] == '.': for c in cur.children: if helper(word, index + 1, cur.children[c]): return True if word[index] in cur.children: return helper(word, index + 1, cur.children[word[index]]) return False return helper(word, 0, self.root) # Your WordDictionary object will be instantiated and called as such: # wordDictionary = WordDictionary() # wordDictionary.addWord("word") # wordDictionary.search("pattern")
5db138e21313cbbe02cb6d2fb19af6df7106832b
kalbertmata/Python
/IS-python/python-week1/weekonecodealone2.py
332
3.984375
4
x=5 x=x+2 print(x) x+=2 print(x) x = 3.0 * x + 1.0 print(x) interest_rate = 4 interest_rate = x/interest_rate print(interest_rate) pay_rate= 12.0 minutes = 1140 hours = minutes / 60 results=pay_rate*hours print("Pay result is $" + str(results)) x = 43 interestRate = 3 interestRate = x / interestRate print(int(interestRate))
fec612be21bbb8360f32d8b2863157357a1a1494
fport/feyzli-python
/25.0 Fonksiyonlar.py
705
3.75
4
liste = [1,2,3,4,5,2,23,2,2,2] #liste.append(1) #print(liste) #a =liste.count(2) #print(a) """a = liste.reverse() print(liste)""" """ def topla(a,b): return a+b a= topla(5,6) print(a) print(topla(alfa,beta)) """ def karesiniAl(a): return a**2 #print(karesiniAl(5)) def bilgileriGöster(isim,soyisim,telno,sehir): print(""" İsim : %s Soyisim : %s Telefon Nu : %s Sehir : %s """ %(isim,soyisim,telno,sehir)) bilgileriGöster("Porti","Furki","0553xxx","Karabük") bilgileriGöster("Porti","Furki","0553xxx","Karabük") bilgileriGöster("Porti","Furki","0553xxx","Karabük") bilgileriGöster("Porti","Furki","0553xxx","Karabük")
90fd0bc94160b70fdf353e77e401da1dd9280868
AnshulDasyam/python
/syntax/scratch_21.py
318
3.828125
4
'''Asking the user for a input file and finding lines starting with _______ ''' a = open(input("file name:")) c = 0 g = 0 for b in a : if b.startswith("X-DSPAM-Confidence:") : b = b.rstrip() print(b) e = float(b[20:26]) print(e) c +=1 g +=e print("The average is",g/c)