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
46ef97a9715a56b3fc255fbda074468e2ca9c299
Billy-Q/learn_python
/day01/day01_8.py
1,028
3.859375
4
''' ********** Date: 2021-10-28 Author: Billy-Q ********** ''' # 1.我们出拳 定义变量保存用户输入 my = int(input('请输入出拳')) # 2.电脑随机出拳(假定电脑出石头) com = 1 # 3.判断胜负 if (my==1 and com==2) or (my==2 and com==3) or (my==3 and com==1): # 用户胜利 print('用户胜利, my=%d,com=%d'%(my,com)) elif my==com: print('平局,决战到天亮') else: print('电脑胜利,my=%d,com=%d'%(my,com)) # python生成随机数 random import random # 1.我们出拳 定义变量保存用户输入 my = int(input('请输入出拳:')) # 2.电脑随机出拳(假定电脑出石头) # 指定开始 结束 包含开始包含结束 com = random.randint(1,3) # 3.判断胜负 if (my==1 and com==2) or (my==2 and com==3) or (my==3 and com==1): # 用户胜利 print('用户胜利,my=%d,com=%d'%(my,com)) elif my==com: print('平局,决战到天亮,my=%d,com=%d'%(my,com)) else: print('电脑胜利,my=%d,com=%d'%(my,com))
7e2b4918ca8404278db3fb3e02b690ba578e509e
mak705/Python_interview
/python_prgrams/testpython/if6.py
143
4.09375
4
num = 7 if num == 5: print("HI I AM 5") elif num == 11: print("Number is 11") elif num == 7: print ("i am 7") else: print("not 5 7 11")
1297e534aba2896e3af4d8300b90269e7d1a3e4c
DanecLacey/GUI_Projects
/calculator/simple_calculator.py
2,870
4.0625
4
from tkinter import * import util as ut #Set the root object for tkinter root = Tk() root.title("Simple Calculator") #set the entry object e = Entry(root, width = 35, borderwidth = 5) e.grid(row = 0, column = 0, columnspan = 3, padx = 10, pady = 10) #define buttons button_1 = Button(root, text = "1", padx = 40, pady = 20, command = lambda: ut.button_click(e, 1)) button_2 = Button(root, text = "2", padx = 40, pady = 20, command = lambda: ut.button_click(e, 2)) button_3 = Button(root, text = "3", padx = 40, pady = 20, command = lambda: ut.button_click(e, 3)) button_4 = Button(root, text = "4", padx = 40, pady = 20, command = lambda: ut.button_click(e, 4)) button_5 = Button(root, text = "5", padx = 40, pady = 20, command = lambda: ut.button_click(e, 5)) button_6 = Button(root, text = "6", padx = 40, pady = 20, command = lambda: ut.button_click(e, 6)) button_7 = Button(root, text = "7", padx = 40, pady = 20, command = lambda: ut.button_click(e, 7)) button_8 = Button(root, text = "8", padx = 40, pady = 20, command = lambda: ut.button_click(e, 8)) button_9 = Button(root, text = "9", padx = 40, pady = 20, command = lambda: ut.button_click(e, 9)) button_0 = Button(root, text = "0", padx = 40, pady = 20, command = lambda: ut.button_click(e, 0)) button_add = Button(root, text = "+", padx = 39, pady = 20, command = lambda: ut.button_add(e)) button_sub = Button(root, text = "-", padx = 39, pady = 20, command = lambda: ut.button_sub(e)) button_mult = Button(root, text = "*", padx = 39, pady = 20, command = lambda: ut.button_mult(e)) button_div = Button(root, text = "/", padx = 39, pady = 20, command = lambda: ut.button_div(e)) button_equal = Button(root, text = "=", padx = 89, pady = 20, command = lambda: ut.button_equal(e)) button_mod = Button(root, text = "%", padx = 38, pady = 20, command = lambda: ut.button_mod(e)) button_pow = Button(root, text = "^", padx = 39, pady = 20, command = lambda: ut.button_pow(e)) button_clear = Button(root, text = "Clear", padx = 100, pady = 20, command = lambda: ut.button_clear(e)) #put buttons on the screen button_1.grid(row = 3, column = 0) button_2.grid(row = 3, column = 1) button_3.grid(row = 3, column = 2) button_4.grid(row = 2, column = 0) button_5.grid(row = 2, column = 1) button_6.grid(row = 2, column = 2) button_7.grid(row = 1, column = 0) button_8.grid(row = 1, column = 1) button_9.grid(row = 1, column = 2) button_0.grid(row = 4, column = 0) button_equal.grid(row = 4, column = 1, columnspan = 2) button_clear.grid(row = 7, column = 0, columnspan = 3) button_add.grid(row = 5, column = 0) button_sub.grid(row = 5, column = 1) button_mult.grid(row = 5, column = 2) button_div.grid(row = 6, column = 0) button_mod.grid(row = 6, column = 1) button_pow.grid(row = 6, column = 2) #necessary tkinter loop root.mainloop()
322f4e4bd46165b5440aa67d9328f90d5a17cbed
JLMarshall63/myGeneralPythonCode_B
/SynchronousPython.py
216
3.59375
4
#Example standard synchronous Python #prints hello waits 3 sec the prints world from time import sleep def hello(): print('Hello') sleep(3) print('World!') if __name__ == '__main__': hello()
c701e79927f5b435adb8f281414d1b55a2a04fdb
Skipper609/python
/Sample/class eg/lab questions/2B/4.py
592
3.671875
4
class Account : def __init__(self, accno , name, balance): self.accno = accno self.name = name self.balance = balance def deposit(self, deposit_amount): self.balance += deposit_amount def withdraw(self, withdraw_amount): self.balance -= withdraw_amount def show_info(self): print(f"Account number :{self.accno}\nName : {self.name}\nBalance : {self.balance}") obj_1 = Account(123, "Robin" , 10000) obj_2 = Account(124, "Da bank" , 20000) obj_1.deposit(100) obj_2.withdraw(500) obj_1.show_info() obj_2.show_info()
7ce5ddf7c1bc2e14ae1ade4fa724f32298867b33
farean/TDDPythonRomanConverter
/consoleinitial.py
3,336
3.546875
4
class NumbersRoman: def __init__(self, arg): super(NumbersRoman, self).__init__() self.arg = arg def ValidateNumber(entervalue): letters=['I','V','X','L','C','D','M'] retvalue=True for x in list(entervalue): if (x not in letters): retvalue=False break return retvalue def RomToDec(entervalue): sumvalue=0 itembefore="" numberbefore=0 if not NumbersRoman.ValidateNumber(entervalue): return "NAN" for item in range(len(entervalue)): strnumber=entervalue[item] returnvalue=NumbersRoman.LetterToDecimal(strnumber) #print(item,strnumber,returnvalue) if numberbefore < returnvalue: returnvalue-=(numberbefore *2) numberbefore=returnvalue sumvalue += returnvalue return sumvalue def LetterToDecimal(param): if param == "I": return 1 elif param == "V": return 5 elif param == "X": return 10 elif param == "L": return 50 elif param == "C": return 100 elif param == "D": return 500 elif param == "M": return 1000 else: return 0 def converttoroman(valor): strreturn="" letter="" if not (str(valor).isdigit()): return "NAN" if valor == 0: return "" else: if NumbersRoman.isFourOrNine(valor): letter = NumbersRoman.FourOrNine(valor) decrease =NumbersRoman.DecreaseFourOrNine(valor) else: letter=NumbersRoman.Letter(valor) decrease=NumbersRoman.Decrease(valor) strreturn = strreturn + letter + NumbersRoman.converttoroman(valor-decrease) return strreturn def DecreaseFourOrNine(valor): repeatnumber=len(str(valor))-1 digitnumber=int(str(valor)[0]) strbeforenumber=str(digitnumber) for valor in range(repeatnumber): strbeforenumber += "0" return int(strbeforenumber) def FourOrNine(valor): repeatnumber=len(str(valor))-1 digitnumber=int(str(valor)[0]) strbeforenumber="1" strafternumber=str(digitnumber + 1) for valor in range(repeatnumber): strbeforenumber += "0" for valor in range(repeatnumber): strafternumber += "0" antes=NumbersRoman.Letter(int(strbeforenumber)) despues=NumbersRoman.Letter(int(strafternumber)) return antes + despues def isFourOrNine(valor): strvalor=str(valor) numbers=len(strvalor) numfirstdigit=0 if numbers <= 0: return False else: numfirstdigit=int(strvalor[0]) if numfirstdigit == 4 or numfirstdigit == 9: return True else: return False def Letter(valor): strLetter="" if valor >= 1 and valor < 4: strLetter="I" elif valor >=4 and valor <9: strLetter = "V" elif valor >=9 and valor <50: strLetter="X" elif valor >=50 and valor < 90: strLetter="L" elif valor >=90 and valor < 100: strLetter="X" elif valor >=100 and valor < 500: strLetter="C" elif valor >=500 and valor < 1000: strLetter="D" elif valor >=1000 and valor < 5000: strLetter="M" return strLetter def Decrease(valor): decrease=0 if valor >= 1 and valor < 4: decrease=1 elif valor >=4 and valor <9: decrease = 5 elif valor >=9 and valor <50: decrease=10 elif valor >=50 and valor < 90: decrease=50 elif valor >=90 and valor < 100: decrease=90 elif valor >=100 and valor < 500: decrease=100 elif valor >=500 and valor < 1000: decrease=500 elif valor >=1000 and valor < 5000: decrease=1000 return decrease
2572e593338c29a8a19bc1dbfefb81969f8401f8
MCBoarder289/PythonArcadeGames
/Chapter 11 - Bitmapped Graphics and Sound/Chapter 11 Lesson.py
2,455
3.8125
4
""" Pygame base template for opening a window Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Explanation video: http://youtu.be/vRB_983kUMc """ import pygame # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) pygame.init() # Set the width and height of the screen [width, height] size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Chapter 11 Lesson") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Loading background image / sounds background_image = pygame.image.load("saturn_family1.jpg").convert() # Image from http://ProgramArcadeGames player_image = pygame.image.load("player.png").convert() # Image from http://ProgramArcadeGames player_image.set_colorkey(BLACK) click_sound = pygame.mixer.Sound("laser5.ogg") # Hide the mouse cursor pygame.mouse.set_visible(0) # Play "O Fortuna" by MIT Choir # Available from: # http://freemusicarchive.org/music/MIT_Concert_Choir/Carmina_Burana_Carl_Orff/01_1355 pygame.mixer.music.load('MIT_Concert_Choir_-_01_-_O_Fortuna.mp3') pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) pygame.mixer.music.play() # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: click_sound.play() # --- Game logic should go here # Get the current mouse position. This returns the position # as a list of two numbers. player_position = pygame.mouse.get_pos() x = player_position[0] y = player_position[1] # --- Screen-clearing code goes here # Here, we clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. # If you want a background image, replace this clear with blit'ing the # background image. screen.blit(background_image, [0, 0]) # Copy image to screen: screen.blit(player_image, [x, y]) # --- Drawing code should go here # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # Close the window and quit. pygame.quit()
87db4d955c9be83ce81db41757cac3285b6ab324
fedorrb/Python
/Prometheus/8/84.py
2,586
3.96875
4
# -*- coding: utf-8 -*- def make_sudoku(size): sudoku = [] size_sud = size ** 2 arr = range(1,size_sud + 1) def moveSize(arr): new_arr = arr[size:] + arr[:size] return new_arr def move1(arr): new_arr = arr[1:] + arr[:1] return new_arr for i in range(size_sud): sudoku.append(arr) if (i+1) % size == 0: arr = move1(arr) else: arr = moveSize(arr) return sudoku #********************************************* # після спроби скласти вручну (на папері) судоку розмірностей 2, 3, 4 можна помітити, # що достатньо побудувати перші size квадратів, а інші можна отримати з них зсувом вліво або вправо # всередині перших size квадратів перший рядок може бути записаний довільним чином (наприклад, числа послідовно) # інші рядки.. також можна отримати зсувом, лише на цілий квадрат # до речі, схожий евристичний алгоритм можна знайти і в інтернеті def make_sudoku1(size): s = [] # заповнюємо перші квадрати # замість обчислення полів по одному, в список-рядок можна генерувати готові шматки за допомогою range() for i in range(size): s.append(range(i * size + 1, size**2 + 1)) s[i].extend(range(1, i * size +1)) # для того, щоб не мучитися далі з додаванням елементів до списку, створимо їх одразу тут, заповнимо нулями for i in range(size, size**2): s.append([]) for j in range(size**2): s[i].append(0) # тепер заповнюємо "нулі", копіюючи числа з попередніх квадратів "по діагоналі" # здається, тут можна було обійтися 2 циклами, не розмежовуючи окремі квадрати між собою for i in range(1,size): for j in range(0,size): for ii in range(0, size**2): s[i*size + j][ii] = s[(i-1)*size + j][(ii+1)%(size**2)] return s #********************************************* print make_sudoku(2) print make_sudoku1(2)
138cd74945e53d7035ccea5e3a1edc34972f0472
fkfouri/HackerHank_PythonStudy
/30 Days of Code/18 - Queues and Stacks.py
641
3.921875
4
#https://www.hackerrank.com/challenges/30-queues-stacks/problem #https://docs.python.org/2/tutorial/datastructures.html class Solution: def __init__ (self): self.q = [] #Queue self.s = [] #Stack self.reverse = False #Stack def pushCharacter(self, ch): self.s.append(ch) def popCharacter(self): return self.s.pop() #Queue def enqueueCharacter(self, ch): self.q.append(ch) def dequeueCharacter(self): if self.reverse == False: self.reverse = True self.q.reverse() return self.q.pop()
e8f0ccadb4447896140996e552deb8a281427ac2
AdamZhouSE/pythonHomework
/Code/CodeRecords/2111/60708/272746.py
509
3.734375
4
numof=int(input()) i=0 n=1 n1=1 while(i<numof): n=n1 check=True if(n==2 or n==3 or n==5): check=True else: while (check): if (n % 2 == 0): n = int(n / 2) elif (n % 3 == 0): n = int(n / 3) elif (n % 5 == 0): n = int(n / 5) elif (n == 1): break else: check = False break if(check): i=i+1 n1=n1+1 print(n1-1)
d18213efa9d3286e56a2b9fd9ab05b18604d4243
shalu169/lets-be-smart-with-python
/generator.py
841
4.3125
4
# generator function # Unlike regular functions which on encountering a return statement terminates entirely, # generators use yield statement in which the state of the function is saved from the last call and # can be picked up or resumed the next time we call a generator function. # Another great advantage of the generator over a list is that it takes much less memory. def generator_function(): yield 2 yield 3 yield 4 # way 1 print(generator_function()) # this is an generator function count = 0 for i in generator_function(): count += 1 print(i) # print print('no of time loop executes', count) # 3 times loop executes # every time function is called 1 yield executes # way 2 :make a generator object x = generator_function() print(next(x)) print(x.__next__()) print(x.__next__()) # print(x.__next__())
7777b0e1002aa240eb8544797bf9711bb88abcd3
bitsandpieces-1984/python_samples
/is_armstrong.py
889
4.125
4
""" The k-digit number N is an Armstrong number if and only if the k-th power of each digit sums to N. Given a positive integer N, return true if and only if it is an Armstrong number. Example 1: Input: 153 Output: true Explanation: 153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3. Example 2: Input: 123 Output: false Explanation: 123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36. """ class Solution: def isArmstrongv1(self, N): sum_total = sum([int(x) ** len(str(N)) for x in str(N)]) if sum_total == N: return True else: return False def isArmstrongv2(self, N): sum_total = sum(map(lambda x: int(x) ** len(str(N)), list(str(N)))) if sum_total == N: return True else: return False obj = Solution() print(obj.isArmstrongv1(153)) print(obj.isArmstrongv1(153))
c24a97de0006a6812cf3cb1fec0a82539dcbfa03
BerilBBJ/scraperwiki-scraper-vault
/Users/S/sym/adnams-pubs.py
4,858
3.515625
4
import csv import re import urllib2 import BeautifulSoup from scraperwiki import datastore from scraperwiki import geo class Outcodes(): def __init__(self): self.download_outcodes() def download_outcodes(self): """ Downloads a CSV file from http://www.freemaptools.com/ and puts it in memory. """ req = urllib2.urlopen('http://www.freemaptools.com/download/postcodes/postcodes.csv') self.outcodes = csv.DictReader(req) def next(self): return self.outcodes.next() def __iter__(self): return self class Scrape(): def __init__(self): pass def scrape(self, code): """ Submits the form and returns the file like response object. """ self.page = urllib2.urlopen("http://adnams.co.uk/beer/pub-finder?postcode=%s" % code) def parse(self): soup = BeautifulSoup.BeautifulSoup(self.page) results = [] for result in soup.find('ul', id='pub-results').findAll('li'): pub = {} pub['name'] = result.h3.string if not pub.get('name'): pub['name'] = result.h3.a.string pub['address-line1'] = result.find('', {'class' : 'pub-address-line1'}).string pub['address-line2'] = result.find('', {'class' : 'pub-address-line2'}).string pub['address-line3'] = result.find('', {'class' : 'pub-address-line3'}).string pub['address-town'] = result.find('', {'class' : 'pub-address-town'}).string pub['address-county'] = result.find('', {'class' : 'pub-address-county'}).string pub['address-postcode'] = result.find('', {'class' : 'pub-address-postcode'}).string pub['telephone'] = result.find('', {'class' : 'pub-telephone'}).string pub['website'] = result.find('', {'class' : 'pub-website'}).string for k,v in pub.items(): if not v: del pub[k] results.append(pub) return results scraper = Scrape() for code in Outcodes(): if code['outcode'][:2] == "IP" or code['outcode'][:2] == "NR": scraper.scrape(code['outcode']) results = scraper.parse() for pub in results: datastore.save(['name','address-postcode'], pub, latlng=geo.gb_postcode_to_latlng(pub['address-postcode'])) import csv import re import urllib2 import BeautifulSoup from scraperwiki import datastore from scraperwiki import geo class Outcodes(): def __init__(self): self.download_outcodes() def download_outcodes(self): """ Downloads a CSV file from http://www.freemaptools.com/ and puts it in memory. """ req = urllib2.urlopen('http://www.freemaptools.com/download/postcodes/postcodes.csv') self.outcodes = csv.DictReader(req) def next(self): return self.outcodes.next() def __iter__(self): return self class Scrape(): def __init__(self): pass def scrape(self, code): """ Submits the form and returns the file like response object. """ self.page = urllib2.urlopen("http://adnams.co.uk/beer/pub-finder?postcode=%s" % code) def parse(self): soup = BeautifulSoup.BeautifulSoup(self.page) results = [] for result in soup.find('ul', id='pub-results').findAll('li'): pub = {} pub['name'] = result.h3.string if not pub.get('name'): pub['name'] = result.h3.a.string pub['address-line1'] = result.find('', {'class' : 'pub-address-line1'}).string pub['address-line2'] = result.find('', {'class' : 'pub-address-line2'}).string pub['address-line3'] = result.find('', {'class' : 'pub-address-line3'}).string pub['address-town'] = result.find('', {'class' : 'pub-address-town'}).string pub['address-county'] = result.find('', {'class' : 'pub-address-county'}).string pub['address-postcode'] = result.find('', {'class' : 'pub-address-postcode'}).string pub['telephone'] = result.find('', {'class' : 'pub-telephone'}).string pub['website'] = result.find('', {'class' : 'pub-website'}).string for k,v in pub.items(): if not v: del pub[k] results.append(pub) return results scraper = Scrape() for code in Outcodes(): if code['outcode'][:2] == "IP" or code['outcode'][:2] == "NR": scraper.scrape(code['outcode']) results = scraper.parse() for pub in results: datastore.save(['name','address-postcode'], pub, latlng=geo.gb_postcode_to_latlng(pub['address-postcode']))
e4d4d066f9e9c0789e4f0a7bf41ad75cd9b28681
dyhwong/projecteuler
/Problem 015.py
248
3.890625
4
def factorial(n): product = 1 for i in range(n): product *= (i + 1) return product def choose(n, k): return factorial(n) / (factorial(k) * factorial(n - k)) rows = 20 cols = 20 n = rows + cols k = rows print choose(n, k)
7697f46c2bd182c2f2aa89ba5a712f4aea69f0a4
sdpy5/pythonlearning
/list_in_dict.py
362
3.9375
4
classes = { 'teachers' : 'srinivas murthy', 'students' : ['sangith','dharshan','sushagh','shravanya'] } print('the class teacher is : ' + classes['teachers'] + '.') print('the students are : ') for student in classes['students']: print('\t' + student.title()) if student == 'sushagh': print('sushagh is the favourite student')
bce7358927e74e37b27370b59b71b9252361d2e0
nkini/SplitWiser
/SplitWiser.py
2,045
3.75
4
import sys print("Welcome to SplitWiser") def fileinput(): with open(sys.argv[1]) as f: linecount = 1 for line in f: if linecount == 1: amt_list = {k:[] for k in line.strip().split(' ')} else: amt, *patrons = line.strip().split( ) for patron in patrons: amt_list[patron].append(float(amt)/len(patrons)) linecount += 1 print("Overview: ") print(amt_list) caculate_splits(amt_list) def commandline(): print("For any prompt, type quit and enter to exit.") initials = input("Enter each person's initials separated by space: ") amt_list = {k:[] for k in initials.strip().split(' ')} print("Calculating splits for:\n"+"\n".join(amt_list.keys())+"\n") while True: amt = input("Enter new amount or quit: ") if amt == 'q' or amt == 'quit': break amt = float(amt) patrons = input("Enter initials: ") patrons = [patron for patron in patrons.strip().split(' ') if patron != ''] for patron in patrons: amt_list[patron].append(amt/len(patrons)) print("Overview: ") print(amt_list) caculate_splits(amt_list) def caculate_splits(amt_list): tax = float(input("Enter Tax: ")) gratuity = float(input("Enter Gratuity: ")) tip = float(input("Enter Tip Amount: ")) person_total = {patron:sum(amts) for patron,amts in amt_list.items()} total_total = sum(person_total.values()) person_total_and_proportion = {patron:(total,total/total_total) for patron,total in person_total.items()} print("Splits:") tally = 0 for person, t_p in person_total_and_proportion.items(): total = t_p[0] prop = t_p[1] final_amt = total + prop*tax + prop*gratuity + prop*tip tally += final_amt print("{} pays {}".format(person,final_amt)) print("\nTally\nBill total : {}".format(tally)) if len(sys.argv) > 1: fileinput() else: commandline()
76c69d38bced270526d63b690831b6d16e90a545
sudo-LuSer/Calculate-the-big-factorials
/factorial.py
521
4.125
4
NMAX=10**5 factorial=[1] def plein_the_factorial(): for i in range(1,NMAX+1): factorial.append(factorial[i-1]*i) def title(): print ("-"*(1.5)*10**2) print("\t\t\t\t\t\t\t"+"welcome to my factorial program using dynamic programming you can calculate n! for all 0<=n<10^5 Enjoy") print ("-"*(1.5)*10**2) plein_the_factorial() title() def run(): try: print("ENTER A POSITIVE INTGER N:") N=int(input()) print("THE N! = ") print(factorial[N]) except ValueError: print("ENTER A NUMBER PLEASE !") run() run()
4b988589a32ea55bdc791048768cd38e3dfcbafe
asadugalib/URI-Solution
/Python3/uri 1131.py
674
3.703125
4
#1131 num_game = 0 inter = 0 gremio = 0 draw = 0 new_game = True while new_game: num_game += 1 x, y = list(map(int, input().split())) if x > y: inter += 1 elif x < y: gremio += 1 else: draw += 1 while True: print("Novo grenal (1-sim 2-nao)") d = input() if d == "1": break elif d == "2": new_game = False break print("{} grenais\nInter:{}\nGremio:{}\nEmpates:{}".format(num_game, inter, gremio, draw)) if inter > gremio: print("Inter venceu mais") elif inter < gremio: print("Gremio venceu mais") else: print("Não houve vencedor")
b17f27d346153766e34373263367ef707f7a77c2
Linerre/LPTHW
/ex33.py
1,087
4.28125
4
i = 0 numbers = [] while i < 6: print(f"At the top i is {i}") # in order: 0, 1, 2, ... 5 numbers.append(i) i = i + 1 print("Numbers now: ", numbers) # [0], [0, 1], [0, 1, 2] ... [0, ..., 5] print(f"At the bottom i is {i}") # 1, 2, 3 ..., 6 print("The numbers: ") for num in numbers: print(num) # below is drills: # drill 1: i = 0 numbers = [] threshold = int(input('Please define the threshold using a whole number: ')) while i < threshold: print(f"At the top i is {i}") numbers.append(i) i = i + 1 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) # drill 2: i = 0 numbers = [] threshold = int(input('Please define the threshold using a whole number: ')) step = int(input('Enter a whole number for the increment at a time: ')) while i < threshold: print(f"At the top i is {i}") numbers.append(i) i = i + step print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num)
15a5b31a3bb7db24952a879e15d3fc9a6265cf8c
Mropat/ComparativeGenomicsMM
/p8/scripts (copy)/average_connectivity.py
309
3.625
4
def average_con(filename): s = set() with open(filename, 'r') as f: f = f.readlines() for line in f: line = line.split(' ') s.add(line[0]) average = len(f)/len(s) print(average) average_con('test.txt')
01aa3a6882efb2c71547df73c5d0a32673c5f006
krxsky/AlgoData
/compress.py
431
3.78125
4
def compress(h): result = {} #dict to store result def helper(h, acc): #acc keeps track of the keys so far if isinstance(h, dict): #reduction step #list comprehension is used as syntactical sugar [helper(v,acc+"_"+k) for k,v in h.items()] else: #base case result[acc[1:]] = h #add to the result dict helper(h, "") return result
0c070931717086aa2456231f9ba27d4e3fda199a
olympiawoj/my-first-blog
/helloworld.py
305
3.9375
4
print('Hello, Django girls!') if 1>2: print('this works') else: print('does not work') def hi(name): print('hi, {}'.format(name)) hi('olympia') girls = ['Andrea', 'Olympia', 'Kendall', 'Courtney'] for name in girls: hi(name) print('Next girl') for i in range(1,6): print(i)
af9f853d66638a96fcd8ec12863c0338eceebefd
museumgeek/likelion_github_session
/word.py
652
4.15625
4
#사용자로부터 인풋이 들어온다 #그 인풋을 받아서 끝자리 음절과 #다음 인풋의 첫 음절이 같아야 통과다 #3글자만 허용 word1=input("끝말잇기를 시작합시다.") #인풋의 값은 기본적으로 string if (len(word1)==3): #계속 진행 while True:#반복문 word2=input() if (len(word2)==3) and (word2[0]==pre_word[2]): print("정답입니다.") pre_word=word2 else: print("오답입니다.") break else: print("오답입니다.") print("게임이 끝났습니다.") #종료 #깃변경사항 체크용
0fb038910bacf4f457d4626bf4f4883a43e0cb7e
LeonSubZero/PythonArchive
/sphere.py
1,728
4.40625
4
""" Flavio Leon 3.30.17 sphere.py Menu-driven interface program that allows the user to: 1.Calc the surface area of a sphere. 2.Calc the volume of a sphere. 3. Quit """" import math def main(): print("Geometry Calculator App...") print() option=0 #Menu while option !==3: print("Choose one of the following options:") print("\t1. Calculate the surface area of a sphere.") print("\t2.Calculate the volume of a sphere.") print("\t3. Quit") option=eval(input("Option: ")) #Drive menu option if option ==1: #Area of a Sphere #Prompt user for radius radius=getRadius() #Calculate area area=sphereArea(radius) #Display result print("The surface area is",area) print() elif option ==2: #Volume of a sphere print() #Prompt user for radius #Calculate the volume #Display result elif option ==3: #Quit print("Good Bye...") print() else: #Invalid option print("Error...invalid try again") #def getRadius() # #Prompt the user for the radius of a sphere, #and returns the value entered. def getRadius(): rad = -1 while rad <0: #Prompt user for radius rad = eval(input("\nPlease enter sphere radius: ")) if rad <0: print("Error...Invalid radius. Try Again") return rad def sphereArea(rad): #Calculate area area = 4* math.pi *rad**2 return area main()
fb42610a1de7885d9a3727277a2ec7d8a21663fe
22pereai/unit-2.1
/python_cookbook/csv_read.py
257
3.78125
4
import csv FILENAME = "trips.csv" spreadsheet = [] with open(FILENAME, newline="") as file: # read from CSV file reader = csv.reader(file) # selected reader for row in reader: # for each row... spreadsheet.append(row) # append it to the list
89281326d18d1b4eba0b2eef187b3dc0f2ec1c80
owain-Biddulph/deep-ail
/utils.py
6,902
3.828125
4
from typing import Tuple, List import math import numpy as np def distance_min(state): """input: state output: la distance minimal entre un de nos groupes et les groupes ennemies""" distances = [] groups = [None, None] for position_nous in state.our_species.tile_coordinates(): distance_cette_unité = math.inf for position_ennemie in state.enemy_species.tile_coordinates(): if distance(position_ennemie, position_nous) < distance_cette_unité: distance_cette_unité = distance(position_ennemie, position_nous) groups[0] = position_nous groups[1] = position_ennemie distances.append(distance_cette_unité) return min(distances), groups def win_probability(attack_troops: int, defense_troops: int, defense_type: int) -> float: """ Return the probability of attacking troops winning a battle :param attack_troops: :param defense_troops: :param defense_type: :return: """ if defense_type == 1: if attack_troops >= defense_troops: return 1 else: return random_battle_win_probability(attack_troops, defense_troops) else: if attack_troops >= 1.5 * defense_troops: return 1 elif defense_troops >= 1.5 * attack_troops: return 0 else: return random_battle_win_probability(attack_troops, defense_troops) def random_battle_win_probability(species_1_units: int, species_2_units: int) -> float: """ Given the number of units, measures the probability that species 1 wins. :param species_1_units: int, number of units of species 1 :param species_2_units: int, number of units of species 2 :return: float, probability that species 1 wins """ if species_1_units <= species_2_units: p = species_1_units / (2 * species_2_units) else: p = species_1_units / species_2_units - .5 return p def expected_battle_outcome(attacking_species_units: int, defending_species_type: int, defending_species_units: int) -> int: """ Returns the expected number of attacking species units to result from battle, note that this is not a simulation. :param attacking_species_units: int, number of units of attacking species :param defending_species_units: int, number of units of defending species :param defending_species_type: int, can be any species (1, 2, 3) :return: int """ expected_outcome = 0 # True if the battle is not an outright win if ((defending_species_units == 1) & (attacking_species_units < defending_species_units)) | ( (defending_species_units != 1) & (attacking_species_units < 1.5 * defending_species_units)): probability_of_winning = random_battle_win_probability(attacking_species_units, defending_species_units) expected_outcome += int(probability_of_winning * attacking_species_units) # Under estimate # If losers are humans, every one of them has a probability of being transformed. if defending_species_type == 1: expected_outcome += int(probability_of_winning * defending_species_units) # Under estimate # If it is an outright win else: expected_outcome += (attacking_species_units >= defending_species_units) * attacking_species_units if defending_species_type == 1: expected_outcome += defending_species_units return expected_outcome def distance(square_1: Tuple[int, int], square_2: Tuple[int, int]) -> int: """ Returns the distance in number of moves between 2 squares :param square_1: tuple, square 1 coordinates :param square_2: tuple, square 2 coordinates :return: int, distance between squares """ return max(abs(square_1[0] - square_2[0]), abs(square_1[1] - square_2[1])) def battle_simulation(species_1_units: int, species_1_type: int, species_2_units: int, species_2_type: int) -> Tuple[int, int]: """ Simulates a battle between two species :param species_1_units: int, number of units of species 1 :param species_1_type: int, species 1 type :param species_2_units: int, number of units of species 2 :param species_2_type: int, species 2 type :return: tuple, battle outcome, winning species type and number of remaining units """ if ((species_2_type == 1) and (species_1_units < species_2_units)) or ((species_2_type != 1) and ( species_1_units < 1.5 * species_2_units) and species_2_units < 1.5 * species_1_units): p = random_battle_win_probability(species_1_units, species_2_units) # If species 1 wins if p >= np.random.random(): # Every winner's unit has a probability p of surviving. winner = species_1_type remaining_units = np.random.binomial(species_1_units, p) if species_2_type == 1: # If losers are humans, every one of them has a probability p of being transformed. remaining_units += np.random.binomial(species_2_units, p) # If species 2 wins else: winner = species_2_type # Every winner's unit has a probability 1-p of surviving remaining_units = np.random.binomial(species_2_units, 1 - p) else: winner = species_1_type if species_1_units >= species_2_units else species_2_type if winner == species_1_type: remaining_units = species_1_units + (species_2_type == 1) * species_2_units else: remaining_units = species_2_units return winner, remaining_units def species_coordinates(state, species: int) -> List[Tuple[int, int]]: """ Returns a list of coordinates of all the squares occupied by a given species :param state: The current state object :param species: The species to look for :return: """ return list(zip(*np.where(state.board[:, :, 0] == species))) def ordered_board_content_for_given_coordinates(state, coordinate_list: List[Tuple[int, int]] ) -> List[Tuple[int, int, int, int]]: """ Returns the contents of the squares given a list of coordinates :param state: The current state object :param coordinate_list: List of coordinates :return: List of tuples containing square contents, the format is [x, y, species type, unit count] ordered by count """ contents = [] if len(coordinate_list) == 0: return contents for coordinates in coordinate_list: temp = [coordinates[0], coordinates[1]] temp.extend(state.board[coordinates[0], coordinates[1]]) contents.append(temp) contents = np.array(contents) contents = contents[contents[:, -1].argsort()] return contents def hash_array(array: np.ndarray) -> int: return array.tobytes()
57bad52d9052fe6580d65bf22666462319380e2e
opwe37/Algorithm-Study
/LeetCode/src/1195.py
1,029
3.625
4
import threading class FizzBuzz: def __init__(self, n: int): self.n = n self.b = threading.Barrier(4) # printFizz() outputs "fizz" def fizz(self, printFizz: 'Callable[[], None]') -> None: self.handler(lambda x: x % 3 == 0 and x % 5, printFizz) # printBuzz() outputs "buzz" def buzz(self, printBuzz: 'Callable[[], None]') -> None: self.handler(lambda x: x % 5 == 0 and x % 3, printBuzz) # printFizzBuzz() outputs "fizzbuzz" def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None: self.handler(lambda x: x % 5 == 0 and x % 3 == 0, printFizzBuzz) # printNumber(x) outputs "x", where x is an integer. def number(self, printNumber: 'Callable[[int], None]') -> None: self.handler(lambda x: x % 5 and x % 3, printNumber, True) def handler(self, check, sucess, parameter=False): for i in range(1, self.n+1): if check(i): sucess(i) if parameter else sucess() self.b.wait()
c2ad347df17df6f686c93b27774a29c8be92b84d
ancuongnguyen07/TUNI_Prog1
/Week11/fraction.py
6,593
3.96875
4
""" COMP.CS.100 Ohjelmointi 1 / Programming 1 Fractions code template """ class Fraction: """ This class represents one single fraction that consists of numerator (osoittaja) and denominator (nimittäjä). """ def __init__(self, numerator, denominator): """ Constructor. Checks that the numerator and denominator are of correct type and initializes them. :param numerator: int, fraction's numerator :param denominator: int, fraction's denominator """ # isinstance is a standard function which can be used to check if # a value is an object of a certain class. Remember, in Python # all the data types are implemented as classes. # ``isinstance(a, b´´) means more or less the same as ``type(a) is b´´ # So, the following test checks that both parameters are ints as # they should be in a valid fraction. if not isinstance(numerator, int) or not isinstance(denominator, int): raise TypeError # Denominator can't be zero, not in mathematics, and not here either. elif denominator == 0: raise ValueError self.__numerator = numerator self.__denominator = denominator def return_string(self): """ :returns: str, a string-presentation of the fraction in the format numerator/denominator. """ sign = "" if self.__numerator * self.__denominator < 0: sign = "-" """else: sign = """"" return f"{sign}{abs(self.__numerator)}/{abs(self.__denominator)}" def simplify(self): """ Simplify the fraction """ gcd = greatest_common_divisor(self.__denominator,self.__numerator) """self.__denominator //= gcd self.__numerator //= gcd""" return Fraction(self.__numerator // gcd, self.__denominator // gcd) def complement(self): """ Return a new fraction object which numerator = -self.__numerator :return : fraction object """ return Fraction(-self.__numerator,self.__denominator) def reciprocal(self): """ Return a new fraction object which numerator, denominator is swapped :return : fraction object """ return Fraction(self.__denominator, self.__numerator) def multiply(self, frac2): """ Multiply 2 fractions :return : fraction object """ newNumerator = self.__numerator * frac2.__numerator newDenominator = self.__denominator * frac2.__denominator return Fraction(newNumerator, newDenominator) def divide(self,frac2): """ Divide 2 fractions : return : fraction object """ inverseFrac = frac2.reciprocal() return self.multiply(inverseFrac) def add(self,frac2): """ Add 2 fractions :return : fraction object """ newNumerator = self.__numerator * frac2.__denominator + frac2.__numerator * self.__denominator newDenominator = self.__denominator * frac2.__denominator return Fraction(newNumerator, newDenominator) def deduct(self,frac2): """ Substract 2 fractions :return : fraction object """ newNumerator = self.__numerator * frac2.__denominator - frac2.__numerator * self.__denominator newDenominator = self.__denominator * frac2.__denominator return Fraction(newNumerator, newDenominator) def __lt__(self, other): """ Built-in method if 'self' is less than 'other' :return : boolean value """ return self.__numerator * other.__denominator < other.__numerator * self.__denominator def __str__(self): """ Built-in method return string of object :return : string """ return self.return_string() def greatest_common_divisor(a, b): """ Euclidean algorithm. Returns the greatest common divisor (suurin yhteinen tekijä). When both the numerator and the denominator is divided by their greatest common divisor, the result will be the most reduced version of the fraction in question. """ while b != 0: a, b = b, a % b return a def main(): """ Get user's input (fraction) then store in a list Print simplified format of each fraction """ fracDict = {} while True: command = input("> ") if command == "add": fracText = input("Enter a fraction in the form integer/integer: ") name = input("Enter a name: ") numerator, denominator = fracText.split("/") fracDict[name] = Fraction(int(numerator), int(denominator)) elif command == "print": name = input("Enter a name: ") if name not in fracDict: print(f"Name {name} was not found") else: print(f"{name} = {fracDict[name]}") elif command == "list": for fr in sorted(fracDict): print(f"{fr} = {fracDict[fr]}") elif command == "*": firstName = input("1st operand: ") if firstName not in fracDict: print(f"Name {firstName} was not found") continue secondName = input("2nd operand: ") if secondName not in fracDict: print(f"Name {secondName} was not found") continue multipliedFrac = fracDict[firstName].multiply(fracDict[secondName]) print(f"{fracDict[firstName]} * {fracDict[secondName]} = {multipliedFrac}") print(f"simplified {multipliedFrac.simplify()}") elif command == "file": fileName = input("Enter the name of the file: ") try: file = open(fileName, mode='r') for row in file: name, fracText = row.split("=") numerator, denominator = fracText.split('/') fracDict[name] = Fraction(int(numerator), int(denominator)) except IOError: print("Error: the file cannot be read.") continue except ValueError: print("Error: the file cannot be read.") continue file.close() elif command == "quit": print("Bye bye!") break else: print("Unknown command!") if __name__ == "__main__": main()
c09a3aced0a9064b309e314921c3414dc8262a74
bishkou/leet-code
/Linked list/flattenLinkedList.py
825
3.640625
4
# Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child class Solution: def flatten(self, head: 'Node') -> 'Node': if head: aux = head while aux: if aux.child: temp = aux ch = temp.child nx = temp.next while temp.child: temp = temp.child while temp.next: temp = temp.next aux.next = aux.child ch.prev = aux temp.next = nx nx.prev = temp aux.child = None aux = aux.next
6ca8fe670469dedc4e671fe8914656e70f0b04e7
ryoman81/Leetcode-challenge
/LeetCode Pattern/1. Breadth First Search/111_easy_minimum_depth_of_binary_tree.py
1,350
4.09375
4
''' Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: root = [2,null,3,null,4,null,5,null,6] Output: 5 Constraints: The number of nodes in the tree is in the range [0, 105]. -1000 <= Node.val <= 1000 ''' class Solution: ''' MY CODE VERSION Thought: This is a standard question of BFS in a binary tree. Follow template should be good - We use a variable 'depth' to count the number of layers we have been through - Return the depth once a node has no left or right child Complexity: Time: O(n) Space: O(1) ''' def minDepth(self, root: TreeNode) -> int: if not root: return 0 queue = [root] depth = 0 while queue: depth += 1 levelSize = len(queue) for i in range(levelSize): node = queue.pop(0) if not node.left and not node.right: return depth if node.left: queue.append(node.left) if node.right: queue.append(node.right) return depth ## Since we don't have tree class and a tree creating method ## We don't do test in local environment. Please use LeetCode editor for testing
86b7f5a488bd620063b85bd51f9a7ef03aaf6fdc
ufv-ciencia-da-computacao/CCF110
/lista2/ex4.py
163
3.921875
4
numMes = int(input()) if numMes // 3 == 1: print("1 trimestre") elif numMes // 3 == 2: print("2 trimestre") elif numMes // 3 == 3: print("3 trimestre")
6d2854f0e11794fdd4334f9ae2d184d7d481ad7e
lucasffgomes/Python-Intensivo
/seçao_04/tipo_string.py
1,805
4.21875
4
""" Tipo string Em Python um dado é considerado do tipo STRING sempre que: - Estiver entre aspas simples; 'uma string', '234', 'a', 'True', '42.3' - Estiver em aspas duplas; "uma string", "234", "a", "True", "42.3" - Estiver entre aspas simples triplas; '''uma string''', '''234''', '''a''', '''True''', '''42.3''' - Estiver entre aspas duplas triplas; ''''''uma string'''''', ''''''234'''''', ''''''a'''''', ''''''True'''''', ''''''42.3'''''' nome = 'Geek University' TUDO MAIÚSCULA. print(nome.upper()) nome = 'Geek University' TUDO MINÚSCULA. print(nome.lower()) """ nome = 'Geek University' print(nome) print(type(nome)) nome = "Gina's Bar" print(nome) print(type(nome)) nome = 'Angelina \n Jolie' # \n -> Serve para pular linha. print(nome) print(type(nome)) nome = """Angelina Jolie""" print(nome) print(type(nome)) print("-----------------------------------------") nome = "Angelina \" Jolie" # \" Serve para aparecer a aspas dentro da string na hora de imprimir. print(nome) print("-----------------------------------------") nome = 'Geek University' print(nome.split()) # SPLIT -> Coloca cada palavra da string em lista. # [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] # [ 'G', 'e', 'e', 'k', ' ', 'U', 'n', 'i', 'v', 'e', 'r', 's', 'i', 't', 'y' ] nome = 'Geek University' print(nome[0:4]) # Slice de string print(nome[5:15]) # Slice de string # [ 0, 1] # ['Geek', 'University'] print(nome.split()[0]) print(nome.split()[1]) print("----------------------------------------------------") """ [::-1] -> Começa do primeiro elemento, vá até o último elemnto e inverta. """ print(nome[::-1]) # Inversão da STRING Pythônico # ANTES -> lucas gomes # DEPOIS -> semog sacul print(nome.replace('G', 'P'))
b2398643494506a58170843330de6b3ffe78bfd6
jackcogdill/Learn-Python-Challenges
/06.py
718
3.5625
4
# Translator! Use the following dictionary to # translate a given sentence into leetspeak. # # Reference: https://docs.python.org/3/tutorial/datastructures.html#dictionaries # # Rules: if the word exists, use the word. Otherwise, # Only translate character by character (if it exists in the dictionary). # E.g., 'but my leet senses were troubled' => 'bu7 my 1337 53n535 w3|23 7|20ub13[)' table = { 'more': 'm04R', 'fear': 'ph33r', 'hacker': 'h4x0r', 'has': 'h4z', 'have': 'h4z', 'you': 'j00', 'the': 't3h', 'please': 'plz', 'I': 'EyE', 'o': '0', 'e': '3', 't': '7', 'l': '1', 'i': '1', 's': '5', 'g': '6', 'c': '(', 'd': '[)', 'r': '|2', }
e4a68d13340e23c0533fc93a4d30e3e148e3eb4a
neiljonesdeloitte/sphinx-multimodule-docexample
/module1/classA.py
577
3.765625
4
# -*- coding: utf-8 -*- class classA(object): def __init__(self, a, b): self.a = a self.b = b def func1(param1, param2): """ Args: param1: The first parameter. \n param2: The second parameter. Returns: The return value. True for success, False otherwise. """ param1 = param2 return param1 def func2(): """ Args: Takes no parameters. Returns: The return value is None. """ return None
f5d22c6af829d0ff946103b199858801f033af75
qiuyucc/pythonRoad
/BasicReview/07MethodRecursive.py
1,715
3.75
4
def fac(num): if num in (0, 1): return 1 return num * fac(num - 1) print(fac(5)) # 递归调用函数入栈 # 5 * fac(4) # 5 * (4 * fac(3)) # 5 * (4 * (3 * fac(2))) # 5 * (4 * (3 * (2 * fac(1)))) # 停止递归函数出栈 # 5 * (4 * (3 * (2 * 1))) # 5 * (4 * (3 * 2)) # 5 * (4 * 6) # 5 * 24 # 120 # 函数调用会通过内存中称为“栈”(stack)的数据结构来保存当前代码的执行现场,函数调用结束后会通过这个栈结构恢复之前的执行现场。 # 栈是一种先进后出的数据结构,这也就意味着最早入栈的函数最后才会返回,而最后入栈的函数会最先返回。 # 例如调用一个名为a的函数,函数a的执行体中又调用了函数b,函数b的执行体中又调用了函数c,那么最先入栈的函数是a,最先出栈的函数是c。 # 每进入一个函数调用,栈就会增加一层栈帧(stack frame),栈帧就是我们刚才提到的保存当前代码执行现场的结构; # 每当函数调用结束后,栈就会减少一层栈帧。通常,内存中的栈空间很小,因此递归调用的次数如果太多,会导致栈溢出(stack overflow), # 所以递归调用一定要确保能够快速收敛。我们可以尝试执行fac(5000),看看是不是会提示RecursionError错误, # 错误消息为:maximum recursion depth exceeded in comparison(超出最大递归深度),其实就是发生了栈溢出。 # def fib(n): # if n in (1, 2): # return 1 # return fib(n - 1) + fib(n - 2) def fib(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a # 打印前20个斐波那契数 for i in range(1, 21): print(fib(i))
271f736be9b3ca2b3c769c779666e5f4076a3a07
sapnashetty123/python-ws
/labquest/q_6.py
124
3.53125
4
inp = input("entr the sen:") for ch in inp: if ch in ['a','e','i','o','u']: inp=inp.replace(ch," ") print(inp)
29610cbd336eb940daff644ac9f28e6a747efcea
sumitpatra6/leetcode
/binary_tree_path_with_sum.py
949
3.71875
4
from binary_tree import BinaryTree # broot force algorithm # sum the path received from all the sub trees # this solution is no optimized for better runtime def path_with_sum(root, value): if root is None: return 0 path_from_root = count_path_with_sum(root, 0, value) path_from_left = count_path_with_sum(root.left, 0, value) path_from_right = count_path_with_sum(root.right, 0, value) return path_from_root + path_from_left + path_from_right def count_path_with_sum(root, current, target): if not root: return 0 current += root.val total_path = 0 if current == target: total_path = 1 total_path += count_path_with_sum(root.left, current, target) total_path += count_path_with_sum(root.right, current, target) return total_path array = [2, 6, 5,None, None, 1, 3] bst = BinaryTree(array) bst.inorder() print(path_with_sum(bst.root, 8))
835e634fd6d068ec8968cac65a7856bd665c9f22
AndreeaNenciuCrasi/Programming-Basics-Exercises
/Second SI week/binary_convertor.py
483
4
4
def decimal_to_binary(n): if(n > 1): decimalToBinary(n//2) print(str(n % 2) + ' ') def binary_to_decimal(n): decimal = 0 i = 0 while n != 0: a = n % 10 decimal = decimal + a * (2 ** i) n = n // 10 i += 1 print(decimal) def binary_decimal_convertor(number, system): if system == 2: decimalToBinary(number) elif system == 10: binary_to_decimal(number) binary_decimal_convertor(101000, 10)
3e492916112e095a0abacd25e930dd0aa8a8a027
Bitflip-CET/python-real-world
/gamePlayer.py
2,257
4.125
4
import random # Board Creation board = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] def printBoard(): print("\n") for row in board: print(*row) print("\n") # Win Check def winCheck(symbol): # Rows for row in range(3): if(board[row][0] == symbol and board[row][1] == symbol and board[row][2] == symbol): # print("Row", row) return True # Columns for column in range(3): if(board[0][column] == symbol and board[1][column] == symbol and board[2][column] == symbol): # print("Column", column) return True # Diagonals if(board[0][0] == symbol and board[1][1] == symbol and board[2][2] == symbol): # print("Leading Diagonal") return True if(board[0][2] == symbol and board[1][1] == symbol and board[2][0] == symbol): # print("Off Diagonal") return True return False def main(): turns = 9 player1 = True player2 = False choice = '' choices = [0, 1, 2, 3, 4, 5, 6, 7, 8] while turns > 0: # If Player, Take input. if(player1): print("Player 1's Turn") symbol=player1Symbol printBoard() print(choices) choice = int(input("Enter your choice: ")) if(choice not in choices): print("INVALID CHOICE!") continue else: print("Player 2's Turn") symbol=player2Symbol printBoard() print(choices) choice = int(input("Enter your choice: ")) if(choice not in choices): print("INVALID CHOICE!") continue choices.remove(choice) # 0 -> 0, 0 # 1 -> 0, 1 # 2 -> 0, 2 # 3 -> 0, 3 # 5 -> 1, 1 # 7 -> 2, 1 => 3 * 2 + 1 # choice = 7 column = choice % 3 row = (choice - column)//3 board[row][column] = symbol didPlayer1Win = winCheck(player1Symbol) didPlayer2Win = winCheck(player2Symbol) if(didPlayer1Win): printBoard() print("PLAYER 1 WON!") break if(didPlayer2Win): printBoard() print("PLAYER 2 WON!") break player1 = not player1 player2 = not player2 turns -= 1 if(turns == 0): printBoard() print("DRAW!") player1Symbol = input("What should be Player 1 Symbol: ") player2Symbol = input("What should be Player 2 Symbol: ") main()
27b856a50b59ab681a644c49c60f1262ff5339bd
2470370075/all
/面向对象高级方法.py
2,400
3.546875
4
# class List(list): #改装 # # def append(self, obj): # if isinstance(obj,int): # super().append(obj) # else: # print('no') # # @property # def mid(self): # return self[len(self)//2] # # def clear(self): # s=input('password:') # if s=='123': # super().clear() # else: # print('no') # # @mid.deleter # def mid(self): # print('有人想删除') # # # # l=List([1,2,3]) # # del l.mid # # print(l.mid) # l.append(1) # print(l) # # # print(hasattr(l,'clear')) # if hasattr(l,'clear'): # name=input('name:') # setattr(l,'name',name) # # # l.clear() # print(l) # print(getattr(l,'name','不存在')) # class Foo(): # # def __init__(self,name='1'): # self.name=name # # def __getitem__(self, item): #对象加中括号加字符串运行 # print('有人想查询!') # getattr(self,item) #反射 # # def __setitem__(self, key, value): # print('有人想设置!') # setattr(self,key,value) # # def __delitem__(self, key): # print('有人想删除!') # delattr(self,key) # # # def __del__(self): #删除时运行 # print('对象被删除') # # f=Foo() # print(f.__dict__) # print(f.name) # f['name']='wjx' # print(f.name) # f['name']='jxw' # print(f.name) # del f['name'] # print(f.__dict__) # # class Foo(): # name='wjx' # # def __getattr__(self, item): #兜底 # print('没找到',item) # # def __setattr__(self, key, value): # print('set了',key,value) # # # def __call__(self, *args, **kwargs): #对象加括号 # print('hello') # # f=Foo() # # f.name='111' # f() # Foo()() # # class Foo(): # def __new__(cls): # if not hasattr(cls, 'ins'): # cls.ins = super().__new__(cls) # return cls.ins # # f1=Foo() # f2=Foo() # print(f1 is f2) # f1.name='wjx' # print(f2.name) # class Foo(): #私有变量,类自己里面用,子类也不行 def __init__(self,name,age): self.name=name self.__age=age foo=Foo('wjx',22) print(foo._Foo__age) #私有变量只能这么取
8d09dc51d5bba7086f0c0c017feb6f3d1cdb80d7
anyadao/hw_python_introduction
/hw105.py
2,387
4.40625
4
# 102. Implement the below function: # # def is_valid_credit_card(credit_card): # """ # Given a value determine whether or not it is valid per the Luhn formula. # The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, # such as credit card numbers. # The task is to check if a given string is valid. # Strings of length 1 or less are not valid. # Spaces are allowed in the input, but they should be stripped before checking. # All other non-digit characters are disallowed. # # Example 1: valid credit card number # # 4539 1488 0343 6467 # # Step 1 # The first step of the Luhn algorithm is to double every second digit, starting from the right. We will be doubling # 4_3_ 1_8_ 0_4_ 6_6_ # # Step 2 # If doubling the number results in a number greater than 9 then subtract 9 from the product. # The results of our doubling: # 8569 2478 0383 3437 # # Step 3 # Then sum all of the digits: # 8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80 # # Step 4 # If the sum is evenly divisible by 10, then the number is valid. This number is valid! # # Example 2: invalid credit card number # # 8273 1232 7352 0569 # # Step 1, 2 # Double the second digits, starting from the right # 7253 2262 5312 0539 # # Step 3 # Sum the digits # 7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57 # # Step 4 # 57 is not evenly divisible by 10, so this number is not valid. # # :param score: credit card to check (string) # :return: True if valid, False otherwise # """ # pass import re def is_valid_credit_card(credit_card): cre_card_comp = re.findall(r'\d', credit_card) print('Номер вашей кредитной карты:', credit_card) sum = 0 for i, elem in enumerate(cre_card_comp): cre_card_comp[i] = int(elem) for i, elem in enumerate(cre_card_comp): if i % 2 == 0: cre_card_comp[i] = elem * 2 if cre_card_comp[i] > 9: cre_card_comp[i] -= 9 sum += cre_card_comp[i] if sum % 10 == 0: return True else: return False print(is_valid_credit_card('4539 1488 0343 6467'))
d5561750b687e4700645bf941e7c3e392daffd64
vaseem14/GUVI
/Nhello.py
120
3.6875
4
while True: try: a=int(input()) break except: print("Invalid input") break for x in range(a): print('Hello')
fadfbfac26fa71621b07e41ad6a72f2ea8b3b3eb
secginelif/python_cozumler
/faktöriyel.py
131
3.78125
4
sayi = int(input("Sayıyı giriniz:")) faktoriyel = 1 for i in range(1,sayi+1): faktoriyel = faktoriyel * i print(faktoriyel)
f6f7de9047a5b5ae4e693e4d7cd6516ce9144587
mai-codes/MITx-6.00.1x
/Week_1_-_Python_Basics/pset1.2.py
338
3.8125
4
balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 monthlyInterest = annualInterestRate/12 for i in range(12): minMonthPay = monthlyPaymentRate*balance monthlyUnpaidBal = balance - minMonthPay balance = monthlyUnpaidBal + (monthlyInterest*monthlyUnpaidBal) print('Remaining balance: ' + str(round(balance, 2)))
b48dfbf154912f03fbe4cb22849ad6a7b9f1d2dc
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/kindergarten-garden/0b4a92d57e814ecea837e7a774975279.py
1,615
3.828125
4
_DEFAULT_STUDENTS = [ 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry' ] _PLANT_MAP = { 'C': 'Clover', 'G': 'Grass', 'R': 'Radishes', 'V': 'Violets' } def _get_plant(letter): return _PLANT_MAP[letter] class Garden: def __init__(self, layout, students=None): self.layout = layout if students: self.students = sorted(students) else: self.students = _DEFAULT_STUDENTS self.create_garden() def create_garden(self): """Build a map of student to plant list based on layout and student list. This is incredibly fragile in that edge cases list uneven rows or insufficiently large student list are not handled. """ self.garden = {} for r in self.layout.split("\n"): for i, p in enumerate(zip(r[::2], r[1::2])): index = self.students[i] if index not in self.garden: self.garden[index] = [] self.garden[index].extend(map(_get_plant, p)) def plants(self, name): return self.garden[name] def plants2(self, name): """Secondary solution that searches layout every time. This one gets the student's index and grabs the right plants directly from the layout. """ start_index = self.students.index(name) * 2 g = [] for r in self.layout.split("\n"): g.extend(map(_get_plant, r[start_index:start_index+2])) return g
51660f1b1678cc948fc4c9b7b89276a9f1a9a4d8
param-choksi/test
/calc.py
338
3.75
4
def add(a, b): """Addition Function""" return a + b def sub(a, b): """Subtraction Function""" return a - b def mul(a, b): """Multiplication Function""" return a * b def div(a, b): """Division FUnction""" if b == 0: raise ValueError('Can not divide with zero') else: return a / b
10c145648c4eb783aaa0530a2c62e4b67d129546
sahanasripadanna/word-frequency
/word-frequency-starter.py
3,049
4.125
4
#set up a regular expression that can detect any punctuation import re punctuation_regex = re.compile('[\W]') #open a story that's in this folder, read each line, and split each line into words #that we add to our list of storyWords storyFile = open('short-story.txt', 'r') #replace 'short-story.txt' with 'long-story.txt' if you want! storyWords = [] for line in storyFile: lineWords = line.split(' ') #separate out each word by breaking the line at each space " " for word in lineWords: cleanedWord = word.strip().lower() #strip off leading and trailing whitespace, and lowercase it cleanedWord = punctuation_regex.sub('', cleanedWord) #remove all the punctuation #(literally, replace all punctuation with nothing) storyWords.append(cleanedWord) #add this clean word to our list #set up an empty dictionary to hold words and their frequencies #keys in this dictionary are words #the value that goes with each key is the number of times that word appears in the dictionary #Example: a key might be 'cat', and frequency_table['cat'] might be 5 if the word 'cat' #appears 5 times in the storyWords list frequency_table = {} ignoreWords = ['i', 'a', 'an', 'the', 'this', 'that', 'my', 'me', 'of', 'to', 'and', 'it'] # All code goes here for word in storyWords: #if i haven't seen any words of this type before, add a new entry if word not in frequency_table: frequency_table[word] = 1 #if i HAVE seen it before, add 1 to its current count else: frequency_table[word] = 1 + frequency_table[word] #this is a function that defines the most frequent word def find_max_frequency(): #at the start i haven't seen any words #but i want to keep track of the most frequent word i've seen so far max_freq = 0 max_word = ' ' #look through ALL words in the frequency table for word in frequency_table: #i can check if it's an ignore word # if it is then i want to moooove on girlfriend if word in ignoreWords: pass #if its not an ignore word please consider it else: #if the words im looking at now has appeared more than any #words i've seen so far, update my max if frequency_table[word] > max_freq: max_freq = frequency_table[word] max_word = word #at the end of the for loop, we've looked through all the entries #and max_word has the most frequent word in it return max_word best_word = find_max_frequency() print("The most frequent non ignore word is: " + best_word) # make a function to find the top ten def give_me_the_top(number): #take the most frequent word out of the frequency table 10 times for count in range(number): top_word = find_max_frequency() print(top_word + " appears " + str(frequency_table[top_word]) + " times!") del(frequency_table[top_word]) #take that entry out of the table give_me_the_top(10)
b004a89f40d7249d75e1ebdb2e15a432397c04b3
mrudulamucherla/Python-Class
/2nd assign/leap yr, 115.py
550
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 25 10:47:39 2020 @author: mrudula """ #Write a program to check whether year is leap year or not using conditional operator year = int(input("enter a year")) if (year%4)==0: if (year%100)==0: if (year%400)==0: print("{0}is a leap year".format(year)) else: print("{0}is not a leap year".format(year)) else: print("{0}is a leap year".format(year)) else: print("{0}is not a leap year".format(year))
6212b2aa6b6c50e4649f954bb07ade9db68c01b2
cristobalvch/CS50-Harvard-University
/pset6/marioless/mario.py
190
3.890625
4
from cs50 import get_int while True: n = get_int('height ') if n >0 and n<=8: break for i in range(n): print(' ' * (n-i-1),end='') print('#' * (i + 1),end='\n')
d6b71bace59b23876dff51690de645ea8eb2ce8b
kaurjassi/pythonnew
/program1.py
344
4.15625
4
def greatest(a,b,c): if c < a > b : return a elif a < b > c : return b else: return c num1 = int(input("enter first number : ")) num2 = int(input("enter second number : ")) num3 = int(input("enter third number : ")) biggest = greatest (num1,num2,num3) print(f"{biggest} is biggest")
69e30d078537f8dd97f0e6d38ef9847d726d897f
larcat/python_hard_way
/chp_7_8/chp7_ex1_py2.py
1,129
4.03125
4
#Prints print "Mary had a little lamb." #Prints with an inserted value print "Its fleece was white as %s." % 'snow' #Prints print "And everywhere that Mary went." #Prints "." 10 times in a row on the same line. print "." * 10 # what'd that do? -- String multiplication is like R #Let's assign some text to variables end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # And then print them out together in clever ways # watch that comma at the end. try removing it to see what happens print end1 + end2 + end3 + end4 + end5 +end6, print end7 + end8 +end9 + end10 + end11 + end12 # Comma makes explicit continue on same line, at least for print # Dunno if it works for other stuff # Lets find out # Prints the result of 2 plus 2 (it is 4) print 2 + 2 #Prints "a", but keeps the printing on the same line because comma print "a", #And here's the four after our a on the same line print 2 + 2 # So it works for the line over all, but you cannot interrupt an expression # and have it work right... i.e it doesn work with the comma after the plus
9cbd51b5e266ba13e3c85da87dc260ea2701949e
madeibao/PythonAlgorithm
/PartB/Py逆置单链表3.py
675
3.984375
4
class ListNode(object): def __init__(self,x): self.val = x self.next = None class Solution: def reverseNodes(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head pre = None while head: temp = head.next head.next = pre pre = head head = temp return pre if __name__ == "__main__": s = Solution() n2 = ListNode(1) n3 = ListNode(2) n4 = ListNode(4) n5 = ListNode(9) n6 = ListNode(8) n7 = ListNode(5) n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 n6.next = n7 n7.next = None res= s.reverseNodes(n2) while res: print(res.val,end=" ") res = res.next
6ada5df392d72d2e38a33b6dc1a165aca2b8bde6
sayalipawade/Python-Programs
/tictactoe.py
1,271
3.953125
4
import random board=[0,1,2,3,4,5,6,7,8,9] #Variables symbol=0 player=" " cell_count=0 maximum_cell=9 computer="O" user="X" class Tic_Tac_Toe: #Display board def print_board(self): print(board[1],'|',board[2],'|',board[3]) print('----------') print(board[4],'|',board[5],'|',board[6]) print('----------') print(board[7],'|',board[8],'|',board[9]) #Assign symbol to players def assign_symbol(self): user="X" computer="O" #Toss for who play first def switch_player(self): random_no=random.randint(0,1) if random_no == 1: self.user_play() else: print('computer will play') #Function for player def user_play(self): global cell_count if cell_count < maximum_cell: position=int(input("Enter Position:")) if board[position] == position: board[position]=user cell_count=cell_count+1 self.print_board() else: print("Invalid Cell") self.user_play() else: print("Game Tie!!!") tic_tac_toe=Tic_Tac_Toe() tic_tac_toe.print_board() tic_tac_toe.assign_symbol() tic_tac_toe.switch_player()
c35cbee09b246ef466868f87889b4c89dbba71a0
furutuki/LeetCodeSolution
/剑指offer系列/剑指 Offer 41. 数据流中的中位数/solution.py
1,370
3.5
4
import heapq class MaxHeapObj(object): def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __eq__(self, other): return self.val == other.val def __str__(self): return str(self.val) class MinHeap(object): def __init__(self): self.h = [] def heappush(self, x): heapq.heappush(self.h, x) def heappop(self): return heapq.heappop(self.h) def __getitem__(self, i): return self.h[i] def __len__(self): return len(self.h) class MaxHeap(MinHeap): def heappush(self, x): heapq.heappush(self.h, MaxHeapObj(x)) def heappop(self): return heapq.heappop(self.h).val def __getitem__(self, i): return self.h[i].val class MedianFinder: def __init__(self): self.minHeap = MinHeap() self.maxHeap = MaxHeap() def addNum(self, num: int) -> None: self.maxHeap.heappush(num) n = self.maxHeap.heappop() self.minHeap.heappush(n) sizeDiff = len(self.minHeap) - len(self.maxHeap) if sizeDiff > 1 or sizeDiff < 0: self.maxHeap.heappush(self.minHeap.heappop()) def findMedian(self) -> float: m, n = len(self.maxHeap), len(self.minHeap) if m == n: return (self.maxHeap.__getitem__(0) + self.minHeap.__getitem__(0)) / 2 else: return self.minHeap.__getitem__(0)
2ebc50b7bfd5bbfaca381ea06c5ee7392b7ba9cf
djrff/rpi-enviro-phat
/sensors/display/motion.py
687
3.828125
4
#!/usr/bin/env python import sys import time from envirophat import motion, leds print("""This example will detect motion using the accelerometer. Press Ctrl+C to exit. """) threshold = 0.05 readings = [] last_z = 0 try: while True: motion_detected = False last_reading = motion.accelerometer() readings.append(last_reading.z) readings = readings[-4:] z = sum(readings) / len(readings) if last_z > 0 and abs(z - last_z) > threshold: print("Motion Detected!!!") leds.on() motion_detected = True last_z = z time.sleep(0.5) leds.off() except KeyboardInterrupt: pass
ddbca93f8dcb398b0b572dd9b0950d8fca1681ce
everbird/leetcode-py
/2015/Subsets_v0.py
532
3.734375
4
#!/usr/bin/env python # encoding: utf-8 class Solution: # @param {integer[]} nums # @return {integer[][]} def subsets(self, nums): nums.sort() return self._subsets(nums) def _subsets(self, nums): if len(nums) == 1: return [nums, []] last = nums[-1] items = self._subsets(nums[:-1]) r = items[:] for item in items: r.append(item + [last]) return r if __name__ == '__main__': s = Solution() print s.subsets([1,2,3])
9d8d9f60574e8b12b7974c71e33dbe15c5c45e80
eognianov/PythonProjects
/PythonFundamentals/1.Functions, Debugging and Troubleshooting Code/8. Multiply Evens by Odds.py
457
3.96875
4
def get_multiple_of_even_and_odds(n): return get_sum_of_even_digits(n) * get_sum_of_odd_digits(n) def get_sum_of_even_digits(n): result = 0 while n != 0: result += n % 10 if (n % 10)% 2==0 else 0 n //= 10 return result def get_sum_of_odd_digits(n): result = 0 while n != 0: result += n % 10 if (n % 10)% 2==1 else 0 n //= 10 return result print(get_multiple_of_even_and_odds(abs(int(input()))))
6bfc8016c69f9ee29380b736b22d0e5076d16b57
udhayprakash/PythonMaterial
/python3/16_Web_Services/f_web_application/a_static_web_pages/d_addition_operation.py
1,326
3.53125
4
def fileToStr(fileName): # NEW """Return a string containing the contents of the named file.""" fin = open(fileName) contents = fin.read() fin.close() return contents # def main(): # person = input("Enter a name: ") # NEW # contents = fileToStr("helloTemplate.html").format(**locals()) # NEW # browseLocal(contents, "helloPython3.html") # NEW filename def processInput(numStr1, numStr2): # NEW """Process input parameters and return the final page as a string.""" num1 = int(numStr1) # transform input to output data num2 = int(numStr2) total = num1 + num2 return fileToStr("d_addition_operation.html").format(**locals()) def main(): # NEW numStr1 = input("Enter an integer: ") # obtain input numStr2 = input("Enter another integer: ") contents = processInput(numStr1, numStr2) # process input into a page browseLocal(contents, "helloPython3.html") # display page def strToFile(text, filename): """Write a file with the given name and the given text.""" output = open(filename, "w") output.write(text) output.close() def browseLocal(webpageText, filename): """Start your webbrowser on a local file containing the text.""" strToFile(webpageText, filename) import webbrowser webbrowser.open(filename) main()
e8e9d2430c56185eb6e7ed754623dcfdc9539a12
nicolascarratala/2020.01
/59098.Davara.Federico/05-trabajo/main.py
1,860
3.875
4
from producto import Producto from productoServices import ProductoService class Menu(): def menu_productos(self): print("""\n\t1 > Ver productos 2 > Agregar un Producto 3 > Modificar un Producto 4 > Eliminar un Producto 5 > Salir """) return int(input("\tSeleccionar una opción: ")) if __name__ == "__main__": main = Menu() sistema = ProductoService() while True: seleccion = main.menu_productos() if seleccion == 1: t = sistema.get_productosList() print("\n\tLos productos son: \n\t{}".format(t)) if seleccion == 2: productos = Producto() productos.descripcion = input("\n\tAgregar una descripcion del producto: ") productos.precio = int(input("\tAgregar un precio del producto: ")) productos.tipo = input("\tAgregar el tipo de producto: ") sistema.add_producto(productos) if seleccion == 3: productos = Producto() key = int(input("\n\tProporcione el codigo del producto: ")) productos.descripcion = input("\tAgregar una descripcion sobre el producto: ") productos.precio = int(input("\tAgregar un precio para el producto: ")) productos.tipo = input("\tAgregar el tipo de producto: ") sistema.update_producto(key, productos) if seleccion == 4: productos = Producto() key = int(input("\n\t¿Cual es el producto que se desea eliminar?: ")) sistema.delete_producto(key) if seleccion < 1 or seleccion > 5: print("""\t\t>>>Esta opción no es valida por favor utilise una de las opciones que se encuentran en pantalla<<<""") if seleccion == 5: print("\n\tFinalizando programa...") break
8c30103b04e7720412dd349599a18d1eea199e57
kzhamada/test-repo
/__init__.py
194
3.546875
4
# -*- encoding: utf8 -*- if __name__ == "__main__": print("hello") print("hello, world") print("hello, world") print("hello, world2") for i in range(0, 10): print(i)
6d5dbcfb2736bc50f6f7683de28215d8be3e6870
sandeepkrishnagopalappa/self_study
/InstanceClassStatic.py
1,172
3.703125
4
class Sony: __division = 'Software Architecture Division' def __init__(self, fullname): self.fullname = fullname def email(self): self.first, self.last = self.fullname.split(' ') return self.first + '.' + self.last + '@sony.com' @classmethod def change_dept(cls, division): cls.__division = division @staticmethod def new_dept(): return Sony.__division s1 = Sony('Monish Kalaiselvan') s2 = Sony('Sagar Ramesh') #print(Sony._Sony__division) #Private class variable can be accessed... #But not recommended Sony.change_dept('SARD') print(s1.new_dept()) print(s2.new_dept()) print(s1.email()) ------------------------------------------------------------------ class Sony: def __init__(self, first, last): self.first = first self.last = last @classmethod def name(cls, fullname): first, last = fullname.split(' ') return cls(first, last) def email(self): return self.first + '.' + self.last + '@sony.com' s = Sony.name('Monish Kalaiselvan') print(s.email()) -------------------------------------------------------------------
2764833c2d3062119861ce7aec18b66d2e0e52da
FVPukay/work-log
/work_log.py
1,030
3.75
4
import work_log_ui from textwrap import dedent if __name__ == '__main__': while True: work_log_ui.clear_screen() print(dedent("""\ WORK LOG What would you like to do? a) Add new entry b) Search in existing entries c) Quit program\ """)) choice = input('>') if choice.lower() == 'a': work_log_ui.clear_screen() work_log_ui.add_entry() work_log_ui.clear_screen() continue elif choice.lower() == 'b': work_log_ui.clear_screen() work_log_ui.search() continue elif choice.lower() == 'c': work_log_ui.clear_screen() print(dedent("""\ Thanks for using the Work Log program! Come again soon.\ """)) break else: error = "Please enter 'a', 'b', or 'c'\nPress enter to try again" enter = input(error) continue
c81350217ebf22aafde032cf78b9f1400b6c175f
HyperdriveHustle/leetcode
/parserURL.py
1,939
3.53125
4
# -*- coding:utf-8 _*- ''' 深信服2019春招笔试题1 题目描述: 一个百分号%后面跟一个十六进制的数字,则表示相应的ASCII码对应的字符,如 %2F 表示 /; %32 表示 2. %编码还可以进行嵌套,如 %%32F 可以解析为 %2F 然后进一步解码为 /。 输入: 第一行是一个正整数 T ,表示 T 个样例。 对于每个测试样例,输入一个字符串 s ,字符串不包括空白符且长度小于100,000. 输出: T 行,每行一个字符串,表示解码结果,解析到不能继续解析为止。 通过率:70% (还没发现问题出在哪) ''' def parserURL(url): if len(url) < 3: return url j = len(url) - 1 # 找到最后一次出现的% while j >= 0 and url[j] != '%': j -= 1 # 没有百分号则非法 if j < 0: return url while j >= 0: # 如果后面的数字至少还有两位 if j < len(url) - 2: i = j + 1 # 判断后面两位是否是合法的十六进制 # print 'n : ', url[i:i + 2], ':', int(url[i:i + 2], 16), ':', chr(int(url[i:i+2], 16)) try: n = int(url[i:i+2], 16) # 注意如果此时已经到了最后一位 if j + 2 == len(url): # print '----', chr(int(url[j:j+2], 16)) url = url[:i-1] + chr(n) else: url = url[:i-1] + chr(n) + url[i+2:] except: j -= 1 # print 'url : ', url # j 继续向前移动,找到上一个% # print j, url else: j -= 1 while 0 <= j and url[j] != '%': j -= 1 # print 'url : ', url return url if __name__ == '__main__': n = raw_input() for i in range(int(n)): url = raw_input() print parserURL(url) # print parserURL('%%323%%32F%3H')
ec4d32bc7190b83f79f6df3bc554eb4aa7020c5d
hash6490/Python
/Inheritance.py
1,043
3.90625
4
class school_member: def __init__(self,name,age): self.name=name self.age=age print('Initialized schoolmember {}\n'.format(self.name)) def tell(self): print('Name:{} Age:{}\n'.format(self.name,self.age)) class Teacher(school_member): def __init__(self,name,age,salary): school_member.__init__(self,name,age) self.salary=salary print('Initialized teacher {}\n'.format(self.name)) def tell(self): print('Name:{} Age:{} Salary:{}\n'.format(self.name,self.age,self.salary)) class Student(school_member): def __init__(self,name,age,grade): school_member.__init__(self,name,age) self.grade=grade print('Initialized student {}\n'.format(self.name)) def tell(self): print('Name:{} Age:{} Grade:{}'.format(self.name,self.age,self.grade)) t=Teacher('Pushpa','35','70,000') s=Student('Abhishek','21','A') members=[t,s] for member in members: member.tell()
401f83bd2ca81883ae29555e92985d5e9bef2323
iceman951/Intro-Python-with-Sadhu-Coding-system
/Basic math and string/เข้ารหัสอย่างง่าย.py
274
3.78125
4
def inv(c): if 'a' <= c <= 'z': return chr(122 - ord(c) + 97) if 'A' <= c <= 'Z': return chr(90 - ord(c) + 65) return c text = str(input("Enter 5 characters: ")) output = ''.join(inv(c) for c in text) print("Encryption is",output.lower())
744f1e08a7e888c141997e295001cb61a24e1180
da-ferreira/uri-online-judge
/uri/1249.py
921
3.578125
4
lower = [ '', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' ] upper = [ '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M' ] while True: try: mensagem = input() codigo = '' for i in range(len(mensagem)): if mensagem[i].isalpha(): if mensagem[i].islower(): codigo += lower[lower.index(mensagem[i]) + 13] else: codigo += upper[upper.index(mensagem[i]) + 13] else: codigo += mensagem[i] print(codigo) except EOFError: break
743beeb4cec639a9254d584e3b289b6bad2df3d6
jatin556/Learn-Python
/DS_assignment11.py
1,542
3.890625
4
#DSA-Assgn-11 #This assignment needs DataStructures.py file in your package, you can get it from resources page from src.DataStructures import Queue def merge_queue(queue1,queue2): list1=[] list2=[] merged_queue=Queue(9) while not queue1.is_empty(): list1.append(queue1.dequeue()) while not queue2.is_empty(): list2.append(queue2.dequeue()) if len(list1)<len(list2): for i in range(len(list1)): merged_queue.enqueue(list1.pop(0)) merged_queue.enqueue(list2.pop(0)) for x in list2: merged_queue.enqueue(x) #write your logic here return merged_queue elif len(list1)>len(list2): for i in range(len(list2)): merged_queue.enqueue(list1.pop(0)) merged_queue.enqueue(list2.pop(0)) for x in list1: merged_queue.enqueue(x) return merged_queue else: for i in range(len(list2)): merged_queue.enqueue(list1.pop(0)) merged_queue.enqueue(list2.pop(0)) return merged_queue #Enqueue different values to both the queues and test your program queue1=Queue(3) queue2=Queue(6) queue1.enqueue(3) queue1.enqueue(6) queue1.enqueue(8) queue2.enqueue('b') queue2.enqueue('y') queue2.enqueue('u') queue2.enqueue('t') queue2.enqueue('r') queue2.enqueue('o') merged_queue=merge_queue(queue1, queue2) print("The elements in the merged queue are:") merged_queue.display()
33c1e36b88aab2c08066693f70b00bd1e82c6c83
nin9/CTCI-6th
/Chapter10/11-peaksAndValleys.py
760
4.0625
4
from typing import List """ Time Complexity O(nlogn) Space Complexity O(1) """ # Approach 1 def sortPeakValley(arr: List[int]) -> List[int]: arr.sort() n = len(arr) for i in range(1,n,2): arr[i], arr[i-1] = arr[i-1], arr[i] return arr #################################################### """ Time Complexity O(n) Space Complexity O(1) """ # Approach 2 def sortPeakValley2(arr: List[int]) -> List[int]: n = len(arr) for i in range(1,n-1,2): if arr[i] > arr[i+1] and arr[i] > arr[i-1]: continue # arr[i] is already a peak if arr[i+1] > arr[i-1]: arr[i], arr[i+1] = arr[i+1], arr[i] else: arr[i], arr[i-1] = arr[i-1], arr[i] return arr arr = [5,3,1,2,3] print(sortPeakValley(arr)) print(sortPeakValley2(arr))
75ed36add48a51ca5cfa6e7c17ace992a3c6b2fb
ab5tract/rosalind.info
/dna/pycount.py
597
3.515625
4
#!/usr/bin/env python from __future__ import print_function import sys def main(argv): file = argv[0] print('file = ' + file) f = open(file, 'r') seq = f.read().strip() print('seq = ' + seq) count = {} for char in list(seq): if not count.has_key(char): count[char] = 0 count[char] += 1 #map(lambda s: count[s] = count[s] + 1, list(seq)) #count = map(lambda s: count[s] = count[s] + 1, list(seq)) for base in list('ACGT'): print(count[base], end=' ') print('') if __name__ == "__main__": main(sys.argv[1:])
84905f9f78000e21092e5797fdba0f5f4ec5f559
SauravAryal49/guessinggame
/guess_game.py
701
3.828125
4
game=["dog", "cat", "rabbit"] print("hint : three pet animals","and you have only five 'wrong' trials options") guess="" guess_number=0 number=[0,1,2] guess_result = False while (guess_number<5) and not(guess_result==True): guess=input("enter the guess") x=False for i in number: if (guess.strip()==game[i]): x=True print("thats correct") game.remove(game[i]) number.pop() if (game==[]): print(":) you win congrats") guess_result=True if (x==True): continue else: print("not correct") guess_number+=1 if (guess_number==5): print(":( sorry you lost")
e9aaa5a2f17ef0afc64329ff018be2212d084be2
aacharyakaushik/i_code_in_python
/leetcode/Plus_one.py
469
3.65625
4
# -*- coding: utf-8 -*- """ @author: Kaushik Acharya """ from typing import List def plusOne(self, digits: List[int]) -> List[int]: # print(digits[-1]) # print(digits[:-1]) # print(set(digits)) if digits[-1] != 9: digits[-1] += 1 elif set(digits) == {9}: digits = [1] + [0] * len(digits) else: digits[-1], digits[:-1] = 0, self.plusOne(digits[:-1]) return digits input_1 = [1, 2, 3] p = plusOne(plusOne,input_1) print(p)
5448d35b84736e8459c4bcd8b3e3194eecacefac
RashRAJ/Raj_tech
/ping pong game.py
860
3.640625
4
import turtle wn = turtle.Turtle() wn = turtle.Screen() wn = turtle.bgcolor("black") tim = turtle.Turtle() tim.penup() tim.hideturtle() tim.goto(200, 200) tim.pendown() tim.color("pink") tim.width(10) tim.speed(10) for i in range(50): tim.forward(300) tim.left(170) tim1 = turtle.Turtle() tim1.penup() tim1.hideturtle() tim1.goto(-200, 200) tim1.pendown() tim1.color("#f37736") tim1.width(10) tim1.speed(10) for i in range(50): tim.forward(300) tim.left(170) pen = turtle.Turtle() pen.color("#f9caa7") pen.penup() pen.hideturtle() pen.goto(0, 90) pen.write("Happy", align="center", font=("Times", 20, "bold italic")) pen.goto(0, 20) pen.write("Birthday", align="center", font=("Times", 30, "bold italic")) pen.goto(30, 30) pen.write("Moha!!!!!", align="right", font=("Times", 20, "bold italic"))
2abd5204144abbd5b0373cb19506ff81bc8d5071
AnaGVF/Programas-Procesamiento-Imagenes-OpenCV
/Ejercicios - Enero25/Funciones_1.py
763
3.859375
4
# Nombre: Ana Graciela Vassallo Fedotkin # Expediente: 278775 # Fecha: 25 de Enero 2021. # Podemos regresar una expresion def sum(var1, var2, var3): return var1 + var2 + var3 print(sum(19, 20, 30)) print() print() # Función obtenga datos def obtener_datos(): return "python", "basico", "clase" curso, nivel, materia = obtener_datos() print(curso, nivel, materia) print() print() # Factorial def factorial(numero): f = 1 for i in range(1, numero + 1): f=f*i return f print("Factorial:", factorial(5)) print() print() # Factorial Recursivo def factorialRecursivo(numero): if(numero == 0): return 1 else: return numero * factorialRecursivo(numero-1) print("Factorial Recursivo:", factorialRecursivo(5)) print() print()
3df4a4b42358e8e0ce96b5cd8a5109fd866e52fe
beidou9313/deeptest
/第一期/成都-MFC/task002/kuaixuepython3/python3_tuple.py
1,995
3.546875
4
# -*- coding:utf-8 -*- __author__ = 'TesterCC' __time__ = '18/1/11 16:31' """ tuple https://mp.weixin.qq.com/s?__biz=MzI0NDQ5NzYxNg==&mid=2247484018&idx=1&sn=44f10b570f3136e584b0935882a9be0b&scene=19#wechat_redirect """ tuple1 = (u'MFCTest', u'测试开发', u'1') tuple2 = (1, 2, 3, 4, 5) tuple3 = ("a", "b", "c", "d", "e") tuple_demo = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0) # 计算tuple1中元素个数 print(len(tuple1)) # 返回tuple2中最大值的元素 print(max(tuple2)) # 返回tuple3中最小值的元素 print(min(tuple3)) # 将list转换成元组 print("-"*50) print("列表转元组示例") list_demo = [1, 2, 3, 4, 5, 6, 7] tuple0 = tuple(list_demo) print(type(tuple0)) # 打印转换后的元组 print(tuple0) print("-"*50) # 切片 Slice print(u"元组切片操作示例!") data_demo = (u"DeepTest", u"SET", u"MFC", u"hello", u"python3") # 读取第2个元素SET, 注意索引下标从0开始 e = data_demo[1] print(e) # 读取倒数第2个hello e = data_demo[-2] print(e) # 切片,截取从第2个元素开始后的所有元素 e = data_demo[1:] print(e) # 切片,截取第2-4个元素, 4是第5个元素,就是说左闭右开[a:b) e = data_demo[1:4] print(e) print("-"*50) print(u"元组合并或连接操作示例!") tup1 = (u"LearnTest", u"appium") tup2 = (u"MFC", u"hello", u"python3") # 合并元组 tup3 = tup1 + tup2 print(tup1) print(tup2) print(tup3) # 删除元组 print("-"*50) print(u"元组合并或连接操作示例!") tup1 = (u"LearnTest", u"appium") print(tup1) del tup1 # print(tup1) # throw except # 元组运算 print("-"*50) print(u"元组运算示例") tup1 = (u"LearnTest", u"测试开发") tup2 = (1, 2, 3, 4) # 计算元组长度 print(len(tup1)) # 元组连接 tup3 = tup1 + tup2 print(tup3) # 元组复制 tup4 = tup1 * 2 print(tup4) # 判断元素是否在元组中, 是则返回True, 否则返回 result = 5 in tup2 print(result) result2 = 1 in tup2 print(result2) # 遍历元组 for t in tup2: print(t)
26de046c4a8b33b624a8e44a7332f122d08dd8f6
Dmitrygold70/rted-myPythonWork
/Day04/ex23_loops.py
307
3.78125
4
x = [1, 2, 702, 704, 3, 4, 804, 806, 808] print("before removing:", x) print("sorted to help us see:", sorted(x)) # if a number is greater than 300 and even, remove it. i = 0 while i < len(x): if x[i] > 300 and x[i] % 2 == 0: del x[i] continue i += 1 print("after removing:", x)
1409736d7a3cb4be4639ea1fab7537c8474ed023
Tieshia/RESTAPIs_udemy
/if_statements.py
874
4.125
4
# should_continue = True # if should_continue: # print("Hello") ''' known_people = ["John", "Anna", "Mary"] person = input("Enter the person you know: ") if person in known_people: print("You know {}.".format(person)) else: print("You don't know {}.".format(person)) ''' ## Exercise def who_do_you_know(): # Ask user for a list of people they know # Split string into list people = input("Enter the names of people you know, separated by commas: ") people = people.split(', ') return people def ask_user(): # Ask user for a name # See if their name is in the list of people they know # Print out that they know the person person = input("Enter the person you know: ") if person in who_do_you_know(): print("You know {}.".format(person)) else: print("You don't know {}.".format(person)) ask_user()
f4741aceb7e193f60f8113573610318bf39ca431
ningxu2020/python201
/funnylist3.py
558
4.0625
4
class FunnyList(list): def __eq__(self, other): """Check for equality without concern for order. If the sorted versions of two FunnyLists are the same, then we deem the FunnyLists to be the same.""" return sorted(self) == sorted(other) def __add__(self, thing): """Add an item to a FunnyList. We'll create a new list which is a copy of our current list (self) plus the item we want to add. """ newlist = self.copy() + [thing] return FunnyList(newlist)
20e7ab59626f609fcdb463114803e7ae849ae467
kren1504/Training_codewars_hackerrank
/dir_reduction.py
791
3.71875
4
""" 23 minutos def dirReduc(arr): dir = " ".join(arr) dir2 = dir.replace("NORTH SOUTH",'').replace("SOUTH NORTH",'').replace("EAST WEST",'').replace("WEST EAST",'') dir3 = dir2.split() return dirReduc(dir3) if len(dir3) < len(arr) else dir3 """ def dirReduc(arr): opposite = [["NORTH", "SOUTH"],["EAST", "WEST"],["WEST","EAST"],["SOUTH","NORTH"]] i = 0 aux = [] while i< (len(arr)-1): aux.append(arr[i]) aux.append(arr[i+1]) if aux in opposite: del arr[i] del arr[i] i=0 aux.clear() continue i+=1 aux.clear() return arr if __name__ == "__main__": print(dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
948530f99a1939f0104abfcb0c26b9a44a091a74
tjmann95/ECEC
/Homework 8/pi_series.py
1,814
4.09375
4
# A generator to find pi. import math print "1. A neverending series to find pi. But it converges really, really slowly." def pi_series(): sum = 0 i = 1.0 # Guarantees division will use floats. j = 1 while True: # The iterator will be infinite! sum += j / i yield 4 * sum i += 2; # The odd divisors j *= -1 # The alternating signs print "Estimate pi by summing Leibnitz's series (*4) out to n = 20." slow_gen = pi_series() for n in range(0,21): print "Out to n = %2d --> " % n, slow_gen.next() print "Ack! Very slow convergence." print "\n2. That sure is a slow convergence! Let's apply the non-linear Aitken extrapolation to accelerate the convergence!" # Accelerates a series using the non-linear Aitken extrapolation. def accelerate(my_generator): s0 = my_generator.next() s1 = my_generator.next() s2 = my_generator.next() while True: accelerated_term = s2 - ((s2 - s1)**2) / (s0 - 2 * s1 + s2) yield accelerated_term s0, s1, s2 = s1, s2, my_generator.next() fast_gen = accelerate( pi_series()) # The accelerated generator. for n in range(0,21): print "Out to n = %2d --> " % n, fast_gen.next() print "Awesome! The convergence is much faster." print "\n3. Let's compare the slow and fast series going out to n = 100. That's 101 terms." print "a. Estimate pi by summing Leibnitz's slow series out to n = 100." slow_gen = pi_series() for n in range(0,101): result = slow_gen.next() print "Out to n = 100 --> ", result print "b. Estimate pi by summing the accelerated series out to n = 100." fast_gen = accelerate( pi_series() ) # A fresh accelerated generator. for n in range(0,101): result = fast_gen.next() print "Out to n = 100 --> ", result print "Actual value of pi is: ", math.pi
b539e45709d1495cf8c5966ff65d0f802ec843c3
ksentrax/think-py-2e--my-solutions
/exercise10/exercise10-7.py
386
3.96875
4
"""This script checks the list for duplicates.""" def has_duplicates(li): """Checks if there is any element that appears more than once. :param li: list :return: boolean value """ li.sort() for i in range(len(li)-1): if li[i] == li[i+1]: return True return False if __name__ == '__main__': print(has_duplicates([1, 1, 5, 4, 2]))
f0d33efd07e1c2168b4b4aea330c0b24d04bf076
samantadearaujo/python
/bioinformatica/listas.py
479
3.71875
4
lista = [32,'Samanta', 4.000] print(lista) print(len(lista)) for e in range(len(lista)): print(lista[e]) lista1 = [1,2,3,4,5,6] lista1.append(7) print(lista1) lista2 = lista +lista1 print(lista2) lista3 = [1,2,3,4,5,6,7,8] removido = lista3.pop(0) print(removido) lista4= [1,2,3,4,5,6,7,8,9] lista4.remove(3) print(lista4) print(lista4[::-1]) print(lista4[0::-1]) lista4.insert(3,100) print(lista4) lista5 = [50,37,89,1,2,3,70] lista5.sort() print(lista5)
0323db2f9633e59fbaccef9c6c168e52bb39ef72
Gaurav-Patil-10/Snake_Game
/snake.py
4,759
3.84375
4
import pygame import random pygame.init() # screen dimensions screen_width = 800 screen_height = 600 # colors black = (0 ,0,0) white = (255 , 255 , 255) red = (255 ,0 , 0) # Game window game_window = pygame.display.set_mode((screen_width , screen_height)) pygame.display.set_caption("SNAKE") pygame.display.update() # game specifics # food food_x = random.randint(20 , screen_width) food_y = random.randint(20 , screen_height) food_size = 10 with open("high_score.txt" , "r") as f: highscore = f.read() clock = pygame.time.Clock() font = pygame.font.SysFont(None , 55) def text_score(text , color , x , y): # function for displaying the text on screen screen_text = font.render(text , True , color) game_window.blit(screen_text , [x , y]) def plot_snake (game_window , color , snake_list, snake_size): # plotting of the snake for x ,y in snake_list: pygame.draw.rect(game_window , color , [x , y ,snake_size , snake_size]) def welcome(): global clock exit_game = False while not exit_game: game_window.fill((233 , 220 , 229)) text_score("Welcome to SNAKE game" , black , 160 , 240) text_score("Press SPACEBAR to PLAY" , black , 150 , 310) for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: game_loop() pygame.display.update() clock.tick(60) # main Loop def game_loop (): exit_game = False game_over = False snake_x = 45 snake_y = 55 snake_size = 10 fps = 30 velocity_x = 0 velocity_y = 0 init_velocity = 8 snk_list = [] snake_length = 1 score = 0 food_x = random.randint(20, screen_width) food_y = random.randint(20, screen_height) food_size = 10 global highscore while not exit_game: if game_over : with open("high_score.txt" , "w") as f: f.write(str(highscore)) game_window.fill(white) text_score(f"Game Over ! Press Enter to Play Again" , red , 60 , 260) for event in pygame.event.get(): # print(event) if event.type == pygame.QUIT: exit_game = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: welcome() else: for event in pygame.event.get(): # print(event) if event.type == pygame.QUIT: exit_game = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: velocity_x = init_velocity velocity_y = 0 if event.key == pygame.K_LEFT: velocity_x = - init_velocity velocity_y = 0 if event.key == pygame.K_UP: velocity_y = - init_velocity velocity_x = 0 if event.key == pygame.K_DOWN: velocity_y = init_velocity velocity_x = 0 snake_x += velocity_x # incrementing of the position of the snake snake_y += velocity_y if abs(snake_x - food_x) < 10 and abs(snake_y - food_y) < 10: # food eating system and new food generation score += 10 food_x = random.randint(80, screen_width // 2) food_y = random.randint(80, screen_height // 2) snake_length += 2 if score > int(highscore): highscore = score game_window.fill(black) text_score(f"Score : {score} High Score : {highscore}", (255, 255, 0), 5, 5) pygame.draw.rect(game_window, red, [food_x, food_y, food_size, food_size]) head = [] head.append(snake_x) head.append(snake_y) snk_list.append(head) if len(snk_list) > snake_length: del snk_list[0] if snake_x < 0 or snake_y < 0 or snake_x > screen_width or snake_y > screen_height : game_over = True # print(game_over) if head in snk_list[:-1]: game_over = True plot_snake(game_window , white ,snk_list , snake_size ) # pygame.draw.rect(game_window , white , snake_list, snake_size) pygame.display.update() clock.tick(fps) if __name__ == '__main__': welcome() # game_loop() pygame.quit() quit()
5cce2bd0df081f2f32ab4f5281a365c6d5b855de
snowraincloud/leetcode
/460.py
6,077
3.984375
4
# 设计并实现最不经常使用(LFU)缓存的数据结构。它应该支持以下操作:get 和 put。 # get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。 # put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,它应该在插入新项目之前,使最不经常使用的项目无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,最近最少使用的键将被去除。 # 进阶: # 你是否可以在 O(1) 时间复杂度内执行两项操作? # 示例: # LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ ); # cache.put(1, 1); # cache.put(2, 2); # cache.get(1); // 返回 1 # cache.put(3, 3); // 去除 key 2 # cache.get(2); // 返回 -1 (未找到key 2) # cache.get(3); // 返回 3 # cache.put(4, 4); // 去除 key 1 # cache.get(1); // 返回 -1 (未找到 key 1) # cache.get(3); // 返回 3 # cache.get(4); // 返回 4 class LFUCache: __data = dict() __length = None __time = 0 def __init__(self, capacity: int): self.__length = capacity def get(self, key: int) -> int: val = self.__data.get(key) if val == None: return -1 self.__data[key][1] += 1 self.__time += 1 self.__data[key][2] = self.__time return self.__data[key][0] def put(self, key: int, value: int) -> None: val = self.__data.get(key) if val != None: self.__data[key][0] = value self.__data[key][1] += 1 self.__data[key][2] = self.__time return if len(self.__data) + 1 > self.__length: remove_k = None remove_v = [0x3f3f3f3f, self.__time+1] for k, v in self.__data.items(): if v[1] < remove_v[0] or (v[1] == remove_v[0] and v[2] < remove_v[1]): remove_k = k remove_v = [v[1], v[2]] self.__data.pop(remove_k) self.__time += 1 self.__data[key] = [value, 0, self.__time] # 11 测试用例 提交不通过但是本地测试通过 # if __name__ == "__main__": # cache = LFUCache(3) # print(cache.put(2, 2)) # print(cache.put(1, 1)) # print(cache.get(2)) # print(cache.get(1)) # print(cache.get(2)) # print(cache.put(3, 3)) # print(cache.put(4, 4)) # print(cache.get(3)) # print(cache.get(2)) # print(cache.get(1)) # print(cache.get(4)) class hashLink: __data = dict() __min_freq = 0 def put(self, node: dict): link = self.__data.get(node['freq']) if link == None: link = { 'head': None, 'tail': None, } self.__data[node['freq']] = link node['next'] = self.__data[node['freq']]['head'] if self.__data[node['freq']]['head'] != None: self.__data[node['freq']]['head']['pre'] = node self.__data[node['freq']]['head'] = node if self.__data[node['freq']]['tail'] == None: self.__data[node['freq']]['tail'] = node if node['freq'] < self.__min_freq: self.__min_freq = node['freq'] def remove(self) -> int: res = self.__data[self.__min_freq]['tail'] self.delete(self.__data[self.__min_freq]['tail']) return res['k'] def delete(self, node: dict) -> None: if node['pre'] == None: if node['next'] == None: self.__data.pop(node['freq']) else: self.__data[node['freq']]['head'] = node['next'] node['next']['pre'] = None else: if node['next'] == None: self.__data[node['freq']]['tail'] = node['pre'] node['pre']['next'] = None else: node['pre']['next'] = node['next'] node['next']['pre'] = node['pre'] def update(self, node: dict) -> None: self.delete(node) if self.__min_freq not in self.__data and node['freq'] == self.__min_freq: self.__min_freq += 1 node['freq'] += 1 node['pre'] = None node['next'] = None self.put(node) class LFUCacheBetter: def __init__(self, capacity: int): self.__len = capacity self.__data = dict() self.__hashlink = hashLink() def get(self, key: int) -> int: if key in self.__data: self.__hashlink.update(self.__data[key]) return self.__data[key]['v'] return -1 def put(self, key: int, value: int) -> None: if not self.__len: return if len(self.__data) + 1 > self.__len: k = self.__hashlink.remove() self.__data.pop(k) if key in self.__data: self.__data[key]['v'] = value self.__hashlink.update(self.__data[key]) else: self.__data[key] = { 'freq': 0, 'k': key, 'v': value, 'pre': None, 'next': None } self.__hashlink.put(self.__data[key]) # 8 测试用例报 4 keyerror 错误 本地运行无误 if __name__ == "__main__": # cache = LFUCacheBetter(3) # print(cache.put(2, 2)) # print(cache.put(1, 1)) # print(cache.get(2)) # print(cache.get(1)) # print(cache.get(2)) # print(cache.put(3, 3)) # print(cache.put(4, 4)) # print(cache.get(3)) # print(cache.get(2)) # print(cache.get(1)) # print(cache.get(4)) # cache = LFUCacheBetter(2) # print(cache.put(2, 1)) # print(cache.put(2, 2)) # print(cache.get(2)) # print(cache.put(1, 1)) # print(cache.put(4, 4)) # print(cache.get(2)) cache = LFUCacheBetter(1) print(cache.put(2, 1)) print(cache.get(2)) print(cache.put(3, 2)) print(cache.get(2)) print(cache.get(3)) # None # None # 2 # 1 # 2 # None # None # -1 # 2 # 1 # 4
c40f02ed6ae09320221ce9d5f8ebefd7b38e0563
syedmuhammadhassanzaidi/CampaignMonitor
/CampaignMonitorTechTask/PythonScripts/task4.py
455
4.03125
4
def find_duplicates(input): dup_list = [] counter = 1 for i in input: num_rep = input.count(i) if (num_rep >= counter): counter = num_rep dup_list.append(i) return set(dup_list) """ Test cases """ input = [5, 4, 3, 2, 4, 5, 1, 6, 1, 2, 5, 4] #input = [1, 2, 3, 4, 5, 1, 6, 7] #input = [1, 2, 3, 4, 5, 6, 7] most_rep = find_duplicates(input) print('Most Occurring Values are: {0}'.format(most_rep))
3ca6af54de82b2114830534eaa9ebe8965073866
zexiangzhang/algorithmAndDataStructure
/data_structure/graph/depth_first_search.py
2,638
3.671875
4
# depth first search # adjacency matrix from adjacency_matrix import AdjacencyMatrix def depth_first_search(graph, i): global vertex_visited vertex_visited[i] = True print(graph.get_vertex_value(i)) for j in range(graph.get_number()): if graph.has_arc(i, j) and not vertex_visited[j]: depth_first_search(graph, j) def depth_first_search_traverse(graph): global vertex_visited for i in range(graph.get_number()): if not vertex_visited[i]: depth_first_search(graph, i) test = AdjacencyMatrix(False, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I') test.insert_arc('A', 'B', 1) test.insert_arc('A', 'F', 1) test.insert_arc('B', 'G', 1) test.insert_arc('F', 'G', 1) test.insert_arc('E', 'F', 1) test.insert_arc('E', 'H', 1) test.insert_arc('D', 'E', 1) test.insert_arc('D', 'H', 1) test.insert_arc('G', 'H', 1) test.insert_arc('D', 'G', 1) test.insert_arc('D', 'I', 1) test.insert_arc('C', 'D', 1) test.insert_arc('C', 'I', 1) test.insert_arc('B', 'C', 1) test.insert_arc('B', 'I', 1) vertex_visited = [False] * test.get_number() depth_first_search_traverse(test) print('=====================') # adjacency list from adjacency_list import AdjacencyList, VertexNode def depth_first_search_list(graph, i): global vertex_visited_list vertex_visited_list[i] = True current_vertex = graph.get_vertex_value(i) print(current_vertex.value) first_arc = current_vertex.first_arc while first_arc: to_vertex = first_arc.to_vertex j = graph.get_vertex_key(to_vertex) if not vertex_visited_list[j]: depth_first_search_list(graph, j) first_arc = first_arc.next_arc def depth_first_search_traverse_list(graph): global vertex_visited_list for i in range(graph.get_number()): if not vertex_visited_list[i]: depth_first_search_list(graph, i) a = VertexNode('A') b = VertexNode('B') c = VertexNode('C') d = VertexNode('D') e = VertexNode('E') f = VertexNode('F') g = VertexNode('G') h = VertexNode('H') i = VertexNode('I') test_list = AdjacencyList(False, a, b, c, d, e, f, g, h, i) test_list.add_arc(a, b, 1) test_list.add_arc(a, f, 1) test_list.add_arc(b, g, 1) test_list.add_arc(f, g, 1) test_list.add_arc(e, f, 1) test_list.add_arc(e, h, 1) test_list.add_arc(d, e, 1) test_list.add_arc(d, h, 1) test_list.add_arc(g, h, 1) test_list.add_arc(d, g, 1) test_list.add_arc(d, i, 1) test_list.add_arc(c, d, 1) test_list.add_arc(c, i, 1) test_list.add_arc(b, c, 1) test_list.add_arc(b, i, 1) vertex_visited_list = [False] * test_list.get_number() depth_first_search_traverse_list(test_list)
189158a0718e676060467288f21f9e376f009062
je-castelan/Algorithms_Python
/Python_50_questions/3 Binary Search/binary_tree.py
1,692
3.984375
4
def binarySearchRecursive(arr,obj,initial,final): middle = (initial+final) // 2 if arr[middle] == obj: return middle elif initial > final: return -1 elif arr[middle] < obj: return binarySearchRecursive(arr,obj,middle + 1,final) else: return binarySearchRecursive(arr,obj,initial,middle - 1) def binarySearchWhile(arr, target): left = 0 right = len(arr)-1 while left <= right: mid = (left+right)//2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 def printfunc(arr,obj): res = binarySearchRecursive(arr,obj,0,len(arr)-1) print ("BUSQUEDA BINARIA CON RECURSIVIDAD DE {} EN {} ES {}".format(obj,arr, res)) res = binarySearchWhile(arr,obj) print ("BUSQUEDA BINARIA CON WHILE DE {} EN {} ES {}".format(obj,arr, res)) if __name__ == "__main__": printfunc([11,12,14,15,16,17,18],18) printfunc([11,12,14,15,16,17,18],17) printfunc([11,12,14,15,16,17,18],16) printfunc([11,12,14,15,16,17,18],15) printfunc([11,12,14,15,16,17,18],14) printfunc([11,12,14,15,16,17,18],13) printfunc([11,12,14,15,16,17,18],12) printfunc([11,12,14,15,16,17,18],11) printfunc([11,12,14,15,16,17,18,19],19) printfunc([11,12,14,15,16,17,18,19],18) printfunc([11,12,14,15,16,17,18,19],17) printfunc([11,12,14,15,16,17,18,19],16) printfunc([11,12,14,15,16,17,18,19],15) printfunc([11,12,14,15,16,17,18,19],14) printfunc([11,12,14,15,16,17,18,19],13) printfunc([11,12,14,15,16,17,18,19],12) printfunc([11,12,14,15,16,17,18,19],11)
123a3365a015f1ce2bd77f6d907784e6f7759e18
MiroVatov/Python-SoftUni
/Python Advanced 2021/EXAMS_PREPARATION/additional_exams/02_presents_delivery.py
4,758
3.671875
4
def nice_kids_count(matrix, NICE_KID_HOUSE): nice_kids = 0 for row in range(len(matrix)): for col in range(len(matrix[row])): if matrix[row][col] == NICE_KID_HOUSE: nice_kids += 1 return nice_kids def santa_starting_position(matrix, santa): for row in range(len(matrix)): if santa in matrix[row]: return row, matrix[row].index(santa) def check_indices(row, col, size): if 0 <= row < size and 0 <= col < size: return True return False def move_player(row, col, dir_dict, move_com): row += dir_dict[move_com][0] col += dir_dict[move_com][1] return row, col def print_matrix(matrix): for line in range(len(matrix)): print(f"{' '.join(matrix[line])}") def change_matrix_after_move(matrix, pr_row, pr_col, cur_row, cur_col): matrix[pr_row][pr_col] = EMPTY_POSITION matrix[cur_row][cur_col] = SANTA return matrix number_of_presents = int(input()) size = int(input()) neighborhood = [list(input().split()) for _ in range(size)] SANTA = 'S' # -> Santa's starting position - > Santa moves - > EMPTY_POSITION NAUGHTY_KID_HOUSE = 'X' # don't receive a present in normal cases -> house becomes EMPTY_POSITION NICE_KID_HOUSE = 'V' # receives a present always -> house becomes EMPTY_POSITION EMPTY_POSITION = '-' COOKIE = 'C' # -> Santa eats cookies and becomes happy and extra generous to all the kids around him* (meaning all of them will receive presents (doesn’t matter if naughty or nice)) # But Santa doesn't change his position -> only change the houses to EMPTY_POSITIONS directions_dict = { 'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1), } # Keep in mind that you have to check whether all of the nice kids received presents! santa_current_row, santa_current_col = santa_starting_position(neighborhood, SANTA) nice_kids_presents = 0 while number_of_presents > 0: command = input() if command == "Christmas morning": break santa_previous_row, santa_previous_col = santa_current_row, santa_current_col if command == 'up': santa_current_row, santa_current_col = move_player(santa_current_row, santa_current_col, directions_dict, command) elif command == 'down': santa_current_row, santa_current_col = move_player(santa_current_row, santa_current_col, directions_dict, command) elif command == 'left': santa_current_row, santa_current_col = move_player(santa_current_row, santa_current_col, directions_dict, command) elif command == 'right': santa_current_row, santa_current_col = move_player(santa_current_row, santa_current_col, directions_dict, command) if not check_indices(santa_current_row, santa_current_col, size): continue if neighborhood[santa_current_row][santa_current_col] == NICE_KID_HOUSE: neighborhood = change_matrix_after_move(neighborhood, santa_previous_row, santa_previous_col, santa_current_row, santa_current_col) number_of_presents -= 1 nice_kids_presents += 1 elif neighborhood[santa_current_row][santa_current_col] == NAUGHTY_KID_HOUSE: neighborhood = change_matrix_after_move(neighborhood, santa_previous_row, santa_previous_col, santa_current_row, santa_current_col) elif neighborhood[santa_current_row][santa_current_col] == COOKIE: neighborhood = change_matrix_after_move(neighborhood, santa_previous_row, santa_previous_col, santa_current_row, santa_current_col) for move in directions_dict.values(): if number_of_presents > 0: row = santa_current_row + move[0] col = santa_current_col + move[1] if neighborhood[row][col] == NICE_KID_HOUSE: neighborhood[row][col] = EMPTY_POSITION number_of_presents -= 1 nice_kids_presents += 1 elif neighborhood[row][col] == NAUGHTY_KID_HOUSE: neighborhood[row][col] = EMPTY_POSITION number_of_presents -= 1 elif neighborhood[santa_current_row][santa_current_col] == EMPTY_POSITION: neighborhood = change_matrix_after_move(neighborhood, santa_previous_row, santa_previous_col, santa_current_row,santa_current_col) nice_kids = nice_kids_count(neighborhood, NICE_KID_HOUSE) if number_of_presents <= 0 < nice_kids: print(f"Santa ran out of presents!") print_matrix(neighborhood) if nice_kids <= 0: print(f"Good job, Santa! {nice_kids_presents} happy nice kid/s.") else: print(f"No presents for {nice_kids} nice kid/s.")
34c8e2266fe8a0a8cf652ef25c67c8ed7ead19a2
class-archives/ENGR-141
/Fall-2015/Post-Activities/Python-1/task2.py
1,082
4
4
# Activity: Python 1 Post Activity # File: Py1_PA_Task2_katherto.py # Date: September 17, 2015 # By: Kathryn Atherton # katherto # Section: 4 # Team: 59 # # ELECTRONIC SIGNATURE # Kathryn Atherton # The electronic signature above indicates that the program # submitted for evaluation is my individual work. I have # a general understanding of all aspects of its development # and execution. # # This program can be used to calculate the equivalent # resistance of series and parallel configurations of 2 # resistors. The output is formatted as a table. from tabulate import tabulate import math First_Resistance = round(float(input("Enter First Resistance:")), 1) Second_Resistance = round(math.sqrt(5.6) * math.pi, 1) Parallel = round(((1 / First_Resistance) + (1 / Second_Resistance)) ** (-1), 1) Series = round(First_Resistance + Second_Resistance, 1) table = [['Type of Resistance', 'First Resistance', 'Second Resistance', 'Equivalent Resistance'], ['Parallel', First_Resistance, Second_Resistance, Parallel], ['Series', First_Resistance, Second_Resistance, Series]] print tabulate(table)
096c8ff0774d84cfe87080eb15453b6464fca46a
SHGITHUBSH/Basic-Python
/source/Basic-If Statement.py
581
4.34375
4
#If Statements Taller_than_the_other_gender = True More_muscular = False Grow_beard = True if Taller_than_the_other_gender or More_muscular or Grow_beard: print("You have possibility to be a male.") elif Taller_than_the_other_gender and not More_muscular and not Grow_beard: print("You might be a girly man.") else: print("You are not a male.") print("\n") def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print(max_num(5,7,4)) print("\n")
1b06fa212a883473b9c055674aeff0076b6518f8
nf-core/ampliseq
/bin/filt_codons.py
3,689
3.640625
4
#!/usr/bin/env python3 ##### Program description ####### # # Title: Filtering ASVs with stop codons # # Author(s): Lokeshwaran Manoharan # # # # Description: The ASVs are filtered if they contain stop codons in the reading frame specified. # # List of subroutines: # # # # Overall procedure: using functions and dictionaries in python # # Usage: filt_codons.py [-h] -f <Seq_file> -t <ASV_table> [-s BEGIN] [-e END] -p <output_basename> # ################################## import re import sys import copy import argparse usage = """This program filters ASVs that contains any stop codon or if the length from the position is not a multiple of 3 in the right reading frame.""" parser = argparse.ArgumentParser(description=usage) parser.add_argument( "-f", "--fasta", dest="fasta", type=argparse.FileType("r"), help="Fasta file of the ASVs from the AmpliSeq pipeline", required=True, ) parser.add_argument( "-t", "--count-table", dest="count", type=argparse.FileType("r"), help="Count table file of the ASVs from the AmpliSeq pipeline", required=True, ) parser.add_argument( "-s", "--start-position", dest="begin", type=int, help="Specific position of the ASV where to start checking for codons. By default it starts from position 1", required=False, default=0, ) parser.add_argument( "-e", "--end-position", dest="end", type=int, help="Specific position of the ASV where to stop checking for codons. By default it checks until the end of the sequence", required=False, ) parser.add_argument( "-x", "--stop-codons", dest="stopcodon", type=str, help='Specific stop codons to look for. Specify multiple codons with in a comma separated list like: "TAA,TAG". By default TAA and TAG are being looked for.', required=False, default="TAA,TAG", ) parser.add_argument( "-p", "--out-prefix", dest="prefix", type=str, help="Prefix of the output files with filtered ASVs and the corresponding count table. The output files will be in *<prefix>_filtered.* format", required=True, ) args = parser.parse_args() if args.begin is not None: begin = args.begin else: begin = 1 if args.stopcodon is not None: stopcodon = args.stopcodon else: stopcodon = "TAA,TAG" stop_list = [item.strip() for item in stopcodon.split(",")] def check_asv(seq, start, stop): sub_seq = seq[start - 1 : stop] sub_list = [] for x in range(0, len(sub_seq), 3): sub_list.append(sub_seq[x : x + 3]) if not len(sub_seq) % 3 == 0: return False elif any(x in sub_list for x in stop_list): return False else: return True Out_Seq = open(args.prefix + "_filtered.fna", "w") Out_list = open(args.prefix + "_filtered.list", "w") Out_table = open(args.prefix + "_filtered.table.tsv", "w") count_dict = {} p1 = re.compile("\t") p2 = re.compile(">") count = 0 for line in args.count: line = line.rstrip("\n") if count == 0: print(line, file=Out_table) count += 1 else: tmp_list = re.split(p1, line) count_dict[tmp_list[0]] = line for line in args.fasta: line = line.rstrip("\n") if re.match(p2, line) is not None: bin_head = re.sub(p2, "", line) else: if args.end is not None: end = args.end else: end = len(line) if check_asv(line, begin, end): print(">", bin_head, "\n", line, file=Out_Seq, sep="") print(bin_head, file=Out_list) print(count_dict[bin_head], file=Out_table) args.count.close() args.fasta.close() Out_Seq.close() Out_list.close() Out_table.close()
944fa8f12006ccda60329d6b24a1222fe093cddc
Davidxswang/leetcode
/easy/821-Shortest Distance to a Character.py
1,133
3.875
4
""" https://leetcode.com/problems/shortest-distance-to-a-character/ Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. Example 1: Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] Note: S string length is in [1, 10000]. C is a single character, and guaranteed to be in string S. All letters in S and C are lowercase. """ # time complexity: O(n), space complexity: O(n) class Solution: def shortestToChar(self, S: str, C: str) -> List[int]: left = [0] * len(S) right = [0] * len(S) for i in range(len(S)): if S[i] == C: left[i] = 0 elif i != 0: left[i] = left[i - 1] + 1 else: left[i] = 10001 if S[~i] == C: right[~i] = 0 elif ~i != -1: right[~i] = right[~i + 1] + 1 else: right[~i] = 10001 result = [] for i in range(len(S)): result.append(min(left[i], right[i])) return result
712cedf8d8fb7674bf198dae99974f5006904329
DariaPetrovaa/mipt_python
/w6/7.py
1,934
4.25
4
from math import sqrt #Координаты вектора вводятся в виде строки "x,y,z" class Vector: def __init__(self, a): if type(a) is list: a = "".join(map(str,a)) x, y, z = a.split(',') x = int(x) y = int(y) z = int(z) self.x = x self.y = y self.z = z def __add__(self, other): a1 = self.x + other.x a2 = self.y + other.y a3 = self.z + other.z ans = self.formatir(a1,a2,a3) return Vector(ans) def __sub__(self, other): a1 = self.x - other.x a2 = self.y - other.y a3 = self.z - other.z ans = self.formatir(a1,a2,a3) return Vector(ans) def __and__(self, other): a1 = self.y*other.z - other.y*self.z a2 = other.x*self.z - self.x*other.z a3 = self.x*other.y - self.y*other.x ans = self.formatir(a1,a2,a3) return Vector(ans) def formatir(self,a1,a2,a3): ans = a1,a2,a3 ans = str(ans) ans = ans[:0] + ans[1:-1] ans = str(ans) return ans def distance(self): return sqrt(self.x**2 + self.y**2 + self.z**2) def __str__(self): return f"Вектор имеет координаты {self.x, self.y, self.z}" N=int(input()) points_list = [[0]*3 for _ in range(N)] for i in range(N): a = input() a = ', '.join(list(a.split(','))) points_list[i]=a ans = 0 for i in range(N): b = Vector(points_list[i]) dist = b.distance() if dist > ans: ans = dist point = points_list[i] print('Наиболее дальняя точка имеет координаты', point, ". Расстояние от этой точки до начала координат", ans, '.') A = Vector('2,4,5') B=Vector('3,56,7') C = A - B print(str(C)) C = A + B print(str(C)) C = A & B print(str(C))
e7f7926e193a9f4d7436384d75467656cbb9f045
weiyang-1/sort_practice
/Insert_sort.py
821
3.65625
4
# -*- coding: utf-8 -*- """ @Created: 2020/10/13 13:50 @AUTH: MeLeQ @Used: pass """ from tools import gene_random_list def insert_sort(random_list: list) -> list: """ 插入排序 保证前面的队列是一个有序的 每次从后面找一个插入到有序的里面去 当后面的数比前面小才需要进行插入 否则跳过当前数 :param random_list: :return: """ length = len(random_list) if length <= 1: return random_list for i in range(1, length): for j in range(i,0,-1): if random_list[j-1] > random_list[j]: random_list[j-1], random_list[j] = random_list[j], random_list[j-1] else: break return random_list if __name__ == '__main__': r = insert_sort(gene_random_list()) print(r)
d480263ae734088e84a8f207e420f2c85babbf91
hscspring/The-DataStructure-and-Algorithms
/CodingInterview2/06_PrintListInReversedOrder/print_list_in_reversed_order.py
1,152
4.40625
4
""" 面试题 6:从尾到头打印链表 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。 """ class Node: def __init__(self, x): self.val = x self.next = None def print_list_reverse(node) -> list: """ print_list_reverse(Node) Print a linklist reversedly. Parameters ----------- Node: Node Returns ------- out: list """ res, stack = [], [] while node: stack.append(node.val) node = node.next while len(stack): res.append(stack.pop()) return res def print_list_reverse_recursive(node, res) -> list: if node: res.insert(0, node.val) print_list_reverse_recursive(node.next, res) def lst2link(lst): root = Node(None) ptr = root for i in lst: ptr.next = Node(i) ptr = ptr.next ptr = root.next return ptr if __name__ == '__main__': lst = [1, 2, 3, 4, 5] # lst = [1] node = lst2link(lst) # while node: # print(node.val) # node = node.next res = [] print_list_reverse_recursive(node, res) print(res)
1a621f52b96e4d79b6eef9313d783d648719d97a
TSamCode/Algorithms
/palindrome.py
680
4.1875
4
# Function to see if a string is some permutation of a palindrome from collections import Counter def permPalindrome(string): # creates a list of characters stringChars = [char for char in string.lower() if char.isalpha()] # create a dictionary containing the count of each character in the string charCounts = Counter(stringChars) # We add up the number of characters that appear an odd number of times oddCharCounts = sum(1 for char, count in charCounts.items() if count%2) # If all characters appear an even number of times, or there is only one odd count then a palindrome is possible return oddCharCounts <= 1 print(permPalindrome('Thomas'))
69bb9b6610a91b92c209ced84b91b4ae63d4edd8
deesaw/PythonD-04
/Exception Handling/46_except2.py
425
4.0625
4
while True: try: x = input("Please enter a number: ") y = input("Please enter a number to divide: ") num= int(x)/int(y) print("Result: ",num) break except ValueError: print("Oops! That was not a valid number. Try again...") except ZeroDivisionError as err: print('Check your denominator.\n The system generated error is', err)
33c4711b363b20b4b9c1a0c78009d627ebb66a8a
Cameron-Calpin/Code
/Python - learning/Looping/loop-control.py
358
4.3125
4
list = [1,2,3,4,5,6,7,8,9] # the loop iterates by one until it hits 7; then stops. for int in list: if int == 7: break else: print(int, end=' ') print('\n') # once the loop hits 7, it will continue to 9. # after the loop has finished, the else will print for int in list: if int == 7: continue else: print(int, end=' ') else: print('default')
78ed63468ebe0aa5aea8be76b0f018e07b8b0c76
fsym-fs/Python_AID
/month01/day07_function+for_for/test/test01.py
868
3.53125
4
""" test01 1.["齐天大圣","猪八戒","唐三藏"]--->key:字符,value:字符长度 2.["张无忌","赵敏","周芷若"] [101,102,103]-->{"张无忌":101..} 3.将练习二的字典的键与值颠倒 4. 骰子 1--6 骰子 1--6 骰子 1--6 将三个骰子的组合数存入列表 """ a = {'cid': 101, 'count': 1} print(a['cid']) # if 101 in a['cid'] : # print("44") # print(a[1]) try: xyj = ["齐天大圣", "猪八戒", "唐三藏"] dict_xyj = {key: len(key) for key in xyj} print(dict_xyj) yttlj_name = ["张无忌", "赵敏", "周芷若"] yttlj_key = [101, 102, 103] yttlj_dict = {yttlj_name[i]: yttlj_key[i] for i in range(len(yttlj_name))} print(yttlj_dict) yttlj_dict2 = {values: key for key, values in yttlj_dict.items()} print(yttlj_dict2) except: print("程序错误!")
e4a288da43c70693fed19c04566de6c80d267743
Oshalb/HackerRank
/insertionp2.py
374
3.859375
4
# Insertion Sort - Part 2 def insertion_sort(n, a): for i in range(1, n): j = i while j > 0 and a[j-1] > a[j]: a[j], a[j-1] = a[j-1], a[j] j -=1 print(*a) if __name__ == "__main__": size_of_list = int(input()) number_list = list(map(int, input().rstrip().split())) insertion_sort(size_of_list, number_list)
dd2a93e18a3ddf756e13ffefa065a56faef4098f
haewon-mit/Syntax-Analysis
/AC-IPSyn/source/extractPhrases.py
730
3.5625
4
#Purpose: Extract phrases from a parse def extractPhraseLastBracket(parse): i=len(parse) stack=[] for j in range(i-1,-1,-1): if parse[j]==')': stack.append(')') elif parse[j]=='(': if len(stack)!=0: stack.pop() if len(stack)==0: #print parse[j:] return parse[j:] if len(stack) !=0: return parse[:i-len(stack)-1] return parse def extractPhraseFirstBracket(parse): #print "ExtractFirstBracket:" +parse i=len(parse) stack=[] for j in range(0,i): if parse[j]=='(': stack.append('(') elif parse[j]==')': if len(stack) !=0: stack.pop() if len(stack)==0: #print parse[:j+1] return parse[:j+1] if len(stack) !=0: print "Not encountered the end of brackets" return parse