blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
59c98dc4f2a4929863ff3d871d134d18f23bc69a
ramonvaleriano/python-
/Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 4/Exercicios 4a/Teste_Primo.py
241
3.703125
4
# Program: Teste_Primo.py # Author: # Description: # Developed: # Updated: number = int(input("Enter with a number: ")) cont = 0 for e in range(1, number+1): if number%e==0: cont+=1 if cont == 2: print() print(number)
d5b0914c92770be48dd09d075a847c42fc1f9987
gmarler/courseware-tnl
/solutions/py2/functions/maxbykey.py
1,109
4.1875
4
''' This is a quick typing exercise. You are to fill in the `max_by_key` function below. >>> nums = ["12", "7", "30", "14", "3"] >>> integers = [3, -2, 7, -1, -20] >>> student_joe = {'gpa': 3.7, 'major': 'physics', ... 'name': 'Joe Smith'} >>> student_jane = {'gpa': 3.8, 'major': 'chemistry', ... 'name': 'Jane Jones'} >>> student_zoe = {'gpa': 3.4, 'major': 'literature', ... 'name': 'Zoe Grimwald'} >>> students = [student_joe, student_jane, student_zoe] >>> max_by_key(nums, int) '30' >>> max_by_key(integers, abs) -20 >>> best_gpa = max_by_key(students, get_gpa) >>> best_gpa['name'] 'Jane Jones' >>> best_gpa['gpa'] 3.8 >>> best_gpa['major'] 'chemistry' ''' def get_gpa(who): return who["gpa"] # Copy in the code for max_by_key here: def max_by_key(items, key): biggest = items[0] for item in items[1:]: if key(item) > key(biggest): biggest = item return biggest # Do not edit any code below this line! if __name__ == '__main__': import doctest doctest.testmod() # Copyright 2015-2017 Aaron Maxwell. All rights reserved.
ec1832a7a1399065083cfbd4b96d58b49b73e4fd
iamprayush/ud120-complete
/__outliers/outlier_cleaner.py
1,010
3.734375
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] ### your code goes here # ages1 = [i[0] for i in ages] # predictions1 = [i[0] for i in predictions] # net_worths1 = [i[0] for i in net_worths] errors = [(i-j)**2 for i,j in zip(predictions, net_worths)] #errors1 = [(i-j)**2 for i,j in zip(predictions, net_worths)] for i in range(9): errors[errors.index(max(errors))] = -1 for i in range(len(errors)): if errors[i] > 0: cleaned_data.append((ages[i], net_worths[i], errors[i])) print(cleaned_data) # print('ages :') # print(ages1) # print('\n\n') # print('pred : \n') # print(predictions1) # print('\n\n') # print('net_worth : \n') # print(net_worths1) return cleaned_data
180a0a08aeaeede3e8c2962c402f6b3b286895d8
bilakos26/Python-Test-Projects
/System_Employees_Managment/main.py
993
3.640625
4
#ΑΣΚΗΣΗ 6 CLASSES import save_data import menu_choices SEARCH = 1 ADD = 2 CHANGE = 3 DELETE = 4 EXIT = 5 def main(): #ΑΣΚΗΣΗ 4 #obj1 = Employee('Susan Meyers', 47899, 'Accounting', 'Vice Precident') #obj2 = Employee('Mark Jones', 39119, 'IT', 'Programmer') #obj3 = Employee('Joy Rogers', 81774, 'Manifacturing', 'Engineer') #list_obj = [obj1, obj2, obj3] #show_obj(list_obj) employees = save_data.load_it() choice = menu_choices.choice() while choice != EXIT: if choice == SEARCH: menu_choices.search_Employee(employees) elif choice == ADD: menu_choices.add_employee(employees) elif choice == CHANGE: menu_choices.change(employees) elif choice == DELETE: menu_choices.delete(employees) choice = menu_choices.choice() save_data.save_it(employees) print("DATA SAVED!") print() #def show_obj(list_obj): # for obj in list_obj: # print(obj) main()
535cdf3688d1daf4213d89af951b71bdda18eca1
areum514/algorithms
/binary_search.py
573
3.828125
4
def binary_search(list, target): low = 0 high = len(list)-1 while low <= high: middle = low+high//2 guess = list[middle] if guess > target: high = middle - 1 elif guess < target: low = middle + 1 else: return middle return None print(binary_search([1, 3, 2], 3)) # 정렬된 리스트에서 # 가운데 값을 부른다 # 가운데 값이 찾고자 하는 값보다 크면 # end를 가운데로 # 가운데 값이 찾고자 하는 값보다 작으면 # start를 가운데로
f5eb608a6b3ba05b259614029586b2cb4a5d40f6
DishaCoder/Python_codes
/tk_add_two_no.py
4,876
3.546875
4
from tkinter import * window = Tk() window.title('Addition') window.geometry('500x500') try: lbl0 = Label(window,text = "Enter choice : ",font = ("Arial Bold",20)) lbl0.grid(column = 0,row = 0) txt0 = Entry(window,width = 10) txt0.grid(column = 1,row = 0) txt0.focus() def entered(): if txt0.get() == 'add' : lbl1 = Label(window,text = " A : ",font = ("Arial Bold" , 20)) lbl1.grid(column = 0,row = 2) txt1 = Entry(window,width = 10) txt1.grid(column = 1,row = 2) txt1.focus() lbl2 = Label(window,text = " B : ",font = ("Arial Bold",20)) lbl2.grid(column = 0,row = 4) txt2 = Entry(window,width = 10) txt2.grid(column = 1,row = 4) lbl3 = Label(window,text = " Answer = ",font = ("Arial Bold",20)) lbl3.grid(column = 0,row = 6) lbl4 = Label(window,font = ("Arial Bold",20)) lbl4.grid(column = 1,row = 6) def add(): res = int(txt1.get()) + int(txt2.get()) lbl4.configure(text = res) btn = Button(window,text = "ADD",font = ("Arial Bold",10),activebackground = 'gray',command = add) btn.grid(column = 1,row = 8) elif txt0.get() == 'sub': lbl1 = Label(window,text = " A : ",font = ("Arial Bold" , 20)) lbl1.grid(column = 0,row = 2) txt1 = Entry(window,width = 10) txt1.grid(column = 1,row = 2) txt1.focus() lbl2 = Label(window,text = " B : ",font = ("Arial Bold",20)) lbl2.grid(column = 0,row = 4) txt2 = Entry(window,width = 10) txt2.grid(column = 1,row = 4) lbl3 = Label(window,text = " Answer = ",font = ("Arial Bold",20)) lbl3.grid(column = 0,row = 6) lbl4 = Label(window,font = ("Arial Bold",20)) lbl4.grid(column = 1,row = 6) def sub(): res = int(txt1.get()) - int(txt2.get()) lbl4.configure(text = res) btn = Button(window,text = "Sub",font = ("Arial Bold",10),activebackground = 'gray',command = sub) btn.grid(column = 1,row = 8) elif txt0.get() == 'mul': lbl1 = Label(window,text = " A : ",font = ("Arial Bold" , 20)) lbl1.grid(column = 0,row = 2) txt1 = Entry(window,width = 10) txt1.grid(column = 1,row = 2) txt1.focus() lbl2 = Label(window,text = " B : ",font = ("Arial Bold",20)) lbl2.grid(column = 0,row = 4) txt2 = Entry(window,width = 10) txt2.grid(column = 1,row = 4) lbl3 = Label(window,text = " Answer = ",font = ("Arial Bold",20)) lbl3.grid(column = 0,row = 6) lbl4 = Label(window,font = ("Arial Bold",20)) lbl4.grid(column = 1,row = 6) def mul(): res = int(txt1.get()) * int(txt2.get()) lbl4.configure(text = res) btn = Button(window,text = "MUL",font = ("Arial Bold",10),activebackground = 'gray',command = mul) btn.grid(column = 1,row = 8) elif txt0.get() == 'div': lbl1 = Label(window,text = " A : ",font = ("Arial Bold" , 20)) lbl1.grid(column = 0,row = 2) txt1 = Entry(window,width = 10) txt1.grid(column = 1,row = 2) txt1.focus() lbl2 = Label(window,text = " B : ",font = ("Arial Bold",20)) lbl2.grid(column = 0,row = 4) txt2 = Entry(window,width = 10) txt2.grid(column = 1,row = 4) lbl3 = Label(window,text = " Answer = ",font = ("Arial Bold",20)) lbl3.grid(column = 0,row = 6) lbl4 = Label(window,font = ("Arial Bold",20)) lbl4.grid(column = 1,row = 6) def div(): if float(txt2.get()) == 0: lbl4.configure(text = "Infinity") else: res = float(txt1.get()) / float(txt2.get()) lbl4.configure(text = res) btn = Button(window,text = "DIV",font = ("Arial Bold",10),activebackground = 'gray',command = div) btn.grid(column = 1,row = 8) else: l = Label(window,text = ' Sorry!\nInvelid Choice ',font = ('Arial Bold',10)) l.grid(column = 1,row = 2) btn0 = Button(window,text = " Enter ",activebackground = 'gray',command = entered) btn0.grid(column = 3,row = 0) except ValueError as Argument: print("You must have to enter any two integer.",Argument) window.mainloop()
627be3398fd59b610afb190ce73fd01b86924de0
Jaxwood/daily
/problems/problem009.py
656
4.1875
4
def largest_sum(nums): """ Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. """ queue = [] for i in range(len(nums)): queue.append((i+2, nums[i])) best = 0 while len(queue) > 0: (i, s) = queue.pop() for j in range(i, len(nums)): if j < len(nums): total = s + nums[j] queue.append((j+2, total)) best = max(best, total) return best
4a42670275a0e0ca5b2fece90de2d6e8292b4b6e
freed24/python_data_stort
/insert_sort.py
640
3.90625
4
#-*- coding: utf-8 -*- #!/usr/bin/python #Filename: insert_sort.py #Author: Boyce #Email: boyce.ywr@gmail.com # 经典算法之直接插入排序(Insert sort) import randata ''' 被注释掉的部分是c语言数组普通的插入方式 未被注释的部分则是使用python列表的插入和删除特性改善的 ''' def insertSort(arr): for i in range(1,len(arr)): ''' tmp=arr[i] j=i while j>0 and tmp<arr[j-1]: arr[j]=arr[j-1] j-=1 arr[j]=tmp ''' j=i while j>0 and arr[j-1]>arr[i]: j-=1 arr.insert(j,arr[i]) arr.pop(i+1)
be1c830cb32f3f8fd4c7aac4f289229ae1edabf6
mohammadh128/text-based-adventure-with-python
/app.py
4,002
3.921875
4
import time character_name = '' answer_A = ["A", "a"] answer_B = ["B", "b"] answer_C = ["C", "c"] answer_D = ["D", "d"] yes = ["Y", "y", "yes"] no = ["N", "n", "no"] sword = 0 required = ("\nUse only A, B, C, D\n") character_name = input('please enter the name of your character: ') print("\nWELCOME TO THE ADVENTURE GAME 🎮\n") print(f"{character_name} wakes up in a dark and foggy forest. There is a certain peace in the forest.🌲\nYou want to get up but you feel pain in your left leg.") def intro(): print("You look around and notice that the path behind you is closed by a rocky mountain.⛰\nIn the far right there is a little light whose source is not known.\nThe path on the left is also impassable by a lot of felled trees.\nYou look ahead and find nothing but darkness.") time.sleep(1) print( "Which path will you choose???\n\nA: forward ⬆\nB: right ➡\nC: bakcwards ⬇\nD: left ⬅") choice = input(">>> ") if choice in answer_A: option_dark_path() elif choice in answer_B: option_light() elif choice in answer_C: print("How do you want to climb a mountain with this injured foot???🙄\n") intro() elif choice in answer_D: print("I do not think it is possible to pass through all these felled trees😩\n") intro() else: print(required) def option_dark_path(): print("\nYou gather all your strength and slowly walk towards the darkness.\nYou try not to feel the pain in your left leg and you feel that little by little your eyes got used to the darkness.👀\nSuddenly you hear a sound from behind the trees and your heart beat rises rapidly.😨") time.sleep(1) print("What would you do???\n\nA: Go back ⬇\nB: move deeper in the darkness") choice = input(">>> ") if choice in answer_A: intro() elif choice in answer_B: option_move_deeper() else: print(required) def option_move_deeper(): print("\nYou walk deeper into the forest and you hear a sound from behind the trees.👂🏻\nYou try not to pay attention to the sound and move forward.\nSuddenly you see a creature hovering in the air next to a tree staring at you with its red eyes.🧛🏻‍♀️") time.sleep(1) print("\nWhat would you do???\n\nA: Go Back ⬇\nB: Find a rock and throw at it 🧱\nC: Move towards it and try pass it ⬆\n") choice = input(">>> ") if choice in answer_A: intro() elif choice in answer_B: print("The creature is angry and come closer and bites your neck!!!😴") print("YOU ARE DEAD!!!\n❌❌❌!!!GAME OVER!!!❌❌❌") elif choice in answer_C: if sword == 0: print( "The creature block your path and wants to fight you.\nYou do not have a weapon and The creature bites your neck!!!😴") print("YOU ARE DEAD!!!\n❌❌❌!!!GAME OVER!!!❌❌❌") else: print( "You fight with all your being and use the ⚔sword⚔ to overcome the creature and move on untill you see the city light.") print("🎈🎉Congratulations you've done it 🎉🎈") else: print(required) def option_light(): print("\nAs you approach the light, you see that the dim light was the refletion of moonlight on a metal object.\nYou bend down and try to pick up the object and realize that the object is a samurai sword.\nYou look around and realize that there is no way forward and you have to go back to where you were before. 🗡🗡🗡") time.sleep(1) print("What would you do???\n\nA: Go Back ⬇\nB: Wait for no reason\n") global sword sword = 1 choice = input(">>> ") if choice in answer_A: intro() elif choice in answer_B: print("Use your head and go back🧠") option_light() else: print(required) intro()
91809437a47e6d017c86e2d2e4c48df1c50fda1e
CnbyC/8.hafta_odevler-Fonksiyonlar
/08.08.19_odev4.py
1,148
3.5625
4
def ebob(): # fonksiyonumuzu adlandirdik x = int(input("Lutfen 1. sayiyi giriniz : ")) # verileri aldik y = int(input("Lutfen 2. sayiyi giriniz : ")) list_x = [] # 3 tane bos liste olusturduk list_y = [] com_list = [] for i in range(1, x + 1): # 2 farkli dongu ile listeleri olusturduk if x % i == 0: list_x.append(i) for i in range(1, y + 1): if y % i == 0: list_y.append(i) if len(list_x) < len(list_y): # 2 farkli if formulasyonu ile sonuca ulastik for i in list_y: if i in list_x: com_list.append(i) com_list.reverse() if len(list_x) > len(list_y): for i in list_x: if i in list_y: com_list.append(i) com_list.reverse() return com_list[0] # sonucu verdik print(ebob()) # fonksiyomuzu cagirdik
71472ce77ca41244f9ac4cee31bc59c05d7bffde
shreyash0023/Python-Implementations
/Basics of Python/TuplesAndLists.py
1,640
4.1875
4
# Tuples # t1 = (3.35,) t2 = (1,'two',3) t3 = (t1,'hellow') print t1 print t2 print (t3 + t2)[3] def findDivisors (n1,n2): '''Assume n1 and n2 are positive ints''' divisors = () for x in range(1,min(n1,n2)+1): if n1%x == 0 and n2%x == 0: divisors = divisors + (x,) return divisors divisors = findDivisors(20,100) print divisors total = 0 print divisors[0] '''for x in range(0,len(divisors)): total += divisors[x] ''' for x in divisors: total += x print total '''Sequences and Multiple Assignments''' def findExtremeDivisors(n1,n2): '''Assume that n1 and n2 are positive ints Returns a tuple containing the smallest common divisor > 1 and the largest common divisor of n1 and n2''' divisor = () minValue,maxValue = None, None for x in range(2,min(n1,n2)+1): if n1%x == 0 and n2%x == 0: if minValue == None or x < minValue: minValue = x if maxValue == None or x > maxValue: maxValue = x return (minValue,maxValue) minDivisor, maxDivisor = findExtremeDivisors(100,200) print minDivisor, maxDivisor '''Lists and Mutability''' '''Lists are mutable,tuples and strings are not''' '''id(), which returns a unique integer identifier for an object, this function is used to test for object equality''' # . append() Techs = ['MIT', 'Caltech'] Ivys = ['Harvard', 'Yale', 'Brown'] Univs = [Techs, Ivys] Univs1 = [['MIT', 'Caltech'], ['Harvard', 'Yale', 'Brown']] print 'Unvis ->', Univs print 'Unvis1 ->', Univs1 # Aliasing '''Two distinct path to the same object'''
e454422d67376975e59c249da569211a012f6d37
Anfercode/Codigos-Python
/Clase 1/Capitulo4/Ejercicio4/ContinueBreak.py
186
3.640625
4
## Instruccion continue y break for i in range(10): if i==6: continue print(i) print('#############################') for i in range(10): if i==6: break print(i) print('Fin')
361235aa9396bfa0d51240b445e9cbc2f2b2346c
quanbanno2/first_upload
/lei.py
208
3.765625
4
class A(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b count=A(3,5) print(count.add()) class B(A): def sub(self): return self.a-self.b print(B(3,5).sub())
467106778d4fa6202f58d76d98b21f2b62c9ce61
Yangfan999/csc148-assignments
/summer 2018/A2/a2_battle_queue.py
12,033
3.65625
4
""" The BattleQueue classes for A2. A BattleQueue is a queue that lets our game know in what order various characters are going to attack. BattleQueue has been completed for you, and the class header for RestrictedBattleQueue has been provided. You must implement RestrictedBattleQueue and document it accordingly. """ from typing import Union class BattleQueue: """ A class representing a BattleQueue. """ def __init__(self) -> None: """ Initialize this BattleQueue. >>> bq = BattleQueue() >>> bq.is_empty() True """ self._content = [] self._p1 = None self._p2 = None def _clean_queue(self) -> None: """ Remove all characters from the front of the Queue that don't have any actions available to them. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.add(c2) >>> bq.is_empty() False """ while self._content and self._content[0].get_available_actions() == []: self._content.pop(0) def add(self, character: 'Character') -> None: """ Add character to this BattleQueue. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.is_empty() False """ self._content.append(character) if not self._p1: self._p1 = character self._p2 = character.enemy def remove(self) -> 'Character': """ Remove and return the character at the front of this BattleQueue. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.remove() Sophia (Rogue): 100/100 >>> bq.is_empty() True """ self._clean_queue() return self._content.pop(0) def is_empty(self) -> bool: """ Return whether this BattleQueue is empty (i.e. has no players or has no players that can perform any actions). >>> bq = BattleQueue() >>> bq.is_empty() True """ self._clean_queue() return self._content == [] def peek(self) -> 'Character': """ Return the character at the front of this BattleQueue but does not remove them. If this BattleQueue is empty, returns the first player who was added to this BattleQueue. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.peek() Sophia (Rogue): 100/100 >>> bq.is_empty() False """ self._clean_queue() if self._content: return self._content[0] return self._p1 def is_over(self) -> bool: """ Return whether the game being carried out in this BattleQueue is over or not. A game is considered over if: - Both players have no skills that they can use. - One player has 0 HP or - The BattleQueue is empty. >>> bq = BattleQueue() >>> bq.is_over() True >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.is_over() False """ if self.is_empty(): return True if self._p1.get_hp() == 0 or self._p2.get_hp() == 0: return True return False def get_winner(self) -> Union['Character', None]: """ Return the winner of the game being carried out in this BattleQueue if the game is over. Otherwise, return None. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.get_winner() """ if not self.is_over(): return None if self._p1.get_hp() == 0: return self._p2 elif self._p2.get_hp() == 0: return self._p1 return None def copy(self) -> 'BattleQueue': """ Return a copy of this BattleQueue. The copy contains copies of the characters inside this BattleQueue, so any changes that rely on the copy do not affect this BattleQueue. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("r", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("r2", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.add(c2) >>> new_bq = bq.copy() >>> new_bq.peek().attack() >>> new_bq r (Rogue): 100/97 -> r2 (Rogue): 95/100 -> r (Rogue): 100/97 >>> bq r (Rogue): 100/100 -> r2 (Rogue): 100/100 """ new_battle_queue = BattleQueue() p1_copy = self._p1.copy(new_battle_queue) p2_copy = self._p2.copy(new_battle_queue) p1_copy.enemy = p2_copy p2_copy.enemy = p1_copy new_battle_queue.add(p1_copy) if not new_battle_queue.is_empty(): new_battle_queue.remove() for character in self._content: if character == self._p1: new_battle_queue.add(p1_copy) else: new_battle_queue.add(p2_copy) return new_battle_queue def __repr__(self) -> str: """ Return a representation of this BattleQueue. >>> bq = BattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("r", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("r2", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.add(c2) >>> bq r (Rogue): 100/100 -> r2 (Rogue): 100/100 """ return " -> ".join([repr(character) for character in self._content]) class RestrictedBattleQueue(BattleQueue): """ A class representing a RestrictedBattleQueue. Rules for a RestrictedBattleQueue: - The first time each character is added to the RestrictedBattleQueue, they're able to add. For the below, you may assume that the character at the front of the RestrictedBattleQueue is the one adding: - Characters that are added to the RestrictedBattleQueue by a character other than themselves cannot add. i.e. if the RestrictedBattleQueue looks like: Character order: A -> B Able to add: Y Y Then if A tried to add B to the RestrictedBattleQueue, it would look like: Character order: A -> B -> B Able to add: Y Y N - Characters that have 2 copies of themselves in the RestrictedBattleQueue already that can add cannot add. i.e. if the RestrictedBattleQueue looks like: Character order: A -> A -> B Able to add: Y Y Y Then if A tried to add themselves in, the RestrictedBattleQueue would look like: Character order: A -> A -> B -> A Able to add: Y Y Y N If we removed from the RestrictedBattleQueue and tried to add A in again, then it would look like: Character order: A -> B -> A -> A Able to add: Y Y N Y """ def __init__(self) -> None: """ Init resticted battle queue. """ super().__init__() self.flag = [True, True] def add(self, character: 'Character') -> None: """ Add character to this bq. >>> bq = RestrictedBattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.is_empty() False """ if not self._p1: self._p1 = character self._p2 = character.enemy if len(self.flag) != len(self._content): self._content.append(character) elif self.flag[0]: if self.peek() != character: self.flag.append(False) self._content.append(character) return count = 0 for i in range(len(self._content)): if self._content[i] == character and self.flag[i]: count += 1 if count >= 2: self.flag.append(False) else: self.flag.append(True) self._content.append(character) def remove(self) -> 'Character': """ Remove and return the character at the front of this BattleQueue. >>> bq = RestrictedBattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("Sophia", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.remove() Sophia (Rogue): 100/100 >>> bq.is_empty() True """ while self._content and self._content[0].get_available_actions() == []: self.flag.pop(0) self._content.pop(0) self.flag.pop(0) return self._content.pop(0) def copy(self) -> 'BattleQueue': """ Return a copy of this BattleQueue. The copy contains copies of the characters inside this BattleQueue, so any changes that rely on the copy do not affect this BattleQueue. >>> bq = RestrictedBattleQueue() >>> from a2_characters import Rogue >>> from a2_playstyle import ManualPlaystyle >>> c = Rogue("r", bq, ManualPlaystyle(bq)) >>> c2 = Rogue("r2", bq, ManualPlaystyle(bq)) >>> c.enemy = c2 >>> c2.enemy = c >>> bq.add(c) >>> bq.add(c2) >>> new_bq = bq.copy() >>> new_bq.peek().attack() >>> new_bq r (Rogue): 100/97 -> r2 (Rogue): 95/100 -> r (Rogue): 100/97 >>> bq r (Rogue): 100/100 -> r2 (Rogue): 100/100 """ new_battle_queue = RestrictedBattleQueue() p1_copy = self._p1.copy(new_battle_queue) p2_copy = self._p2.copy(new_battle_queue) p1_copy.enemy = p2_copy p2_copy.enemy = p1_copy for character in self._content: if character == self._p1: new_battle_queue.add(p1_copy) else: new_battle_queue.add(p2_copy) return new_battle_queue if __name__ == '__main__': import python_ta python_ta.check_all(config='a2_pyta.txt')
c3480bd297af719c36f4882375d833762332fd61
7jdope8/Bitcoin_Bruters_Toolkit
/PERMUTE/permute_multi.py
3,510
4.0625
4
import itertools as it import time ## ## ## STEP 1: Get Inputs ## ## ## ----------------------------------------------- inputFileName = input("which .txt file to read word lists from? : ") # this section just checks you've put the .txt at the end of the filename as its a common habit to forget nameCheck = inputFileName[-4:] # take the last 4 char of the string if nameCheck != ".txt": # check the 4 chars are .txt, otherwise it has not been input inputFileName = inputFileName + ".txt" # add the .txt if it has been forgotten print (" \n ", " opening ", inputFileName, "\n") lineNos=0 with open(inputFileName, 'r') as f: for line in f: lineNos += 1 print("> Total number of items to scramble is ----> ", lineNos, "\n", "\n") permuteLengthMin = int(input("What is the minimum permutation length you seek eg 12 permutations (not combinations!) :\n ")) # permuteLengthMax = input("what is the maximum length you seek eg 50 permutations : ") permuteLengthMax = int(input("\nWhat is the Max permutation length you seek eg 20 permutations: \n")) # permuteLengthMax = input("what is the maximum length you seek eg 50 permutations : ") outputFileName = input("which .txt file to save permutations to? ") # this section just checks you've put the .txt at the end of the filename as its a common habit to forget nameCheck = outputFileName[-4:] # take the last 4 char of the string if nameCheck != ".txt": # check the 4 chars are .txt, otherwise it has not been input outputFileName = outputFileName + ".txt" # add the .txt if it has been forgotten open(outputFileName, 'a+').close() # create the blank file for writing later # open the list from file specified and ignore the \n at the end with open(inputFileName) as f: # open the list from file specified and ignore the \n at the end wordlist = f.read().splitlines() # Note, if the text file has 2 words on one line it will treat it as one, eg "hello world" is 1 item, but with a delimiter (,) as on 1 line "hello", "world" is 2 items. f.close() ## Save RAM, close the file! ## ## ## STEP 2: PERMUTE the wordlist ## ## ## ----------------------------------------------- print ("\n", " calculating....","\n") loopz = 0 combo_list = [] while int(permuteLengthMin+loopz)<= int(permuteLengthMax): tic = time.perf_counter() # ** Start the timer combo_list = list(it.permutations(wordlist, int(permuteLengthMin+loopz))) n=len(combo_list) with open(outputFileName, 'a+') as f: # save the string, as an append to the file f.write(str(combo_list)) # note we turn combo_list into a string, otherwise it doesnt write f.close() toc = time.perf_counter() # ** Stop the timer print("calculation of permutation of length ",int(permuteLengthMin+loopz) ,", which is ", n , " total permutations") loopz = int(loopz + 1) print(f" > \n Calculated in {toc - tic:0.4f} seconds \n") # the 0.4f means 4 decimal places #print(my_combos) first_2_strings = str(combo_list[:2]) print("\n","The first few strings appear like this; "+ first_2_strings + "\n" ,"\n") # print ("\n","\n" + " ,.-~*´¨¯¨`*·~-.¸-(_FINISHED_)-,.-~*´¨¯¨`*·~-.¸ "+ "\n","\n") # print (" results in " + outputFileName + "\n","\n")
37b946f7f30869b1d8e6a057e9284d2716a31d99
jsoto3000/angela-yu-100-days-python
/day-020-snake-1/snake_02.py
697
3.578125
4
# screen setup # snake body using for loop and tuples from turtle import Screen, Turtle import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") # turn off tracer for animation screen.tracer(0) # tuples starting_positions = [(0, 0), (-20, 0), (-40, 0)] segments = [] for position in starting_positions: new_segment = Turtle("square") new_segment.color("white") new_segment.penup() new_segment.goto(position) segments.append(new_segment) game_is_on = True while game_is_on: screen.update() # delay animation time.sleep(0.1) for seg in segments: seg.forward(20) screen.exitonclick()
63b639d391b8db03a71bb058ccbe6ac56a140b0e
SgtHouston/python101
/helloyou2.py
137
4.28125
4
name = input("What is your name?: ") print(("Hello, " + name + "! Your name has " + str(len(name)) + " letters in it! Awesome!").upper())
d3fab4c523ac7690cdf1e655c7e9364b008b85df
FearlessClock/RobotFactory
/UI/Button.py
666
3.640625
4
import pygame from pygame.math import Vector2 from pygame.rect import Rect class Button: """ rect = Rect object, Position and size of the button color = Color of the button in RGB (R,G,B) """ def __init__(self, rect, color, text, callback): self.rect: Rect = rect self.color = color self.text = text self.callback = callback def draw(self, surface, offset, fontRenderer): posRect = self.rect.move(offset.x, offset.y) pygame.draw.rect(surface, self.color, posRect) surface.blit(fontRenderer.render(self.text, False, (0, 0, 0)), posRect) def click(self): self.callback()
24a325b3f8e159c906d5b7859d96a11fdbcce39e
TuranDS/dz
/dz_3/zadacha_3_3.py
539
3.9375
4
num_1 = int(input('Введите число 1: ')) num_2 = int(input('Введите число 2: ')) num_3 = int(input('Введите число 3: ')) def old_hroft(tor, loki, fenrir ): a = max([tor, loki, fenrir]) list_1 = [tor,loki, fenrir]# почему я не могу в объявление списка сразу добавить метод ремов? list_1.remove(a) if list_1[0] > list_1[1]: b = list_1[0] else: b = list_1[1] return a,b print(old_hroft(num_1, num_2, num_3))
1fc67aa31172f1ebd0902252c0e44344292d751f
sabioX9/cashapp
/main.py
1,582
3.6875
4
#not so serious app import datetime import json import menu with open('spent.txt') as spent: data = spent.read() spent_money = int(data) class Spending: def __init__(self, starting_cash): self.cash = starting_cash def add_spending(self, amount): self.cash += amount return self.cash def show_spent_money(self): today = datetime.date.today() exact_day = today.strftime("%d/%m/%Y") return 'Na dzien {} wydales {}'.format(exact_day, self.cash) def greetings(self): print('Witaj w CashApp. Twojej aplikacji do sledzenia wydatkow.') weekday = datetime.datetime.today().weekday() if weekday == 6: print('Dzis mamy niedziele') elif weekday == 0: print('Dzis mamy poniedzialek') elif weekday == 1: print('Dzis mamy wtorek') elif weekday == 2: print('Dzis mamy srode') elif weekday == 3: print('Dzis mamy czwartek') elif weekday == 4: print('Dzis mamy piatek') elif weekday == 5: print('Dzis mamy sobote') def save_to_file(self): cash = str(self.cash) with open('spent.txt', 'w') as spent: spent.write(cash) return None user = Spending(spent_money) if __name__ == "__main__": user.greetings() while True: menu.show_menu() user_input = int(input('Co chcialbys zrobic? ')) menu.execute_menu(user_input)
f64c97c5a5673558f3afd66470170e814227f299
kleineG1zmo/helloworld-python
/Lesson 1/chisla 3.py
134
3.90625
4
a = int(input('YOUR NUMBER ')) b = a + 1 c = a - 1 print ('THE NEXT NUMBER IS', b) print ('THE PREVIOUS NUMBER IS', c)
f337d4f61d27d8a73ba6f88b224b47af73116aeb
aioooi/tictactoe-py
/tictactoe.py
1,657
3.703125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- import tictactoe.game as game import click import numpy as np @click.command() @click.option('--name', prompt=True, default='Human Player', help='Player name.') @click.option('--level', prompt=True, default='medium', type=click.Choice([ 'trivial', 'easy', 'medium', 'hard', 'impossible'], case_sensitive=False)) def cli(name, level): HANDICAP = { 'trivial': 62, 'easy': 50, 'medium': 38, 'hard': 24, 'impossible': 3 } h = HANDICAP[level] stats = { 'Computer': 0, name: 0, 'Draws': 0 } print("\nLet's go!\n\n") computer_moves_first = False while True: prefix = '' suffix = '\n' g = game.Game(h) result = g.play(computer_moves_first) if result == game.Game._HUMAN: stats[name] += 1 msg = 'You win!' computer_moves_first = True elif result == game.Game._COMPUTER: stats['Computer'] += 1 msg = 'I win!' computer_moves_first = False elif result == 0: stats['Draws'] += 1 msg = "That's a draw!" computer_moves_first = bool(np.random.randint(2)) print("{}{}\nStats: {}{}".format(prefix, msg, stats, suffix)) if click.confirm('Play another one?', default=True): if computer_moves_first: print('I will begin…\n\n') else: print('You may start now…\n\n') continue else: break if __name__ == '__main__': cli()
32226848a535061378a5eca6131ed02253b9a35a
RamSinha/MyCode_Practices
/python_codes/check.py
402
3.59375
4
def pre_process_pattern(input): prefix_matrix = [0 for _ in range(len(input))] j=0 for i in range(1, len(input)): while j >0 and input[j] != input[i]: j=prefix_matrix[j-1] if input[j] == input[i]: j=j+1 prefix_matrix[i] = j return prefix_matrix if __name__ == '__main__': ex_text = 'aaabb' print (pre_process_pattern(ex_text))
667219ca2c63fd2f311898eee7a924e1f07e1e8a
lvsazf/python_test
/characteristic/map_reduce.py
1,592
3.890625
4
# -*- coding: utf-8 -*- ''' Created on 2017年7月3日 @author: Administrator ''' # map 第一个参数是函数对象本身,第二个是个Iterable,map将传入的函数依次作用到序列的每个函数上,并把结果做为新的Iterator返回 from _functools import reduce def f(x): return x * x L = map(f, range(10)) print(list(L)) # 将0-9转为字符串 print(list(map(str, range(10)))) ############################################# # reduce把函数作用在另一个序列上,这个函数必须接收两个参数,把结果和序列的下一个元素做累计计算 # 1-9求和 def add(x, y): return x + y print(reduce(add, range(10))) # 将1、3、5、7、9 转为13579 def fn(x, y): if not isinstance(x, int): raise TypeError('x must be a int') if not isinstance(y, int): raise TypeError('y must be a int') return x * 10 + y print(reduce(fn, range(1, 10, 2))) def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] print(reduce(fn, map(char2num, '13579'))) # 用lambda def str2int(s): return reduce(lambda x, y: x * 10 + x, map(char2num, s)) print(str2int('13579')) #将传进来的名字首字母大写,其余小写 names = ['adam', 'LISA', 'barT'] def normalize(name): return map(str.capitalize,name) print(list(normalize(names))) #接收一个list并求积 def prod(L): def f(x,y): return x*y return reduce(f,L) print(list(range(1,5))) print(prod(range(1,5)))
ef0e55822a08363686578424060b27b6c3b26709
enazuma11/CSE241_Artificial_Intelligence
/assignmen7_guided_search/search.py
9,544
3.953125
4
""" search.py: Search algorithms on grid. """ import operator import heapq from collections import deque def heuristic(a, b): """ Calculate the heuristic distance between two points. For a grid with only up/down/left/right movements, a good heuristic is manhattan distance. """ # BEGIN HERE # dist=(abs(a[0]-b[0])+abs(a[1]-b[1])) return dist # END HERE # def searchHillClimbing(graph, start, goal): """ Perform hill climbing search on the graph. Find the path from start to goal. @graph: The graph to search on. @start: Start state. @goal: Goal state. returns: A dictionary which has the information of the path taken. Ex. if your path contains and edge from A to B, then in that dictionary, d[B] = A. This means that by checking d[goal], we obtain the node just before the goal and so on. We have called this dictionary, the "came_from" dictionary. """ # Initialise the came_from dictionary came_from = {} came_from[start] = None l_stack=[] if start==goal: came_from[goal]=start return came_from visited={} for x in range(graph.width): for y in range(graph.height): if graph.isOOB((x,y)): visited[(x,y)]=True else: visited[(x,y)]=False '''for items in visited: print(visited[items])''' #came_from[start]=start l_stack.append(start) #visited[start]=True parent={} parent[start]=start while(l_stack): cur=l_stack.pop() #print (cur) #visited[cur]=True came_from[cur]=parent[cur] if cur==goal: break neighbors=graph.neighboursOf(cur) distances={} for n in neighbors: distances[n]=heuristic(n,goal) sorted_neighbors = sorted(distances.items(), key=operator.itemgetter(1)) for ((x,y),z) in reversed(sorted_neighbors): item=(x,y) #print(visited[item]) if (not(visited[item])): parent[item]=cur visited[cur]=True l_stack.append(item) #print(item) '''for i in came_from: print(i+came_from[i]) # BEGIN HERE # print("goal: ",goal) print("start:",start) #print("goal_parent:",came_from[goal])''' path={} current=goal while(current!=start): path[current]=came_from[current] current=came_from[current] # END HERE # return path def searchBestFirst(graph, start, goal): """ Perform best first search on the graph. Find the path from start to goal. @graph: The graph to search on. @start: Start state. @goal: Goal state. returns: A dictionary which has the information of the path taken. Ex. if your path contains and edge from A to B, then in that dictionary, d[B] = A. This means that by checking d[goal], we obtain the node just before the goal and so on. We have called this dictionary, the "came_from" dictionary. """ # Initialise the came_from dictionary came_from = {} came_from[start] = None heap=[] if start==goal: came_from[goal]=start return came_from visited={} s_dist=heuristic(start,goal) heapq.heappush(heap, (s_dist, start)) # BEGIN HERE # for x in range(graph.width): for y in range(graph.height): if graph.isOOB((x,y)): visited[(x,y)]=True else: visited[(x,y)]=False parent={} parent[start]=start while(heap): (z,(x,y))=heapq.heappop(heap) cur=(x,y) #print(cur) #visited[cur]=True came_from[cur]=parent[cur] if cur==goal: break neighbors=graph.neighboursOf(cur) for n in neighbors: parent[n]=cur if(not(visited[n])): visited[cur]=True #parent[n]=cur dist=heuristic(n,goal) heapq.heappush(heap, (dist, n)) # END HERE # path={} current=goal while(current!=start): path[current]=came_from[current] current=came_from[current] return path #return came_from def searchBeam(graph, start, goal, beam_length=3): """ Perform beam search on the graph. Find the path from start to goal. @graph: The graph to search on. @start: Start state. @goal: Goal state. returns: A dictionary which has the information of the path taken. Ex. if your path contains and edge from A to B, then in that dictionary, d[B] = A. This means that by checking d[goal], we obtain the node just before the goal and so on. We have called this dictionary, the "came_from" dictionary. """ # Initialise the came_from dictionary came_from = {} visited={} if start==goal: came_from[goal]=start return came_from #came_from[start] = None for x in range(graph.width): for y in range(graph.height): if graph.isOOB((x,y)): visited[(x,y)]=True else: visited[(x,y)]=False # BEGIN HERE # q=deque([]) q.append(start) parent={} parent[start]=start while(q): cur=q.popleft() #visited[cur]=True came_from[cur]=parent[cur] if cur==goal: break neighbors=graph.neighboursOf(cur) distances={} for n in neighbors: q.append(n) for n in q: distances[n]=heuristic(n,goal) sorted_neighbors=sorted(distances.items(),key=operator.itemgetter(1)) i=0 q=deque([]) for((x,y),z) in sorted_neighbors: item=(x,y) if (not(visited[item]) and i<=beam_length): visited[cur]=True parent[item]=cur q.append(item) i=i+1 path={} current=goal while(current!=start): path[current]=came_from[current] current=came_from[current] # END HERE # return path #return came_from def searchAStar(graph, start, goal): """ Perform A* search on the graph. Find the path from start to goal. @graph: The graph to search on. @start: Start state. @goal: Goal state. returns: A dictionary which has the information of the path taken. Ex. if your path contains and edge from A to B, then in that dictionary, d[B] = A. This means that by checking d[goal], we obtain the node just before the goal and so on. We have called this dictionary, the "came_from" dictionary. """ # Initialise the came_from dictionary '''came_from={} heap=[] visited={} str_dist={} str_dist[start]=0 s_dist=heuristic(start,goal)+str_dist[start] heapq.heappush(heap, (s_dist, start)) for x in range(graph.width): for y in range(graph.height): if graph.isOOB((x,y)): visited[(x,y)]=True else: visited[(x,y)]=False previous=(-1,-1) while(heap): (z,(x,y))=heapq.heappop(heap) cur=(x,y) #print(cur) visited[cur]=True came_from[cur]=previous if cur==goal: break neighbors=graph.neighboursOf(cur) for n in neighbors: if(not(visited[n])): str_dist[n]=str_dist[cur]+1 dist=heuristic(n,goal)+str_dist[n] heapq.heappush(heap, (dist, n)) previous=cur''' # BEGIN HERE # came_from = {} came_from[start] = None visited_node={} visited_node[start]=1 parent={} parent[start]=None if(start==goal): return came_from cur=start m_list={} dist={} dist[start]=0 m_list[start]=heuristic(start,goal)+dist[start] while(1): if(len(graph.neighboursOf(cur))!=0): l=[] del m_list[cur] l=graph.neighboursOf(cur) for i in l: if i not in visited_node: dist[i]=dist[cur]+1 visited_node[i]=1 parent[i]=cur m_list[i]=heuristic(i,goal)+dist[i] s={} s = [(k, m_list[k]) for k in sorted(m_list, key=m_list.get, reverse=False)] m_list={} c=0 for i in s: if(c==0): cur=i[0] c=1 m_list[i[0]]=i[1] came_from[cur]=parent[cur] if(cur==goal): break return came_from else: del m_list[cur] s={} s = [(k, m_list[k]) for k in sorted(m_list, key=m_list.get, reverse=False)] m_list={} c=0 for i in s: if(c==0): cur=s[0] c=1 m_list[i[0]]=i[1] came_from[cur]=parent[cur] if(cur==goal): break return came_from current=goal path={} while(current!=start): path[current]=came_from[current] current=came_from[current] return path # END HERE # return came_from
3042fc1311ae54b66c9a440deddf8ee9bd8c4571
omdeshmukh20/Python-3-Programming
/ASMD.py
549
3.71875
4
. #Discription :Add,sub,mul,div.. #Date: 2/07/21.. #Author : Om Deshmukh def add(value1,value2): add=value1+value2 return(add) def sub(value1,value2): sub=value1-value2 return(sub) def mul(value1,value2): mul=value1*value2 return(mul) def div(value1,value2): div=value1/value2 return (div) def main(): ret1=add(11,2) ret2=sub(11,2) ret3=mul(11,2) ret4=div(11,2) print("Addition is",ret1) print("Substraction",ret2) print("Multiplication is",ret3) print("Dividion is",ret4) if __name__ == '__main__': main()
af3f9a3ebf11317101e8dc276b72ccedee9accee
RichieSong/algorithm
/算法/Week_03/98. 验证二叉搜索树.py
2,044
4.09375
4
# -*- coding: utf-8 -*- """ 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / \ 1 3 输出: true 示例 2: 输入: 5 / \ 1 4   / \   3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。   根节点的值为 5 ,但是其右子节点值为 4 。 解题思路: 二叉搜索树的特点:中序遍历是递增的 1、中序遍历之后,元素跟排序之后的元素对比 2、bfs,每个元素跟前一个元素比,一直大则ture """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isValidBST(self, root: TreeNode) -> bool: """inorder""" res = [] def inorder(root): if root: inorder(root.left) res.append(root.val) inorder(root.right) inorder(root) return res == list(sorted(set(res))) def isValidBST1(self, root: TreeNode) -> bool: inorder = self.search(root) return inorder == list(sorted(set(inorder))) def search(self, root): if root is None: return [] return self.search(root.left) + [root.val] + self.search(root.right) def isValidBST2(self, root): """ :type root: TreeNode :rtype: bool """ self.prev = None # 定义一个前驱节点 return self.helper(root) def helper(self, root): if root is None: return True if not self.helper(root.left): # 判断左子树 return False if self.prev and self.prev.val >= root.val: return False self.prev = root return self.helper(root.right)
ae05340a06b857c1a421992f4d6b49b028e2a1dd
Viknight/CodingBatSolutions
/Python/List_2/04_sum13__Solution.py
397
3.65625
4
def sum13(nums): total = 0 if len(nums) == 0: return 0 for i in range(len(nums)): if nums[i] == 13: if i<len(nums)-1: nums[i+1] = 0 else: total+=nums[i] return total # if len(nums) == 0: # return 0 # for i in range(0, len(nums)): # if nums[i] == 13: # nums[i] = 0 # if i+1 < len(nums): # nums[i+1] = 0 # return sum(nums)
9f1ac87081d561c46fe07aa1a7e8617ec8f0a86b
Zachary116699/mahjongcalc
/utils.py
5,367
3.796875
4
# -*- coding: utf-8 -*- def is_digit(str_1): """检测字符是否为数字""" try: float(str_1) return True except ValueError: return False def is_chi(item): """检测item是否吃或顺""" if len(item) != 3: return False return item[0] + 2 == item[1] + 1 == item[2] def is_pon(item): """检测item是否碰或刻""" if len(item) != 3: return False return item[0] == item[1] == item[2] def is_m_kan(item): """检测item是否明杠""" if len(item) != 4: return False return item[0] == item[1] == item[2] == item[3] def is_pair(item): """检测item是否雀头""" if len(item) != 2: return False return item[0] == item[1] def is_a_kan(item): """检测item是否暗杠""" if len(item) != 5: return False return item[0] == item[1] == item[2] == item[3] == item[4] def check_left_shun(tile, tiles_list): """检测tile是否和hand_tiles的牌形成左顺""" if (tile in tiles_list) and (tile + 1 in tiles_list) and (tile + 2 in tiles_list): return True return False def check_ke(tile, tiles_list): """检测tile是否和tiles_list的牌形成刻子""" if tiles_list.count(tile) >= 3: return True return False def check_pair(tile, tiles_list): """检测tile是否和tiles_list的牌形成对子""" if tiles_list.count(tile) >= 2: return True return False def check_pmeld_1(tile, tiles_list): """检测tiles_list中是否形成tile在左侧的直接相连的pmeld""" if (tile in tiles_list) and (tile + 1 in tiles_list): return True return False def check_pmeld_2(tile, tiles_list): """检测tiles_list中是否形成tile在左侧的直接相连的pmeld""" if tile in [9, 19, 32, 34, 36, 38, 40, 42, 44]: return False elif (tile in tiles_list) and (tile + 2 in tiles_list): return True else: return False def get_pairs(hand_tiles): """抓雀头形成列表""" pair_tile = [] for tile in hand_tiles: if check_pair(tile, hand_tiles): pair_tile.append(tile) pair_tile = list(set(pair_tile)) pair_tile.sort() return pair_tile def get_near_card(hand_tiles): """得到邻牌列表""" lin_tiles = [] for tile in hand_tiles: if tile in [32, 34, 36, 38, 40, 42, 44]: lin_tiles.append(tile) elif tile in [1, 11, 21]: lin_tiles.append(tile) lin_tiles.append(tile + 1) lin_tiles.append(tile + 2) elif tile in [9, 19, 29]: lin_tiles.append(tile) lin_tiles.append(tile - 1) lin_tiles.append(tile - 2) elif tile in [8, 18, 28]: lin_tiles.append(tile + 1) lin_tiles.append(tile) lin_tiles.append(tile - 1) lin_tiles.append(tile - 2) elif tile in [2, 12, 22]: lin_tiles.append(tile - 1) lin_tiles.append(tile) lin_tiles.append(tile + 1) lin_tiles.append(tile + 2) else: lin_tiles.append(tile) lin_tiles.append(tile - 1) lin_tiles.append(tile + 1) lin_tiles.append(tile - 2) lin_tiles.append(tile + 2) lin_tiles = list(set(lin_tiles)) lin_tiles.sort() return lin_tiles def get_tiles_deck(): """所有牌表的编码""" deck = [32, 34, 36, 38, 40, 42, 44] for i in range(1, 30): deck.append(i) deck.remove(10) deck.remove(20) deck.sort() return deck def get_all_136_tiles(): """获取136张牌的列表""" deck = get_tiles_deck() all_136_tiles = [] for tile in deck: all_136_tiles.append(tile) all_136_tiles.append(tile) all_136_tiles.append(tile) all_136_tiles.append(tile) return all_136_tiles def code_to_str(code): """编码转化成牌""" if 1 <= code <= 9: return str(code) + 'm' if 11 <= code <= 19: return str(code - 10) + 'p' if 21 <= code <= 29: return str(code - 20) + 's' if code >= 31: return str(int((code - 30) / 2)) + 'z' def codes_to_str(tiles_list): """将牌列表转化为牌字符""" man = [] pin = [] sou = [] zi = [] for tile in tiles_list: if 1 <= tile <= 9: man.append(tile) if 11 <= tile <= 19: pin.append(tile - 10) if 21 <= tile <= 29: sou.append(tile - 20) if tile >= 31: zi.append(int((tile - 30) / 2)) tiles_str = '' if len(man) != 0: for code in man: tiles_str += str(code) tiles_str += 'm' if len(pin) != 0: for code in pin: tiles_str += str(code) tiles_str += 'p' if len(sou) != 0: for code in sou: tiles_str += str(code) tiles_str += 's' if len(zi) != 0: for code in zi: tiles_str += str(code) tiles_str += 'z' return tiles_str def str_to_code(a_str): code = 0 if a_str.endswith('m'): code = int(a_str[0]) if a_str.endswith('p'): code = int(a_str[0]) + 10 if a_str.endswith('s'): code = int(a_str[0]) + 20 if a_str.endswith('z'): code = int(a_str[0]) * 2 + 30 return code
e40fc32c0bf40a2c9390bb1c67a0820827048227
alirezahi/InvertedIndexSearch
/LinkedList.py
4,764
3.890625
4
# <--Creating Class LinkedList--> class Node(): def __init__( self, data=None,next=None,prev=None,documentName = None): self.data = data self.next = next self.prev = prev self.superNext = None self.superPrev = None self.documentName = documentName self.isHead = False class LinkedList(): def __init__( self ,documentName = None,node_ref=None) : self.head = Node(documentName) self.head.isHead = True self.head.prev = None self.head.next = None self.documentName = documentName self.root_tree = None self.main_node = None self.node_ref = node_ref def add( self, data ) : node = Node(data , documentName=self.documentName) if self.head.next == None: self.head.next = node self.head.prev = node node.prev = self.head node.next = self.head else: node.prev = self.head.prev self.head.prev.next = node self.head.prev = node node.next = self.head return node def SuperAdd(self,node,root_tree=None,node_ref=None): if self.head.superNext == None: node.main_head = self.head self.head.superNext = node node.superPrev = self.head node.superNext = self.head self.head.superPrev = node node.root_tree = root_tree node.node_ref = node_ref else: node.main_head = self.head self.head.superPrev.superNext = node node.superPrev = self.head.superPrev self.head.superPrev = node node.superNext = self.head node.root_tree = root_tree node.node_ref = node_ref return node def search(self, k): p = self.head while p.next != None and p.next.data != None: p = p.next if p.data.lower() == k.lower(): return p return None def remove( self, inputData ) : p = self.search(inputData) if p != None: p.prev.next = p.next p.next.prev = p.prev def SuperRemove(self , inputNode): if inputNode != None: inputNode.superPrev.superNext = inputNode.superNext inputNode.superNext.superPrev = inputNode.superPrev inputNode.superNext == None inputNode.superPrev == None if (inputNode.main_head.superNext == None or inputNode.main_head.superNext == inputNode.main_head): inputNode.root_tree.remove(inputNode.node_ref) def getAll(self): i=0 p = self.head nameOfLastDocument = '' result_str = '' while p.superNext != self.head and p.superNext != None: result_str = result_str + '\n' p = p.superNext if nameOfLastDocument != p.documentName: nameOfLastDocument = p.documentName result_str = result_str + p.documentName+'\n' result_str = result_str + '( ...' if p.prev != None and not p.prev.isHead and p.prev.prev != None and not p.prev.prev.isHead : result_str = result_str + ' ' + p.prev.prev.data if p.prev != None and not p.prev.isHead : result_str = result_str + ' ' + p.prev.data result_str = result_str + ' ' + p.data if p.next != None and not p.next.isHead: result_str = result_str + ' ' + p.next.data if p.next != None and not p.next.isHead and p.next.next != None and not p.next.next.isHead: result_str = result_str + ' ' + p.next.next.data result_str = result_str + ' ... )' return result_str def getDocuments(self): i = 0 p = self.head nameOfLastDocument = '' result_str = '' next_line = False if p.superNext != self.head and p.superNext != None: next_line = True result_str = result_str + '| ' + p.superNext.data + ' --> ' while p.superNext != self.head and p.superNext != None: p = p.superNext if nameOfLastDocument != p.documentName: nameOfLastDocument = p.documentName result_str = result_str + p.documentName + ' ' if next_line: result_str = result_str + '\n' return result_str def removeAll(self): current_node = self.head while current_node.next != self.head and current_node.next != None: current_node = current_node.next if current_node.superNext != None: self.SuperRemove(current_node) # <--End of Creating Class LinkedList-->
008439259bd89e432083522057e9c7b401c489e5
randsi770/pythonsrc
/First.py
695
4.1875
4
import numpy as np import matplotlib.pyplot as plt from time import sleep def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) / 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print (quicksort([3,6,8,10,1,2,1])) #print quicksort([3,6,8,10,1,2,1]) # Prints "[1, 1, 2, 3, 6, 8, 10]" # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) sleep(1) # Plot the points using matplotlib plt.plot(x, y) plt.show() # You must call plt.show() to make graphics appear.
ccd75b29e2c6103dffef132f6489fb3891589393
muzi-bootstrap/ProgrammingForThePuzzled
/ch2/p19.py
1,295
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 16 15:18:45 2018 @author: sahashi """ sched2 = [(6.0,8.0), (6.5,12.0), (6.5,7.0), (7.0,8.0), (7.5,10.0), (8.0,9.0), (8.0,10.0), (9.0,12.0), (9.5,10.0), (10.0,11.0), (10.0,12.0), (11.0,12.0)] def bestTimeToPartySmart(schedule): times = [] for c in schedule: times.append((c[0], 'start')) times.append((c[1], 'end')) def sortList(tlist): for ind in range(len(tlist)-1): iSm = ind for i in range(ind, len(tlist)): if tlist[iSm][0] > tlist[i][0]: iSm = i tlist[ind], tlist[iSm] = tlist[iSm], tlist[ind] sortList(times) def chooseTime(times): rcount = 0 maxcount = time = 0 for t in times: if t[1] == 'start': rcount += 1 elif t[1] == 'end': rcount -= 1 if rcount > maxcount: maxcount = rcount time = t[0] return maxcount, time maxcount, time = chooseTime(times) print('Best time to attend the party is at', time, 'o\'clock', ':', maxcount, 'celebrities will be attending!') bestTimeToPartySmart(sched2)
0d61628f0542f7985d507535dd8d9126bdedcb0c
skensell/project-euler
/problems/problem-005.py
1,343
3.9375
4
#5. What is the smallest number divisible by each of 1,...,20. def pe5(): result = 1 i=2 while i<=20: if result % i != 0: result = lcm(result,i) i=i+1 return result def lcm(n,m): #finds the lcm of n and m where m should be the smaller number factors_in_common = [] factors_of_m = [] gcd=1 for i in range(len(prime_factors)): #empties prime_factors prime_factors.pop() for entry in factorize(m,2): factors_of_m.append(entry) for entry in factors_of_m: if n % entry ==0: n= n/entry m=m/entry factors_in_common.append(entry) for number in factors_in_common: gcd = gcd*number lcm = gcd*n*m return lcm prime_factors = [] def factorize(n,p): #produces a list of primes dividing n with multiplicity while True: if n % p==0: prime_factors.append(p) return factorize(n/p, p) elif n==1: return prime_factors p=p+1 print lcm(3,4) print lcm(20,15) print lcm(16, 24) print pe5() #Here's the book solution from the forums by lassevk # # i = 1 # for k in (range(1, 21)): # if i % k > 0: # for j in range(1, 21): # if (i*j) % k == 0: # i *= j # break # print i
68486349ca36dc7c1a58c1b5c2156f2c3f7b2971
4597veronica/Projectos_python
/Bucles/pyt05.py
363
3.90625
4
#coding:utf8 limite = input("Introduce un número límite, por favor: ") num = 1 while num <= limite : print str(num) #str= string, cadena num = num + 1 print "Fin del programa." #Va sumando +1 a num que es 1 hasta que llega al número indicado en límite #que es cuando va a terminar el bucle. #Cuenta hasta el límite que yo le digo.
c6dc71351aaf3a00b37b7d947e9fb89301e0093f
adam7902/Commonly-used-Python
/Python读写csv文件/csv读取txt文件.py
853
3.734375
4
# UTF-8 import csv # Reading txt Files With csv """ name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March """ with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') # print(list(csv_reader)) line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') """ 输出: Column names are name, department, birthday month John Smith works in the Accounting department, and was born in November. Erica Meyers works in the IT department, and was born in March. Processed 3 lines. """
e98c6a8e3f51fa9ee7fe15df0058910bcbe88468
Cyki89/Cinema_rooms_reservation_system
/test/test_room.py
6,910
3.53125
4
import unittest import room ROOM_NAME = 'Room Test' ROOM_SIZE = (10, 12) ROOM_SEATING = [None] + [[None] + list(range(1, ROOM_SIZE[1] + 1)) for _ in range(ROOM_SIZE[0])] ROOM_SEATING[1][1] = 'RESERVED' TOTAL_PLACES = ROOM_SIZE[0] * ROOM_SIZE[1] OCCUPATED_PLACES = 10 USER_NAME = 'TEST_USER' class MyTestCase(unittest.TestCase): def setUp(self): ''' create instance of Movie class ''' self.room = room.Room(ROOM_NAME, ROOM_SIZE) # change number of occupated places self.room.occupated_places = OCCUPATED_PLACES # reserve one place in cinema room self.room._Room__seating[1][1] = ROOM_SEATING[1][1] def tearDown(self): ''' create instance of Movie class ''' del self.room def test_create_instance(self): ''' check if instance was correctly created ''' self.assertEqual(self.room.name, ROOM_NAME) self.assertEqual(self.room.size, ROOM_SIZE) self.assertEqual(self.room._Room__seating, ROOM_SEATING) self.assertEqual(self.room.occupated_places, OCCUPATED_PLACES ) def test_parse_seat(self): ''' test 4 edge cases for parse_seat method ''' # test casses for wrong input places = [ ('11', '10'), ('10', '13'), ('10.0', '12') ] # expected error messages err_msg_1 = f'Row {places[0][0]} is not in range 1-{self.room.size[0]}' # row out of range err_msg_2 = f'Place {places[1][1]} is not in range 1-{self.room.size[1]}' # place out of range err_msg_3 = ("Unappropiate types of co-ordinates.Both need to be int:\n" "Cannot convert string to integer!\n" f"invalid literal for int() with base 10: '{places[2][0]}'") # not convertible string to int # put all message on the one list err_messages = [err_msg_1, err_msg_2, err_msg_3] # test 3 wrong inputs in a loop for place, err_msg in zip(places, err_messages): with self.assertRaises(Exception) as err: self.room.parse_seat(*place) self.assertEqual(str(err.exception), err_msg) # test correct input self.assertEqual(self.room.parse_seat(10, 10), (10, 10) ) def test_allocate_set(self): ''' test 3 edge cases for allocate_seat method ''' # test casses for wrong input places = [ ('11', '12'), # row out of range ('1', '1'), # seat is aleady occupated ] # expected error messages err_messages = [ ('Occur some problem during allocation:\n' f'Row {int(places[0][0])} is not in range 1-{self.room.size[0]}'), ('Occur some problem during allocation:\n' f'Seat {int(places[1][0])}, {int(places[1][1])} is already occuppated') ] # test wrong inputs in a loop for place, err_msg in zip(places, err_messages): with self.assertRaises(Exception) as err: self.room.allocate_seat(USER_NAME, *place) self.assertEqual(str(err.exception), err_msg) # correct input place = ('1', '2') self.room.allocate_seat(USER_NAME, *place) self.assertEqual(self.room.occupated_places, OCCUPATED_PLACES+1) self.assertEqual(self.room._Room__seating[int(place[0])][int(place[1])], USER_NAME) def test_relocate_set(self): ''' test 4 edge cases for parse_seat method ''' # test casses for wrong input places = [ ( ('11', '12'), ('10', '10') ), # 'seat_from' row out of range ( ('10', '10'), ('10', '10') ), # 'seat_from' is free ( ('1', '1'), ('1', '1') ), # 'seat_to' is already occupated ] # expected error messages err_messages = [ ('Occur some problem during relocation:\n' f'Row {int(places[0][0][0])} is not in range 1-{self.room.size[0]}'), ('Occur some problem during relocation:\n' f'Seat {int(places[1][0][0])},{int(places[1][0][1])} is free!!!'), ('Occur some problem during relocation:\n' f'Seat {int(places[2][1][0])},{int(places[2][1][1])} already occupied!!!') ] # test wrong inputs in a loop for place, err_msg in zip(places, err_messages): with self.assertRaises(Exception) as err: self.room.relocate_seat(*place[0], *place[1]) self.assertEqual(str(err.exception), err_msg) # correct input place = ( ('1', '1'), ('2', '2') ) self.room.relocate_seat( *place[0], *place[1]) self.assertEqual(self.room._Room__seating[int(place[1][0])][int(place[1][1])], ROOM_SEATING[1][1]) self.assertEqual(self.room._Room__seating[int(place[0][0])][int(place[0][1])], int(place[0][1])) def test_release_set(self): ''' test 3 edge cases for release_seat method ''' # test casses for wrong input places = [ ('11', '12'), # row out of range ('2', '2'), # seat is aleady free ] # expected error messages err_messages = [('Occur some problem during releasing seat:\n' f'Row {int(places[0][0])} is not in range 1-{self.room.size[0]}'), ('Occur some problem during releasing seat:\n' f'Seat {int(places[1][0])},{int(places[1][1])} is free!!!') ] # test wrong inputs in a loop for place, err_msg in zip(places, err_messages): with self.assertRaises(Exception) as err: self.room.release_seat(*place) self.assertEqual(str(err.exception), err_msg) # correct input place = ('1', '1') self.room.release_seat(*place) self.assertEqual(self.room.occupated_places, OCCUPATED_PLACES - 1) self.assertEqual(self.room._Room__seating[int(place[0])][int(place[1])], int(place[1])) def test_client_seats(self): ''' check client_seats method ''' self.assertEqual( list(self.room.cilent_seats() ), [ (ROOM_SEATING[1][1], 1, 1) ] ) def test_num_of_total_places(self): ''' check if num of total places was correct calculated ''' self.assertEqual(self.room.num_of_total_places(), TOTAL_PLACES) def test_num_of_free_places(self): ''' check if num of free places was correct calculated ''' self.assertEqual(self.room.num_of_free_places(), TOTAL_PLACES-OCCUPATED_PLACES) def test_copy(self): ''' check __copy__ method''' room_copy = self.room.__copy__() self.assertEqual(self.room.name, room_copy.name) self.assertEqual(self.room.size, room_copy.size) if __name__ == '__main__': unittest.main()
f2d6f2b7d6ce2c1358b05c5a7a163a56d6b98dc3
AnkitaTandon/NTPEL
/python_lab/median.py
569
4.25
4
#Q: Write a Python program to find the median among three given numbers. num=[] for i in range(3): num.append(int(input("Enter a number: "))) print("The median of three given number: ",end='') if num[0]>num[1] and num[0]>num[2]: if num[1]>num[2]: print(num[1]) else: print(num[2]) if num[1]>num[0] and num[1]>num[2]: if num[0]>num[2]: print(num[0]) else: print(num[2]) if num[2]>num[1] and num[2]>num[0]: if num[1]>num[0]: print(num[1]) else: print(num[0])
edc790e4708751e7b59d55f0d350e48d542907af
danielzuncke/conway_gol
/game_of_life.py
6,932
3.5625
4
import numpy as np import cursor import os import shutil import cv2 class GameOfLife: """ Recreates Conway's game of life and can be printed to cmd or to PNG series Args: width: width of matrix height: height of matrix Vars: width: width of matrix height: height of matrix src_path: script path dst_path: path to which generated files are moved progress: list containing all generations Functions: countNeighbors: returns how many living cells surround target cell iterate: calculates next generation caught: checks if game is caught in a loop toPNG: saves given matrix or list of matrices to png file pixel size is scalable toCMD: prints a given matrix to command line loop: plays the game """ def __init__(self, width, height): self.width = width self.height = height self.src_path = os.path.abspath('.') + ('\\') self.dst_path = os.path.abspath('.') + ('\\output\\') self.progress = [np.random.randint(2, size=(height, width), dtype=np.int)] self.temp = np.zeros((self.height, self.width), dtype=np.int) def countNeighbors(self, A, x, y): """ Counts alive neighbors of a given cell in matrix and returns next gen cell status Args: A: matrix that contains the cell of interest x: position of cell y: position of cell Returns: None """ neighbors = 0 for i in range(3): if (x - 1 + i) < 0 or (x - 1 + i) == self.height: continue for j in range(3): if (y - 1 + j) < 0 or (y - 1 + j) == self.width: continue if j == 1 and i == 1: continue if A[x - 1 + i, y - 1 + j] == 1: neighbors += 1 if neighbors == 3: self.temp[x, y] = 1 return elif neighbors == 2 and A[x, y] == 1: self.temp[x, y] = 1 return self.temp[x, y] = 0 return def iterate(self, A): """ Calculates next generation and appends it to progress list Args: A: matrix to evaluate """ for x in range(self.height): for y in range(self.width): self.countNeighbors(A, x, y) self.progress.append(self.temp.copy()) def caught(self, depth=2): """ Checks if game is stuck by looking for duplicates in progress list Args: depth: defines how many previous generations 0: won't check any 1: returns True if playing field doesn't change at all 2: returns True also if alternating structures exist (recommended) to detect more complex loops depth can be set higher, usually not necessary, high numbers will impact performance Returns: True: when caught in a loop False: when not caught in a loop """ if len(self.progress) == 1: return False if depth > len(self.progress): depth = len(self.progress) for A in self.progress[len(self.progress) - 1 - depth: len(self.progress) - 1]: if np.array_equal(self.progress[-1], A): return True return False def toPNG(self, scale=5, singlePNG=None): """ Creates ordered PNGs; cell-size adjustable, standard 5 by 5 pixels Args: scale: scales the size that one matrix value will take in pixels singlePNG: only saves last Matrix in list """ if singlePNG is None: for x, A in enumerate(self.progress): cv2.imwrite( # pylint: disable=E1101 'output_' + str(x) + '.png', np.kron(A, np.ones((scale, scale), dtype=np.int) * 255)) shutil.move(self.src_path + 'output_' + str(x) + '.png', self.dst_path + 'output_' + str(x) + '.png') else: cv2.imwrite('single_output.png', # pylint: disable=E1101 np.kron(self.progress[-1], np.ones((scale, scale), dtype=np.int) * 255)) shutil.move(self.src_path + 'single_output.png', self.dst_path + 'single_output.png') def toCMD(self, A, x=0): """ Prints playing field to CMD Args: A: matrix to be printed x: generation """ os.system('cls') # on windows output = '\n' for i in range(A.shape[0]): for j in range(A.shape[1]): if A[i, j] == 0: output += ' ' else: output += '█' # good chars: █, ▄, ▓, ░, ■ output += '\n' print(output) print(f'gen: {x}') def loop(self, generations=1, toCMD=None, singlePNG=None, singlePNGscale=1, multiPNG=None, multiPNGscale=1, loopLen=5, depth=2): """ Plays the game of life, can print to cmd or save as png's Args: generations: number of iterations toCMD: if True the game will be printed to the command line singlePNG: if True the final outcome will be saved as PNG singlePNGscale: scales the size that one matrix value will take in pixels multiPNG: if True the playthrough will be saved as PNG multiPNGscale: scales the size that one matrix value will take in pixels loopLen: number of matrizes that are recorded going back from most recent depth: how deep list checks for duplicates """ if toCMD: cursor.hide() for i in range(generations + 1): if toCMD: self.toCMD(self.progress[-1], i) if self.caught(depth): print('caught in loop') break if i != generations: self.iterate(self.progress[-1]) if multiPNG: self.toPNG(multiPNGscale) if singlePNG: self.toPNG(singlePNGscale, self.progress[-1]) if toCMD: cursor.show() if __name__ == "__main__": example = GameOfLife(int(input('width: ')), int(input('height: '))) example.loop(generations=(int(input('generations: '))), multiPNG=True, multiPNGscale=5)
f4093f8e8b54752d0a1bca1e6f53278e1d54a1b8
lsftw/ArbitraryCode
/simple/chat/chatclient.py
711
3.515625
4
# Started from http://ilab.cs.byu.edu/python/socket/echoclient.html # and http://ilab.cs.byu.edu/python/socket/echoserver.html import socket def connectTo(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) return s def getPublicIp(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) # dummy socket to get ip, sorry google return s.getsockname()[0] def main(): print('Your IP: ', getPublicIp()) # host = '129.2.209.207' # port = 50000 # s = connectTo(host, port) # send messages # message = raw_input(">") # size = 1024 # s.send(message) # data = s.recv(size) # print data # s.close() if __name__ == "__main__": main()
b8aaf8d5f1dfca89b1994d3a850246110af064c2
yinzaihecode/hongongpython
/venv/chap41-50/chap43.py
728
3.546875
4
# try: # except: # finally(옵션, 필요에따라 사용) try: number = int(input("> 정수 입력.")) print("입력 값은{} 입니다.".format(number)) except: print("예외가 발생했습니다.") finally: print("무조건적으로 실행됩니다.") def test(): print("test () 함수의 첫 줄입니다.") try: print("try 구문이 실행.") return print("try 구문의 return 키워드 뒤 입니다.") except: print("except 구문 실행") finally: print("finally 구문이 실행 되었습니다.") print("test() 함수의 마지막 줄 입니다.") test() # finally # 1. file.close # 2. db.close # 3. cache clear # 절대지켜
10bf0489299d37c2eb81300af42f33781ec683c3
tomcatcn/algorithm-pratice
/6.二维数组中的查找.py
2,004
3.6875
4
''' 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。   示例: 现有矩阵 matrix 如下: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] 给定 target = 5,返回 true。 给定 target = 20,返回 false。   限制: 0 <= n <= 1000 0 <= m <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # 解法1 遍历法 # class Solution: # def findNumberIn2DArray(self, matrix, target: int) -> bool: # if not matrix: # return False # n = len(matrix) # s = len(matrix[0]) # for i in range(n): # for j in range(s): # if target == matrix[i][j]: # return True # return False # 解法2 找规律 左下角开始找,比目标大向右找,比目标小,向上找 class Solution: def findNumberIn2DArray(self, matrix, target: int) -> bool: # 数组为空直接返回结果 if not matrix: return False # 左下角开始遍历 row, clo = len(matrix) - 1, 0 while row >= 0 and not clo == len(matrix[0]): # 比目标大,向上找 if matrix[row][clo] > target: row -= 1 # 比目标小,向右找 elif matrix[row][clo] < target: clo += 1 elif matrix[row][clo] == target: return True return False if __name__ == "__main__": matrix = [ [-5] ] s = Solution() result = s.findNumberIn2DArray(matrix, -5) print(result)
0e2228c5ef43777a909017f01c169e8fa39ff9e0
matthewkover/aoc
/Day 2/2-1.py
487
3.859375
4
#Advent of Code 2020 Day 2 Part 1 from collections import Counter with open("Day 2/data.txt") as text_file: choices = list(text_file.readlines()) valid_passwords = [] for item in choices: items = item.split(" ") min_val, max_val = items[0].split("-") char = items[1].strip(":") string = items[2].strip("\n") total = Counter(string) if int(min_val) <= int(total[char]) <= int(max_val): valid_passwords.append(string) print(len(valid_passwords))
05d09e44d6cc419b7075c2c7b6306524c4cd185a
CvetelinaS/pyladies
/test_piskvorky.py
703
3.6875
4
import piskvorky import util import ai def test_tah(): pole = "-"*20 assert len(pole) == 20 assert pole.count('x') == 1 assert pole.count('-') == 19 #tah hrace def tah_hrace(pole): while True: try: cislo_policka = int(input('Vyber si policko od 0 do 19!')) except ValueError: print('To není číslo!') else: if pozice < 0 or cislo_policka >= len(pole): print('Pole je obsazeno. Hrej znovu.') elif pole[cislo_policka] != '-': print('Tam není volno!') else: break pole = pole[:cislo_policka] + symbol + pole[cislo_policka + 1:] return pole
12fe859cacbbe2c08038f1cb58fd1d5a9e30e40a
EngrDevDom/Everyday-Coding-in-Python
/CelsiusToFahrebheit.py
169
4.03125
4
# Convert Celsius to Fahrenheit celsius = -40 fahrenheit = (celsius*1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius, fahrenheit))
a651a77eb04262132b449197888196e791144bca
panlourenco/exercises-coronapython
/chapter_04/chapter_4_4_10.py
307
4.3125
4
# 4-10. Slices: my_foods = ['pizza', 'falafel','carrot cake', 'ice cream', 'cannoli'] print("The first three items in the list are: ") print(my_foods[:3]) print("\nThree items from the middle of the list are:") print(my_foods[1:-1]) print("\nThe last three items in the list are:") print(my_foods[-3:])
3872f1324c88a807df30ae90c34d927b45efbf3e
AlisaBurovaE/programming_practice
/Week 3_Алиса Бурова_Б06-907/hw3-task1.py
1,110
3.9375
4
#Откройте произвольный текстовый редактор, например, spyder. Скопируйте туда текст программы, написанной выше. Сохраните текст в файле с именем hypot.py. #Запустите терминал, перейдите в каталог, где лежит файл hypot.py и выполните эту программу:python3 hypot.py #Интерпретатор языка Python вместо интерактивного режима выполнит последовательность команд из файла. #При этом значения вычисленных выражений не выводятся на экран (в отличии от интерактивного режима), поэтому для того, чтобы вывести результат работы программы, то есть значение переменной c, нужна функция print(). if __name__ == '__main__': a = 179 b = 197 c = (a ** 2 + b ** 2) ** 0.5 print(c)
908053bb7c09952bc3490a6c4dbc3296cd0006b9
yangzl2014/Study-Python
/flags/china-m1.py
1,831
3.640625
4
import uturtle turtle = uturtle.Turtle() def draw_rect(x1, y1, color, x2, y2): width = abs(x2 - x1) height = abs(y2 - y1) turtle.penup() turtle.goto(x1,y1) turtle.pendown() turtle.setheading(0) turtle.color(color, color) turtle.begin_fill() for i in range(2): turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.end_fill() def draw_star(center_x, center_y, radius, color): turtle.penup() pt1=turtle.pos() turtle.circle(-radius, 72) pt2=turtle.pos() turtle.circle(-radius, 72) pt3=turtle.pos() turtle.circle(-radius, 72) pt4=turtle.pos() turtle.circle(-radius, 72) pt5=turtle.pos() turtle.pendown() turtle.color(color, color) turtle.begin_fill() turtle.goto(pt3) turtle.goto(pt1) turtle.goto(pt4) turtle.goto(pt2) turtle.goto(pt5) turtle.end_fill() def star(center_x, center_y, radius, big_center_x, big_center_y): turtle.penup() turtle.goto(center_x, center_y) turtle.pendown() turtle.left(turtle.towards(big_center_x, big_center_y) - turtle.heading()) turtle.forward(radius) turtle.right(90) draw_star(turtle.pos().x, turtle.pos().y, radius, 'yellow') #draw_star(turtle.pos()[0], turtle.pos()[1], radius, 'yellow') turtle.reset() turtle.speed(0) width = 180 height = 120 draw_rect(-width/2, height/2, 'red', width/2, -height/2) pice = width/30 big_center_x = -width/3 big_center_y = height/4 star(big_center_x, big_center_y-1, pice*3, big_center_x, big_center_y) star(-width/6, height*2/5, pice, big_center_x, big_center_y) star(-width/10, height*3/10, pice, big_center_x, big_center_y) star(-width/10, height*3/20, pice, big_center_x, big_center_y) star(-width/6, height/20, pice, big_center_x, big_center_y)
787f82537e248b24e181d8734dfa48f93f367870
natTP/2110101-comp-prog
/12_Class/1222-Card.py
1,100
3.515625
4
class Card: def __init__(self, value, suit): self.value = value self.suit = suit def __str__(self): return "(" + str(self.value) + " " + str(self.suit) + ")" def getScore(self): if self.value == 'A': return 1 if self.value in 'JQK': return 10 return int(self.value) def sum(self, other): return (self.getScore() + other.getScore()) % 10 def __lt__(self, rhs): v = ['3','4','5','6','7','8','9','10','J','Q','K','A','2'] s = ["club","diamond","heart","spade"] if self.value == rhs.value: return s.index(self.suit) < s.index(rhs.suit) return v.index(self.value) < v.index(rhs.value) n = int(input()) cards = [] for i in range(n): value, suit = input().split() cards.append(Card(value, suit)) for i in range(n): print(cards[i].getScore()) print("----------") for i in range(n-1): print(Card.sum(cards[i], cards[i+1])) print("----------") cards.sort() for i in range(n): print(cards[i])
4e5be54bf8170214ee8a8ce60ce6d924a3bd6062
krootee/ud120-projects
/outliers/outlier_cleaner.py
984
3.796875
4
#!/usr/bin/python def outlier_cleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ temp_data = [] index = 0 for prediction in predictions: error = (prediction - net_worths[index]) ** 2 temp_data.append([ages[index], net_worths[index], error]) index += 1 print("Data with errors: ", temp_data) cleaned_data = sorted(temp_data, key=lambda x: x[2]) print("Data sorted by error: ", cleaned_data) return_list_size = round(len(cleaned_data)*0.9) print("Array size: ", len(cleaned_data), " items to return: ", return_list_size) returned_data = cleaned_data[:return_list_size] print("Data to return: ", returned_data) return returned_data
208aeec470bde31c525707fd3cb208cd1a043d65
DinethP/Python-Projects
/Lab 4/p2.py
1,387
3.875
4
import sys def CheckLine(line_found): if len(line_found) < 1: print('No match!') else: for item in line_found: print(item) def Case1(fName, keyword): line_found = [] try: file = open(fName) for line in file: if keyword in line.split(): line_found.append(line.rstrip()) CheckLine(line_found) file.close() except: print('File does not exist!') exit() def sublist(keyword, line): return all(item in line for item in keyword) def Case2(fName, keyword): keyword_split = keyword.split() line_found = [] try: file = open(fName) for line in file: line_lower = [word.lower() for word in line.split()] if sublist(keyword_split, line_lower): line_found.append(line.rstrip()) CheckLine(line_found) file.close() except: print('File does not exist!') exit() if '.txt' not in sys.argv[-1] or len(sys.argv) < 3: print('Not enough arguments!') exit() else: fName = sys.argv[-1] if len(sys.argv) > 3: keyword = " ".join([i.lower() for i in sys.argv[1:-1]]) Case2(fName, keyword) else: Case1(fName, sys.argv[0])
73a7095a52a653d77863af85160e7fe3e4b2a9eb
agrawal-khushboo/ECE-143
/write_chunks_of_five.py
1,279
3.546875
4
def write_chunks_of_five(words,fname): """ Using corpus of 10,000 common English words, create a new file that consists of each consecutive non-overlapping sequence of five lines merged into one line. Here are the first 10 lines: the of and to a in for is on that by this with i you it not or be are from at as your all have new more an was we will home can us about if page my has search free but our one other do no information time If the last group has less than five at the end, just write out the last group. Here is your function signature: write_chunks_of_five(words,fname). The words is a list of words from the above corpus and fname is the output filename string. """ assert type(fname)==str for w in words: assert type(w)==str try: f=open(fname,'w') l=len(words)//5 if l!=0: for i in range(l): f.write(words[5*i]+' '+words[(5*i)+1]+' '+words[(5*i)+2]+' '+words[(5*i)+3]+' '+words[(5*i)+4]+'\n') for i in range(5*(l),len(words)): f.write(words[i]+' ') elif l==0: for i in range(len(words)): f.write(words[i]+' ') f.close() except: return
ae6aeca3825cc39068f749704dddda0e9e220fc5
pjoscely/AP-Computer-Science-Principles
/AMC 12 A 2006 #20.py
3,336
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 28 20:35:31 2020 @author: joscelynec """ ''' This program uses Monte Carlo Simulation to solve an American Math Competition Problem AMC The problem is from the 2006 AMC 12A Exam. Problem #20 A bug starts at one vertex of a cube and moves along the edges of the cube according to the following rule. At each vertex the bug will choose to travel along one of the three edges emanating from that vertex. Each edge has equal probability of being chosen, and all choices are independent. What is the probability that after seven moves the bug will have visited every vertex exactly once? ''' import random ''' Given a vertex move, randomly move along one of three edges of the unit cube from the currentVertex to the nextVertex and return the nextVertex the 8 vertices on the unit cube are represented as lists: [0,0,0], [1,0,0], [0,1,0], ....., [1,1,1] The function below randomly selects a coordinate in the currentVertex and then flips its bit. A new three element list called nextVertex is created and returned. ****** Key Observations ***** On the unit cube a move along an edge can only change a single coordinate. A move across a face would change two coordinates A diagonal across the through the cube would change three coordinates. **************************** ''' def getNextVertex(currentVertex): #randomly select x, y, z to change nextVertex = [] c = random.randint(0,2) #a move to another vertex along an edge can only change a single coordinate #change the current value; 0 to 1, 1 to 0 for i in range(3): if(i != c): nextVertex.append(currentVertex[i]) else: if(currentVertex[c] == 0): nextVertex.append(1) else: nextVertex.append(0) #return the next vertex return nextVertex ''' Begin at origin [0,0,0], perform a random walk of length 7 steps return a list containg [0,0,0] and the subsequent 7 vertices visted during the random walk ''' def getWalk(startVertex): walk = [] currentVertex = startVertex for i in range(8): walk.append(currentVertex) currentVertex = getNextVertex(currentVertex) return walk ''' Check if all 8 walk vertices are unique There are slicker ways to do check, but the program is aimed at AP CSP students. Relies interestingly on the Pigeon Hole Principle ''' def isWalkValid(walk): if([1,0,0] not in walk): return False elif([0,1,0] not in walk): return False elif([0,0,1] not in walk): return False elif([1,1,0] not in walk): return False elif([1,0,1] not in walk): return False elif([0,1,1] not in walk): return False elif([1,1,1] not in walk): return False else: return True ''' The mathematical solution from https://artofproblemsolving.com/wiki/index.php/2006_AMC_12A_Problems/Problem_20 lists 2/243 as the exact answer A Monte Carlo simulation of 1000000 trials is performed below the estimated and true value are then displayed ''' ct = 0 for i in range(1000000): walk= getWalk([0,0,0]) if(isWalkValid(walk)): ct+=1 print(ct/1000000, 2/243) ''' Sample run 0.008265 0.00823045267489712 '''
8836648af486454f90ed02ae0a187c9116a567e0
tennisnuts/GreenGas
/StationV4.py
10,889
3.609375
4
''' Author: Oliver Nunn Date Modified: 8/2/2021 About: code to setup the station class for my 4yp project 'Green Gas' Change: putting in the electrolyser size and canisters size optimisation into the station so that no inputs are needed to set up the station - the optimisation just needs to be run ''' import numpy as np import Prices from collections import Counter import math # defining the station class and its methods class Station: def __init__(self): # Separate parameters self.water_price = 1.9101/1000 def get_optimised_electrolyser_demand(self, elec_price, dispenser_time_demand, starting_storage_level,electrolyser_capacity,storage_capacity): ''' Inputs: elec_price : numpy array of size 48 containing the half hourly electricity prices for that day. dispenser_time_demand : numpy array of varying size that contains (in order) the time at which each HGV is arriving i.e. for a HGV arriving at 2am, 10am and 6pm == [4,20,32]. starting_storage_level : a number (float) that states how much Hydrogen there is at 00:00 before the optimisation starts. Outputs: final_electrolyser_demand : numpy array of size 48 containing the optimised electrolyers demand for the following 24 hrs. post_hgv_storage_level[z] : the ending storage level that can then be added into the stations self or input elsewhere. ''' # determines if the demand can be met unsatisfied = 0 # Turns dispenser_time_demand into hydrogen demand dispenser_demand = np.zeros(48) for z in range(len(dispenser_time_demand)): dispenser_demand[dispenser_time_demand[z]] += 1 dispenser_demand = dispenser_demand * 32.09 # Initialises Vectors pre_hgv_storage_level = np.zeros(48) post_hgv_storage_level = np.zeros(48) final_electrolyser_demand = np.zeros(48) # Starts the Optimisation for z in range(48): # ____________________________________________________________________________ # Loop for every z iteration # ____________________________________________________________________________ electrolyser_demand = np.zeros(48) #Setting the Storage level for each hgv iteration if z == 0: storage_level = starting_storage_level else: storage_level = post_hgv_storage_level[z-1] for q in range(len(dispenser_time_demand)): # _______________________________________________________________________ # Loop for every HGV # _______________________________________________________________________ count = 0 for k in range(len(dispenser_time_demand)): if dispenser_time_demand[k] >= z: count += 1 temp = q-(len(dispenser_time_demand)-count) if temp >= 0: h2_needed = max(((temp+1)*32.09 - storage_level),0) else: h2_needed = 0 small_array = elec_price[z:(dispenser_time_demand[q]+1)] sorted_small_array = np.argsort(small_array) for n in range(len(sorted_small_array)): index = sorted_small_array[n] + z if h2_needed > 0: spare_capacity = min((electrolyser_capacity - electrolyser_demand[index]),(storage_capacity - storage_level)) if spare_capacity >= h2_needed: electrolyser_demand[index] += h2_needed storage_level += h2_needed h2_needed = 0 if h2_needed > spare_capacity: electrolyser_demand[index] += spare_capacity storage_level += spare_capacity h2_needed = h2_needed - spare_capacity final_electrolyser_demand[z] = electrolyser_demand[z] if z ==0: pre_hgv_storage_level[z] = starting_storage_level + electrolyser_demand[z] else: pre_hgv_storage_level[z] = post_hgv_storage_level[z-1] + electrolyser_demand[z] post_hgv_storage_level[z] = pre_hgv_storage_level[z] - dispenser_demand[z] if post_hgv_storage_level[z] < 0: unsatisfied += 1 post_hgv_storage_level[z] = max(post_hgv_storage_level[z],0) pre_hgv_storage_level[z] = max(pre_hgv_storage_level[z],0) return final_electrolyser_demand, pre_hgv_storage_level, unsatisfied def get_min_parameters(self, dispenser_time_demand): # the number below is set at 1 initially but the optimisation will increase this until the conditions are satisfied number_electorlysers = 1 # -------------------- # making sure the while loop can start unsatisfaction = np.array([1]) # -------------------- ''' ------------------------------------------------------------------------------------------------------------ ''' # ---------------------------------------------------------------------------------------------------------- # running a while loop to get the minimum number of canisters and the minimum number of electrolysers # ---------------------------------------------------------------------------------------------------------- while np.sum(unsatisfaction) > 0: ''' ------------------------------------------------------------------------------------------------------------ work out the minimum number of canisters to satisfy the demand at the end of the half hour period ''' counter = Counter(dispenser_time_demand) temp = np.zeros(49) for n in range(49): temp[n] = counter[n] temp2 = np.argsort(temp)[-1] maximum = counter[temp2] min_number_canisters = math.ceil((maximum*32.09)/9.5) number_canisters = min_number_canisters ''' ------------------------------------------------------------------------------------------------------------- ''' ''' ------------------------------------------------------------------------------------------------------------- work out the minimum number of canisters to satisfy the constraint that the station needs to be able to charge and discharge at the same time ''' spare_capacity = number_canisters*9.5-maximum*32.09 charge_time = (spare_capacity)/(0.0123*number_electorlysers) discharge_time = 9.5/0.0382 while discharge_time > charge_time: number_canisters += 1 spare_capacity = number_canisters*9.5-maximum*32.09 charge_time = (spare_capacity)/(0.0123*number_electorlysers) discharge_time = 9.5/0.0382 ''' ------------------------------------------------------------------------------------------------------------- ''' ''' ------------------------------------------------------------------------------------------------------------- set up the station with its parameters ''' electrolyser_capacity = 22.125*number_electorlysers storage_capacity = 9.5*number_canisters ''' ------------------------------------------------------------------------------------------------------------- ''' ''' ------------------------------------------------------------------------------------------------------------- run the system for 2020 price data ''' total_cost = np.zeros(365) unsatisfaction = np.zeros(365) for n in range(365): day = n+1 elec_price = Prices.elec_prices_data(day) starting_storage_level = 0 demand, level, unsatisfied = self.get_optimised_electrolyser_demand(elec_price, dispenser_time_demand, starting_storage_level,electrolyser_capacity,storage_capacity) # convert from demand in kg to kWh demand = demand*49.465 # convert electricity prices into pounds elec_price = elec_price/100 # find the cost of the refill cost = np.dot(demand,elec_price) total_cost[n] = cost unsatisfaction[n] = unsatisfied ''' ------------------------------------------------------------------------------------------------------------- ''' ''' ------------------------------------------------------------------------------------------------------------- work out the average refill cost ''' avg_refill_cost = (np.average(total_cost))/(len(dispenser_time_demand)) ''' ------------------------------------------------------------------------------------------------------------- ''' ''' ------------------------------------------------------------------------------------------------------------- if any HGV's were unsatisfied then increment the number of electrolysers and run the simulation again ''' if np.sum(unsatisfaction) > 0: number_electorlysers += 1 ''' ------------------------------------------------------------------------------------------------------------- ''' # ---------------------------------------------------------------------------------------------------------- # running a while loop to get the minimum number of canisters and the minimum number of electrolysers # ---------------------------------------------------------------------------------------------------------- self.n_electrolysers = number_electorlysers self.n_canisters = number_canisters self.electrolyser_capacity = 22.125*self.n_electrolysers self.storage_capacity = 9.5*self.n_canisters
9b916c7df49d6b239607357d56d393d75adfd51f
zbm1012/python_unittest
/test_add1.py
897
3.6875
4
from parameterized import parameterized import unittest # 实现加法的方法: def add(x, y): return x + y test_data = [(1, 1, 2), (1, 0, 1), (-1, 2, 1), (0,0,0)] class TestAdd(unittest.TestCase): # def test_add01(self): # res1 = add(1 , 1) # self.assertEqual(2, res1) # # def test_add02(self): # res2 = add(1, 0) # self.assertEqual(1, res2) # # def test_add03(self): # res3 = add(-1, 2) # self.assertEqual(1, res3) # def test_add(self): # test_add = [(1, 1, 2), (1, 0, 1), (-1, 2, 1)] # for x, y, expect_value in test_add: # res = add(x, y) # self.assertEqual(res, expect_value) @parameterized.expand(test_data) def test_add(self, a, b, result): res = add(a, b) self.assertEqual(res, result) if __name__ == '__main__': unittest.main()
6756d21de5926c22e883de053a8bebc097ab76d5
chenwang/QuantEcon.lectures.code
/python_oop/chaos_class.py
578
3.828125
4
class Chaos: """ Models the dynamical system with :math:`x_{t+1} = r x_t (1 - x_t)` """ def __init__(self, x0, r): """ Initialize with state x0 and parameter r """ self.x, self.r = x0, r def update(self): "Apply the map to update state." self.x = self.r * self.x *(1 - self.x) def generate_sequence(self, n): "Generate and return a sequence of length n." path = [] for i in range(n): path.append(self.x) self.update() return path
9889fd5ec0ecdb4c5d1991524ca7f3d7f4a71bbd
asad632/Python
/in_keyword_list.py
247
4.25
4
# # in keyword in list; we can find item avalible in list or not # fruites = ['apple', 'mango', 'orang'] # if 'apple' in fruites: # print('yes ') # else: # print('no') # # if 'kiwi' in fruites: # print('yes ') # else: # print('no')
aadd238d9f891e2e4d0043deff29165b2a4ea3e7
yes99/practice2020
/codingPractice/python/학교 시험 대비/vendingmachine_renewal.py
480
3.875
4
print("**자판기 프로그램**") price=int(input("물건 값을 입력하시오")) print("자판기에 넣은 돈은?") a = int (input("1000원 지폐개수:")) b = int (input("500원 지폐개수:")) c = int (input("100원 지폐개수:")) thousand = a * 1000 f_hundred = b * 500 hundred = c * 100 sum = thousand + f_hundred + hundred leftover = sum - price fh = leftover//500 h = (leftover %500 ) // 100 t = (leftover % 100) // 10 o = (leftover % 10) print(fh, h, t, o)
7e80356e19df131f3bd98bbe751f35abe0fbe326
Aasthaengg/IBMdataset
/Python_codes/p02390/s450915425.py
137
3.5
4
input = int(raw_input()) h = input / 3600 input -= h * 3600 m = input / 60 input -= m * 60 print str(h) + ":" + str(m) + ":" + str(input)
755491c181f8e5c0e4d8908db7136bbb3b2c7a5b
calendula547/python_fundamentals_2020
/python_fund/basic_syntax/easter_cozonacs.py
726
3.765625
4
budget = float(input()) flour_price = float(input()) egg_price = 75/100 * flour_price milk_price = flour_price + (25/100 * flour_price) need_milk_price = 0.250 * milk_price colored_egg = 0 lose_egg = 0 total_colored_eggs = None save_money = None single_cozonac_price = flour_price + egg_price + need_milk_price count_cozonacs = int(budget/single_cozonac_price) for i in range(1, count_cozonacs + 1): colored_egg += 3 if i % 3 == 0: lose_egg += i - 2 total_colored_eggs = colored_egg - lose_egg save_money = f'{(budget - single_cozonac_price * count_cozonacs):.2f}' print(f"You made {count_cozonacs} cozonacs! Now you have {total_colored_eggs} eggs and {save_money}BGN left.")
ade247a10a56ee90fd19497a185674d13c1bee43
vinoth-madhavan/HackerRank
/Problem Solving/Encryption.py
1,102
3.9375
4
''' Problem: Given an input string, encrypt it by specified scheme. URL: https://www.hackerrank.com/challenges/encryption/ Runtime: O(n) ''' import math as mt def encrypt(s): rows = 0 cols = 0 square_root = mt.sqrt(len(s)) if square_root % 2 == 0: rows = int(square_root) cols = int(square_root) else: rows = int(mt.floor(square_root)) cols = int(mt.ceil(square_root)) while (rows * cols) < len(s): rows += 1 #print("{} x {}".format(rows, cols)) i = 0 matrix = [] for _ in range(0, rows): row = [] for _ in range(0, cols): if i < len(s): row.append(s[i]) else: row.append("#") i += 1 matrix.append(row) #print(matrix) output = [] for index in range(len(matrix[0])): output_row = [row[index] for row in matrix if row[index] != "#"] output.append("".join(output_row)) return " ".join(output) if __name__ == '__main__': text = "iffactsdontfittotheorychangethefacts" encrypt(text)
4a813eb2d913e99b139791954ddd803b89b433e1
victor-paltz/algorithms
/classic_algorithms/Ford_Fulkerson.py
1,530
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Maximum flow by Ford-Fulkerson Complexity O(|V|*|E|*max_capacity) """ def add_reverse_arcs(graph): for u in list(graph.keys()): for v in graph[u]: if u not in graph[v]: graph[v][u] = 0 def _augment(graph, flow, val, u, target, visit): """Find an augmenting path from u to target with value at most val""" visit[u] = True if u == target: return val for v in graph[u]: if not visit[v] and graph[u][v] > flow[u][v]: res = min(val, graph[u][v] - flow[u][v]) delta = _augment(graph, flow, res, v, target, visit) if delta > 0: flow[u][v] += delta flow[v][u] -= delta return delta return 0 def ford_fulkerson(graph, s, t, matrix_output=False): """Maximum flow by Ford-Fulkerson :param graph: weighted directed graph in defaultdict(dict) format :param int s: source vertex :param int t: target vertex :param bool matrix_output: either output a dict(dict) flox of a matrix :returns: flow output, flow value :complexity: `O(|V|*|E|*max_capacity)` """ add_reverse_arcs(graph) n = len(graph) if matrix_output: flow = [[0] * n for _ in range(n)] else: flow = {u: {v: 0 for v in graph[u]} for u in graph} while _augment(graph, flow, float('inf'), s, t, [False]*n)>0: pass return (flow, sum(flow[s] if type(flow) is list else flow[s].values()))
234bb474fad8600f314bb7ea581d7477ff026286
JosephLai241/AAG
/aag/AAG.py
1,285
3.578125
4
#!/usr/bin/python """ Created on Sun Jul 19 17:17:24 2020 ASCII art generator. @author: Joseph Lai """ import random from pyfiglet import Figlet from utils.Cli import CheckArgs, Parser from utils.Examples import Examples from utils.Fonts import FONTS from utils.List import List from utils.Make import Make from utils.Titles import Titles class Main(): """ Putting it all together. """ @staticmethod def main(): args, parser = Parser().parse_args() ### List all fonts with their corresponding number. if args.list: Titles.title() List.print_fonts() ### Generate examples for all fonts. elif args.examples: Titles.title() Examples.generate_examples() ### Generate ASCII art based on the selected font and entered string. elif args.make: CheckArgs.check_make(args, parser) for args in args.make: Make.make(FONTS[int(args[0])], args[1]) ### Generate ASCII art from a random font and entered string. elif args.randomize: Titles.random_title() for text in args.randomize: Make.make(FONTS[random.randint(1,426)], text) if __name__ == "__main__": Main.main()
1eabf10ddad1b0337338eb08310af5ccabfc942b
sinhasaroj/Python_programs
/Generators/test1.py
237
3.53125
4
def my_gen(): yield 'A' yield 'B' yield 'C' g = my_gen() print(type(g)) print(next(g)) print(next(g)) print(next(g)) # if we ask again next(g) we will get StopIteration exception. g = my_gen() for x in g: print(x)
2b5dc851037353299d03aa3cecc851ac09f5ff9a
brymut/ud036_StarterCode
/media.py
396
3.65625
4
class Movie: """ Definition of the movie object, holding all the required information about a movie """ def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube
868a0f4a800fc65e59ebc0db859152c3e879cdfb
xiaochenchen-PITT/CC150_Python
/Leetcode/Reverse Integer.py
438
3.78125
4
class Solution: # @return an integer def reverse(self, x): digit_list = [] for digit in str(abs(x)): digit_list.append(digit) if x < 0: digit_list.append('-') new_string = '' reverse_list = digit_list[::-1] for digit in reverse_list: new_string += str(digit) # new_number = int(new_string) return int(new_string)
5b6dc8661b4bca3e06837a0d5f8a443f4d84d447
Life4honor/DailyAlgorithm
/python/hackerrank/archive/20.08/excel_sheet_column_title.py
548
3.546875
4
# https://leetcode.com/problems/excel-sheet-column-title/problem class Solution: def convertToTitle(self, n: int) -> str: alphabet = ['Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'] result = "" while n > 26: dividend, remainder = n // 26, n % 26 result = alphabet[remainder] + result n = dividend if remainder != 0 else dividend -1 result = alphabet[n % 26]+ result return result
e60ed86e2871f7ccaec7d4633d2e593f4884524a
zareenc/6.867-project
/src/preprocessing/create_even_data.py
2,949
3.625
4
import csv import argparse def get_even_data(input_csv_file, output_csv_file, num_classes, num_each_class, delimiter='\t'): if (not num_classes == 2) and (not num_classes == 5): print("Number of classes must be 2 or 5. Not processing data.") return num_binary_classes = 2 positive_threshold = 3 positive_review_index = 0 negative_review_index = 1 num_multi_classes = 5 output_file = open(output_csv_file, 'wb+') output_writer = csv.writer(output_file, delimiter=delimiter) review_rating_index = 5 class_counts = [0] * num_classes with open(input_csv_file, 'r') as fin: # Read in the column names from the input file col_names = fin.readline().strip().split(delimiter) output_writer.writerow(col_names) have_even_data = False for line in fin: row = line.strip().split(delimiter) rating = int(row[review_rating_index]) if num_classes == num_binary_classes: if rating >= positive_threshold and class_counts[positive_review_index] < num_each_class: class_counts[positive_review_index] += 1 output_writer.writerow(row) elif rating < positive_threshold and class_counts[negative_review_index] < num_each_class: class_counts[negative_review_index] += 1 output_writer.writerow(row) elif num_classes == num_multi_classes: if class_counts[rating-1] < num_each_class: class_counts[rating-1] += 1 output_writer.writerow(row) for class_count in class_counts: if class_count < num_each_class: have_even_data = False break have_even_data = True if have_even_data: break if __name__ == '__main__': parser = argparse.ArgumentParser( description='Create evenly distributed data sets.', ) parser.add_argument( 'input_csv_file_path', type=str, help='The name csv file to read in.', ) parser.add_argument( 'output_csv_file_path', type=str, help='The name csv file to write to.', ) parser.add_argument( 'total_num_classes', type=int, help='Whether you want to make binary or multiclass data. Must be 2 or 5', ) parser.add_argument( 'num_each_class', type=int, help='The number of reviews of each class.', ) args = parser.parse_args() input_csv_file = args.input_csv_file_path output_csv_file = args.output_csv_file_path num_classes = args.total_num_classes num_each_class = args.num_each_class get_even_data(input_csv_file, output_csv_file, num_classes, num_each_class)
6ad10e196440feca1443985021f6182306ad9513
moongchi98/MLP
/백준/JAN_FEB/11586.py
530
3.546875
4
N=int(input()) #비치는 모습 input 받기 위해서 goul = [] #한 줄당 imput으로 받고, 그 한 줄이 goul의 한 개의 요소 for i in range(N): goul.append(input()) K=int(input()) if K == 1: print('\n'.join(goul)) if K == 2: #좌우반전 for j in goul: #안의 각줄을 역으로해서 print print(j[::-1]) if K == 3: #상하반전 #reverse는 원본을 변형 goul.reverse() #전체를 reverse하고 줄바꿈으로 구분해서 출력 print("\n".join(goul))
5106baf53eeb36085427db41c125f02ca1572d2a
VladimirV88/GEEKBRAINS
/Python_GeekBrains/Vasilev_Home_Work_1/GeekBrains_Vasilev_lesson1_5.py
1,782
3.734375
4
# 5. Запросите у пользователя значения выручки и издержек фирмы. # Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). # Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). # Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника. print('Итак давай узнаём работает фирма в прибыль или убыток...') profit = int(input('Введите прибыль, которую фирма получила за год: ')) lose = int(input('Введите убыток фирмы за год: ')) staff = int(input('Введите кол-во сотрудников в фирме: ')) if profit > lose: print('Фирма отработала с прибылью ') efficiency = (profit - lose) / profit efficiency_staff = (profit - lose) / staff print(f'Рентабельность выручки равна {efficiency:.2%} ' '\nПоказатель прибыли в расчете на одного сотрудника равен ' f"{efficiency_staff}") elif profit == lose: print('Вышли в ноль') else: print("Фирма работает в убыток, пора вводить эффективных менеджеров")
3445d0bc8eea51f24481be6917699705f427b967
celalexis/spotify-playlist-creator
/main.py
1,566
3.53125
4
from bs4 import BeautifulSoup import requests import spotipy from spotipy.oauth2 import SpotifyOAuth import os SPOTIPY_CLIENT_ID = os.environ["SPOTIPY_CLIENT_ID"] SPOTIPY_CLIENT_SECRET = os.environ["SPOTIPY_CLIENT_SECRET"] SPOTIPY_REDIRECT_URI = os.environ["SPOTIPY_REDIRECT"] sp = spotipy.Spotify( auth_manager=SpotifyOAuth( scope="playlist-modify-private", redirect_uri=SPOTIPY_REDIRECT_URI, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, show_dialog=True, cache_path="token.txt" ) ) user_id = sp.current_user()["id"] travel_to = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ") response = requests.get(f"https://www.billboard.com/charts/hot-100/{travel_to}") billboard_webpage = response.text soup = BeautifulSoup(billboard_webpage, "html.parser") songs_span = soup.find_all(name="span", class_="chart-element__information__song") song_titles = [song.getText() for song in songs_span] song_uris = [] year = travel_to.split("-")[0] for song in song_titles: result = sp.search(q=f"track:{song} year:{year}", type="track") try: uri = result["tracks"]["items"][0]["uri"] song_uris.append(uri) except IndexError: print(f"{song} doesn't exist in Spotify. Skipped.") playlist = sp.user_playlist_create( user=user_id, name=f"{travel_to} Radio Hits", public=False, collaborative=False, description="Time to boogie.") sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris)
25eac1fdc3663d23d4b83f45a71d9a03133e9ab9
Amla63/loop
/chech_prime_num.py
169
3.953125
4
num=int(input('enter the num')) count=0 i=1 while i<=num: if num%i==0: count+=1 i=i+1 if count==2: print(num,'prime num hai') else: print(num,'prime num nahi hai')
78eed296c345c7033c473d13ef22bae44d5a9731
eechoo/Algorithms
/LeetCode/TwoSum.py
1,091
3.8125
4
#!/usr/bin/python ''' Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 ''' class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): MapNum={} for i in range(len(num)): if(MapNum.has_key(target-num[i])): index1=MapNum[target-num[i]]+1 index2=i+1 else: MapNum[num[i]]=i return (index1,index2) def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) def main(): ins=Solution() test(ins.twoSum([2,7,11,15],9),(1,2)) test(ins.twoSum([0,4,3,0],0),(1,4)) test(ins.twoSum([5,75,25],100),(2,3)) if __name__ == '__main__': main()
d0f75502e69231d4f8d7a2ed63eaf45f63709e94
DenilsonSilvaCode/Python3-CursoemVideo
/PythonExercicios/ex030.py
256
3.828125
4
'''Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.''' n = int(input('Me diga um numero qualquer: ')) resultado = n % 2 if resultado == 0: print('Este numero é PAR') else: print('Este numero é IMPAR')
fffa01c5d5d752a7f209713920844da9be7f9873
ajitabhkalta/Python-Training
/loops/while_1.py
267
4.21875
4
#Program to show else with while num = int(input("Enter a number:")) while num>0: if(num == 5): #if break is executed and loop is broken else will never be executed break print(f"{num}",end=" ") num-=1 else: print("LOOP COMPLETED SUCCESFULLY")
e9767d0e1cc30b790f84f370780ed9c8b0e2d2c6
lansevenit/520
/par.py
279
3.953125
4
#! /usr/bin/python3 ''' Ler o número e verificar se ele é par ou impar e adicionar ele em uma lista com resultado. [2, 'par'] [3, 'impar'] ''' num = int(input("Digite um numero")) resultado = [] resultado.append(num) if num % 2 == 0: print('par') else print("impar")
514c77a7a2c7e51b20c501ca611cad12234f654c
RuzhaK/pythonProject
/Fundamentals/FinalExamPreparation/StringProcessing/WorldTour.py
1,128
3.9375
4
stops=input() line=input() def index_is_valid(index, stops): if 0<=index<len(stops): return True def string_in_string(substring, stops): if substring in stops: return True while line !="Travel": command, index, token=line.split(":") if command=="Add Stop": index=int(index) if index_is_valid(index,stops): first_part=stops[:index] second_part=stops[index:] stops=first_part+token+second_part print(stops) elif command=="Remove Stop": start_index=int(index) end_index=int(token) if index_is_valid(start_index,stops) and index_is_valid(end_index,stops): stops=stops[:start_index]+stops[end_index+1:] print(stops) elif command=="Switch": string_to_check=stops while string_in_string(index,string_to_check): start_index = str.find(stops,index) stops=stops.replace(index,token) string_to_check=string_to_check[start_index+1:] print(stops) line = input() print(f"Ready for world tour! Planned stops: {stops}")
59eb9fc624cd22b0a9c9f6c6547e2e2268ad94d2
mbohekale/Python2019-20
/Lecture2/lab2.3.py
811
4.40625
4
##Your task is to: ##step 1:create an empty list named beatles ##step 2: use the append() method to add the ##list: John,Lennon, Paul McCartney, and George Harrison; ##step 3: use the for loop and the append()method to prompt the user to add the ##following members of the band to the list: Stu,Sutcliffe, and Pete Best; ##step 4: use the del instruction to remove Stu,Sutcliffe and Pete Best from the list; ##step 5: use the insert() method to add Ringo ##Start to the beginning of the list. beatles =[] l2=beatles beatles.append('John') beatles.append('Lennon') beatles.append('Paul McCartney') beatles.append('George Harrison') print(beatles) print('-------------') list1=[] name = int(input("Enter the length of list: ")) print("Enter names: ") for i in range(name): data=input() beatles.append(data)
13a2a4091a572b3763114978bb2fc768b5d1e3f4
wieczorek1990/python
/functional.py
282
3.546875
4
from operator import itemgetter print(filter(lambda x: x == 0, (0, 1, 2, 0))) a = [{'a': 0, 'b': 1}, {'a': 1, 'b': 2}] print(list(reversed(sorted(a, key=itemgetter('b'))))) print(list(reversed(sorted(a, key=lambda a: a['b'])))) a = [1, 2, 3, 4] print(map(lambda x: x ** 2, a))
9a39e603c2732f3eba45a682273cd2c741d3221c
JorG96/DataStructures
/kthSmallestInBST.py
2,037
4.09375
4
''' A tree is considered a binary search tree (BST) if for each of its nodes the following is true: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and the right subtrees must also be binary search trees. Given a binary search tree t, find the kth smallest element in it. Note that kth smallest element means kth element in increasing order. See examples for better understanding. Example For t = { "value": 3, "left": { "value": 1, "left": null, "right": null }, "right": { "value": 5, "left": { "value": 4, "left": null, "right": null }, "right": { "value": 6, "left": null, "right": null } } } and k = 4, the output should be kthSmallestInBST(t, k) = 5. Here is what t looks like: 3 / \ 1 5 / \ 4 6 The values of t are [1, 3, 4, 5, 6], and the 4th smallest is 5. For t = { "value": 1, "left": { "value": -1, "left": { "value": -2, "left": null, "right": null }, "right": { "value": 0, "left": null, "right": null } }, "right": null } and k = 1, the output should be kthSmallestInBST(t, k) = -2. Here is what t looks like: 1 / -1 / \ -2 0 The values of t are [-2, -1, 0, 1], and the 1st smallest is -2. ''' class Tree(object): def __init__(self, x): self.value = x self.left = None self.right = None def kthSmallestInBST(t, k): def dfs(node): if node: yield from dfs(node.left) yield node.value yield from dfs(node.right) f = dfs(t) for _ in range(k): ans = next(f) return ans
23f7b5be8ff721a3ea263ca379a71a8a37b8635d
CHOPPERJJ/Python
/LearningProject/PythonBasics/IO.py
911
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # IO编程 from datetime import datetime with open('test.txt', 'w') as f: f.write('今天是') f.write(datetime.now().strftime('%Y - %m - %d')) with open('test.txt', 'r') as f: s = f.read() print('open for read...') print(s) with open('test.txt', 'rb') as f: s = f.read() print('open as binary for read...') print(s) # write to StringIO from io import StringIO f = StringIO() f.write('hello') f.write(' ') f.write('world!') print(f.getvalue()) # read to stringIO f = StringIO('Helloooo!\nHi\nGoodbye!') while True: s = f.readline() if s == '': break print(s.strip()) # write to BytesIO from io import BytesIO b = BytesIO() b.write('中文'.encode('utf-8')) print(b.getvalue()) # read to BytesIO date = '两情若是久长时,又岂在朝朝暮暮。'.encode('utf-8') bi = BytesIO(date) print(bi.read())
cb6edd357e45453d4271eb5b4a72d5afae823e19
kampetyson/python-for-everybody
/6-Chapter/Exercise4.py
359
4.4375
4
# There is a string method called count that is similar to # the function in the previous exercise. Read the documentation of this # method at https://docs.python.org/3.5/library/stdtypes.html#string-methods # and write an invocation that counts the number of times the letter a # occurs in “banana”. word = 'banana' print('Count: ',word.count('a'))
47cc8e1599d65172b2fa49b849eeb99465ea61fd
omidziaee/DataStructure
/Algorithm_And_Data_Structure/system_design/moving_average.py
619
3.90625
4
''' Created on Apr 5, 2019 @author: USOMZIA ''' class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.size = size self.window = [] def next(self, val): """ :type val: int :rtype: float """ if len(self.window) == self.size: self.window.pop(0) self.window.append(val) return float(sum(self.window)) / min(self.size, len(self.window)) sol = MovingAverage(3) print sol.next(1) print sol.next(10)
2dc53abac71201e4745cebfde61ddf3476dd1671
joneyyx/LeetCodes
/elementaryAlgorithms/Array/JZ29打印矩阵.py
1,468
3.75
4
# 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 # # 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] # 输出:[1,2,3,6,9,8,7,4,5] from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return [] #m行,n列 m, n = len(matrix), len(matrix[0]) res = [] #起始点 left, top, right, bottom = 0, 0, len(matrix[0])-1, len(matrix)-1 while True: #>>>>>>>>从左到右,到达之后top+1 for j in range(left, right+1): res.append(matrix[top][j]) top += 1 #边界条件 if top > bottom: break #>>>>>>>从上倒下,到达之后right-1 for i in range(top, bottom+1): res.append(matrix[i][right]) right -= 1 #边界条件 if right < left: break #>>>>>>>从右到左,到达之后bottom-1 for j in range(right, left-1, -1): res.append(matrix[bottom][j]) bottom -= 1 if bottom < top: break #>>>>>>>从下到上,到达之后left+1 for i in range(bottom, top-1, -1): res.append(matrix[i][left]) left += 1 if left > right: break return res
8a4b4433481345ce93b777517fa64207c50d62e1
n20084753/Guvi-Problems
/beginer/set-4/38-swap-two-numbers-bitwise.py
106
3.59375
4
n, m = [int(x) for x in raw_input().split(" ")] n = n ^ m m = n ^ m n = n ^ m print(str(n) + " " + str(m))
95b273e9962a5bda5c07309e25eb71c5068c43bb
alexvydrin/gb_course_python_base
/lesson_2/task2_3.py
1,665
4.15625
4
""" Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. """ while True: month = int(input("Введите номер месяца в виде целого числа от 1 до 12: ")) if month in range(1, 13): break else: print("Номер введен некорректно - повторите ввод") # наименования времен года закодируем, чтобы в случае переименования изменяли в одном месте а не во всем коде # например в случае изменения языка вывода на английский меняем только здесь, а не в двух вариантах решения winter = "зима" spring = "весна" summer = "лето" autumn = "осень" # реализация решения через list list_month = [winter, winter, spring, spring, spring, summer, summer, summer, autumn, autumn, autumn, winter] print(f"Номер месяца: {month} - время года: {list_month[month - 1]}") # реализация решения через dict dict_month = { 1: winter, 2: winter, 3: spring, 4: spring, 5: spring, 6: summer, 7: summer, 8: summer, 9: autumn, 10: autumn, 11: autumn, 12: winter } print(f"Номер месяца: {month} - время года: {dict_month[month]}")
da9277ccd137b5e3535b352000ded8d9ea1cd471
DiasDogalakov/ICT_2020
/task 1/29.py
101
3.90625
4
c = float(input("Temp: ")) f = c * 1.8 + 32 print(str(c) + " degree(C) == " + str(f) + " degree(F)")
876aaf5ed300a58f2e7db821b13f19f14bd76da7
Satish2611/python-challenge
/PyPoll/Main.py
2,390
3.734375
4
# Import os module,This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv #Going to csv path csvpath=os.path.join('Resources', 'election_data.csv') #open csv with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') # skipping Header csv_header=next(csvreader) data=[] #appending data- Candidate for row in csvreader: data.append(row[2]) #function for finding unique name of candidates and their occurance def unique(name): unique_name=[] for row in name: if row not in unique_name: unique_name.append(row) count=[] #finding the unique names and count of their occurances for i in range(len(unique_name)): unique_name_count=0 for row_1 in name: if unique_name[i] in row_1: unique_name_count+=1 count.append(unique_name_count) return unique_name,count #calling functions and assign them to variables unique_name,count=unique(data) #Total votes calculation totalvotes=len(data) percentages=[] #finding percentage of each candidate for j in range(len(count)): percentages.append(round(count[j]/totalvotes*100,3)) winner=percentages[0] winnerName=unique_name[0] #finding winner who has highest votes if winner<percentages[j]: winnerName=unique_name[j] # Open the file using "write" mode. Specify the variable to hold the contents file_output=open("PyPoll_Output.txt", 'w') # Writing output file_output.write("Election Results\n") file_output.write("-------------------------\n") file_output.write("Total Votes: "+str(totalvotes)+"\n") file_output.write("-------------------------\n") for l in range(len(unique_name)): file_output.write(str(unique_name[l])+':'+str(percentages[l])+'%'+" ("+str(count[l])+")"+"\n") file_output.write("-------------------------\n") file_output.write("Winner:"+winnerName+"\n") file_output.write("-------------------------\n") #Printing output print("Election Results") print("-------------------------") print(f"Total Votes: {totalvotes}") print("-------------------------") for k in range(len(unique_name)): print(f"{unique_name[k]}:{percentages[k]}% ({count[k]})") print("-------------------------") print(f"Winner:{winnerName}") print("-------------------------")
df5e1263fb779d5a7e672683af3de65df1e5e272
goiaciprian/Pyth
/binaryTree.py
1,189
4.25
4
# learnig how to create an binary tree class BinaryTree: def __init__(self, root): self.left = None self.right = None self.root = root def getLeft(self): return self.left def getRight(self): return self.right def setRoot(self, value): self.root = value def getRoot(self): return self.root def insertRight(self, node): if self.right is None: self.right = BinaryTree(node) else: tree = BinaryTree(node) tree.right = self.right self.right = tree def insertLeft(self, node): if self.left is None: self.left = BinaryTree(node) else: tree = BinaryTree(node) tree.left = self.left self.left = tree def printTree(tree): if tree is not None: printTree(tree.getLeft()) # Recursive case print(tree.getRoot()) printTree(tree.getRight()) # recursive case if __name__ == "__main__": myTree = BinaryTree("Gigi") myTree.insertLeft("Bob") myTree.insertRight("Cata") myTree.insertRight("Madalina") printTree(myTree)
2ca40ae8cb5255db3205a56d75f9da920f2d500a
brandonnorsworthy/ProjectEuler
/python/p004.py
619
4.125
4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. foundnumber = 0 for x in reversed(range(900,1000)): for y in reversed(range(900,1000)): number = x * y #print(str(number)[0:3], ' r', str(number)[6:2:-1], ' x', x, ' y', y) str1 = str(number)[0:3] str2 = str(number)[6:2:-1] if(str1 == str2): foundnumber = number break if foundnumber != 0: break print(foundnumber)
6c1f23f2cc0d35394d18c6763e4f25adba3eb1f8
sabuhish/python_advance
/inheritence.py
1,649
4.21875
4
class Decimal: ''' define init method and here put in the number and also the places ''' def __init__(self, number, places): self.number = number self.places = places ''' print a object of this class we are going to do so using the repr method format to print out floating point numbers. 15.68 number of them are places and the F is for floating point ''' def __repr__(self): #return "%.2f" % self.number #old version return "%.{}f".format(self.places) % self.number def add(self): pass ''' when we print repr method is going to called 15.68 ''' print(Decimal(15.6789,3)) ''' Currency inherits from Decimal currently it does nothings Except it does everything that the decimal class does. That's what inheritance it's all of the things. Decimal can do. properties methods from it. inheritance is just like in nature. ''' class Currency(Decimal): ''' this class currency has superclass a parent class. it's getting the superclass which is decimal and it's calling the init method ''' def __init__(self,symbol, number, places): super().__init__(number, places) self.symbol = symbol ''' symbol does not write so lets overwtite it. that calls symbol and super class superclasses repr method, uses self places and numbers, calling class repr in the up ''' def __repr__(self): return "{}{}".format(self.symbol, super().__repr__()) # this method of Currency not Decimal def add_currency(self, currency): #exchagne between currencies pass print(Currency("$",15.6789,3))
69f1da4649f2077cc89ec915e10165e0decb749a
findingxvlasova/my-works
/methods.py
2,868
3.84375
4
class Human: def __init__(self, name, age=0): self._name = name self._age = age def _say(self, text): print(text) def sayName(self): self._say(f"Hello, I am {self._name}.") def sayHowOld(self): self._say(f"I am {self._age} y.o.") class Planet: def __init__ (self,name, population = None): self.name = name self.population = population or [] #def addHuman(self, human): #print(f"welcome to {self.name}, {human.name}.") #self.population.append(human) earth = Planet('Earth') katia = Human('Katia') #earth.addHuman(katia) katia = Human('Katia', 19) katia.sayName() #Hello, I am Katia. class Human1: def __init__(self, name, age=0): self.name = name self.age = age def getAge(self): return self.age @staticmethod def AgeIsValid(age): return 18<=age<150 katia = Human1("Katia", 19) katia.AgeIsValid(katia.getAge()) #True def extractDesc(userString): return userString def extractDate(userString): return userString class Event: def __init__(self, description, eventDate): self.description = description self.date = eventDate def __str__(self): return f"Event {self.description} at {self.date}" @classmethod def fromString(cls, userInput): desc = extractDesc(userInput) date = extractDate(userInput) return cls(desc, date) from datetime import date eventDesc = 'Pashas HB.' eventDate = date.today() event = Event(eventDesc, eventDate) print(event) #Event Pashas HB. at 2021-07-20 event = Event.fromString('домабить в мой календарь пашин день рождения 12 июля') print(event) #Event домабить в мой календарь пашин день рождения 12 июля at домабить в мой календарь пашин день рождения 12 июля class Robot: def __init__(self, power): self.power = power def sertPower(self, power): if power < 0: self.power = 0 else: self.power = power wall_e = Robot(100) wall_e.power = -200 print(wall_e.power) #-200 class Robot: def __init__(self, power): self._power = power power = property() @power.setter def power(self, val): if val < 0: self._power = 0 else: self._powerr = val @power.getter def power(self): return self._power @power.deleter def power(self): print('male robot useless') del self._power wall_e = Robot(100) wall_e.power = -200 print(wall_e.power) #0
5bb35ed02ea50f767783dc39cca986ed366efe1a
Guzhengyang/DSA
/linked_list.py
2,151
3.953125
4
class Node: def __init__(self, data, next=None): self.data = data self.next = next def __str__(self): if self is None: return Node current = self res = [] while current is not None: res.append(current.data) current = current.next return str(res) def insert(node, data): node_new = Node(data, None) if node is None: return node_new current = node if current.next is not None: temp = current.next current.next = node_new node_new.next = temp else: current.next = node_new def search(head, data): current = head while current is not None: if current.data == data: return True current = current.next return False def delete(head, data): if head.data == data: return head.next prev = head current = head.next while current is not None: if current.data == data: temp = current.next prev.next = temp return head prev = current current = current.next return head def reverse(head): current = head prev = None while current.next is not None: temp = current.next current.next = prev prev = current current = temp current.next = prev return current def reverse_pair(head): if head is None: return None if head.next is None: return head left = head right = head.next.next head = head.next left.next = right head.next = left head.next.next = reverse_pair(head.next.next) return head if __name__ == '__main__': node4 = Node(8, None) node3 = Node(6, node4) node2 = Node(4, node3) node1 = Node(2, node2) head = Node(0, node1) print('head: ', head) insert(node3, 33) print('head after insertion: ', node3) print('search result: ', search(head, 7)) print('delete result: ', delete(head, 6)) # print('reversed: ', reverse(head)) print('before reverse pair: ', head) print('pair reversed: ', reverse_pair(head))
6ad499b11c5e386a9dc8eeec985896d02f69dac2
luppieliz/MicroBit-Digital-Watch
/main.py
1,463
3.640625
4
hours = 0 minutes = 0 adjust = 0 time = "" ampm = False time = "" minutes = 0 hours = 0 def on_gesture_shake(): global time time = str(hours) + (":" + str(minutes)) basic.show_string(time) input.on_gesture(Gesture.SHAKE, on_gesture_shake) hours = 0 def on_button_pressed_a(): global hours if hours < 23: hours += 1 else: hours = 0 input.on_button_pressed(Button.A, on_button_pressed_a) minutes = 0 def on_button_pressed_b(): global minutes if minutes < 59: minutes += 1 else: minutes = 0 input.on_button_pressed(Button.B, on_button_pressed_b) ampm = False def on_button_pressed_ab(): global ampm ampm = not (ampm) input.on_button_pressed(Button.AB, on_button_pressed_ab) minutes = 0 hours = 0 def on_forever(): global minutes, hours basic.pause(60000) if minutes < 59: minutes += 1 else: minutes = 0 if hours < 23: hours += 1 else: hours = 0 basic.forever(on_forever) minutes = 0 hours = 0 adjust = 0 time = "" ampm = False def on_gesture_drop(): global adjust, time adjust = hours if ampm: if hours > 12: adjust = hours - 12 else: if hours == 0: adjust = 12 time = "" + str(adjust) time = time + ":" if minutes < 10: time = time + "0" time = time + str(minutes) input.on_gesture(Gesture.SHAKE, on_gesture_shake)
6943a998fe3f9924be0fa3e2f52ff363675ec13e
yesdino/review_before_interview
/算法与数据结构/数据结构与算法进阶/24_26_DynamicPrograming/code/1_给定的数求和的不同方式.py
494
3.609375
4
# 题: # Given n, find the number of different ways to write n as the sum of 1, 3, 4. # 给一个 n, 求 1,3,4 相加得到 n 的所有相加方式 # 公式: D(n) = D(n-1) + D(n-3) + D(n-4) def coin(n): dp = [0] * (n + 1) dp[0] = dp[1] = dp[2] = 1 dp[3] = 2 for i in range(4, n + 1): dp[i] = dp[i - 1] + dp[i - 3] + dp[i - 4] # D(n) = D(n-1) + D(n-3) + D(n-4) return dp[n] if __name__ == "__main__": print(coin(5)) # 6 print(coin(10)) # 64
518870a8eda2f77b05ba5355c94edb35e9d91280
pyl135/Introduction-to-Computing-using-Python
/Unit 5- Objects and Algorithms/Ch 5.2- Algorithms/Binary search.py
838
4.03125
4
def looping_binary_search(searchList, searchTerm): searchList.sort() min = 0 max = len(searchList) - 1 while min <= max: currentMiddle = (min + max) // 2 if searchList[currentMiddle] == searchTerm: return True elif searchTerm < searchList[currentMiddle]: max = currentMiddle - 1 else: min = currentMiddle + 1 return False def recursive_binary_search(searchList, searchTerm): searchList.sort() if len(searchList) == 0: return False middle = len(searchList) // 2 if searchList[middle] == searchTerm: return True elif searchTerm < searchList[middle]: return binary_search(searchList[:middle], searchTerm) else: return binary_search(searchList[middle + 1:], searchTerm)
943fbf8dc3cefa885b32770ef086f32ee4cd8d99
PrakharKopergaonkar/LeetCode-June-Challenge
/Question8.py
357
3.578125
4
#Question 8 : Power of Two import math class Solution: def isPowerOfTwo(self, n: int) -> bool: if(n==1): return True elif(n<=0): return False else: m = math.log10(n)/math.log10(2) if(math.ceil(m) == math.floor(m)): return True return False
9e8439b87d19000a3593b4a74b1db1bafe26d11e
smileshy777/practice
/linked_list/Reverse_Nodes_in_k-Group.py
1,189
4.03125
4
''' Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next or k == 1: return head first = ListNode(0) p = first num = 0 left = head while head: num += 1 right = head head = head.next if num == k: num = 0 right.next = None left_node, right_node = self.reverse_node(left, right) p.next = left_node p = right_node left = head p.next = left return first.next def reverse_node(self, left, right): last = None re_last = left while left: left_next = left.next left.next = last last = left left = left_next return right, re_last
e5e7c1b80b06d4c4504faaa71cb872472be1eeec
naveensridhar/cci
/chapter_01/1_05_string_compression.py
676
3.796875
4
import sys #Try to compress string. Example input: aaaabba output: a4b2a1 if compressed data is smaller than the input def compress_string(input): char_counter = 0 prev_char = input[0] new_str_list = [] for i in input: if prev_char == i: char_counter = char_counter + 1 else: new_str_list.append(prev_char) new_str_list.append(str(char_counter)) prev_char = i char_counter = 1 new_str_list.append(prev_char) new_str_list.append(str(char_counter)) if len(new_str_list) < len(input): return "".join(new_str_list) return input print compress_string(sys.argv[1])
070dd67cedd49c4f12f805eec9e0748ab32a673e
moizsiraj/RSA
/rsa.py
1,663
3.5
4
import sympy as sp def validInputs(p, q): return sp.isprime(p) and sp.isprime(q) def checkCoprime(n): coprimes = [] for i in range(0, n): if sp.gcd(i, n) == 1: coprimes.append(i) return coprimes def getKeys(): values = [] p = int(input('input p: ')) q = int(input('input q: ')) n = -1 if not validInputs(p, q): print('invalid p or q or both') else: n = p * q z = (p - 1) * (q - 1) coprimes = checkCoprime(n) print('select e from given list') print(coprimes) e = int(input('e: ')) d = int((1 + z) / e) values.append(e) values.append(d) values.append(n) print('PU: {' + str(e) + ', ' + str(n) + ' }') print('PR: {' + str(d) + ', ' + str(n) + ' }') return values def encrypt(text, e, n): encrypted = [] for i in text: value = -1 if 65 <= ord(i) <= 90: value = ord(i) - 64 elif 97 <= ord(i) <= 122: value = ord(i) - 96 else: print('invalid character') exit(0) value = pow(value, e) value = value % n encrypted.append(value) print(encrypted) return encrypted def decrypt(text, d, n): decrypted = [] for character in text: temp = pow(character, d) temp = temp % n decrypted.append(chr(temp + 64)) print(decrypted) return decrypted def RSA(): text = input('input text to be encrypted:') values = list(getKeys()) e = int(values[0]) d = int(values[1]) n = int(values[2]) encrypted = encrypt(text, e, n) decrypted = decrypt(encrypted, d, n) RSA()
b2d07b5b0584b9a1c3c06fa1c2f896bde0c242fc
Marat-R/Ch1-P3-Task1
/Task1.py
663
4.03125
4
users_text = input("Input your text: ") counter_up = 0 # Счетчик букв в верхнем регистре counter_low = 0 # Счетчик букв в нижнем регистре for letter in users_text: if letter.isupper(): counter_up += 1 elif letter.islower(): counter_low += 1 print(counter_up) print(counter_low) print("Up %: ", round(counter_up / ((counter_up + counter_low) / 100))) print("Low %: ", round(counter_low / ((counter_up + counter_low) / 100))) # one_percent = (counter_up + counter_low) / 100 # print(round(counter_up / one_percent), 2) # print(round(counter_low / one_percent), 2)