text
stringlengths
37
1.41M
# coding:iso-8859-9 Trke # Python 3 - Multithreaded Programming # Yeni yntemle sicim yaratma: Thread altsnf, override __init__ ve run metodlar, # sicim tip nesneleri yaratma, start ile run' koturma, ve icabnda join ile sicimlerin # almas tamamlanmadan alttaki kodlamaya gememenin salanmas import threading import time kBayra = 0 # Zaman gstererek (0=False) sicimleri tamamlar... class sicimim (threading.Thread): def __init__ (self, sicimNo, sicimAd, geciktir): #Sicim kurucu metodu... threading.Thread.__init__ (self) self.sicimNo = sicimNo self.sicimAd = sicimAd self.geciktir = geciktir def run (self): print ("Balatlyor: " + self.sicimAd) zamanYaz (self.sicimAd, self.geciktir, 10) print ("Sonlandrlyor: " + self.sicimAd) def zamanYaz (ipAd, tehir, saya): while saya: # saya says kadar dng tekrar... if kBayra: # Zaman gstermeden (1=True) sicimleri tamamlar... break time.sleep (tehir) print ("[%s: Saya(%d) Tarih: %s]" % (ipAd, saya, time.ctime (time.time()))) saya -= 1 # 3 adet sicim tip nesnesi yaratalm... sicim1 = sicimim (10, "Sicim-1", 3) # Tehir enok, sonuncu olur... sicim2 = sicimim (25, "Sicim-2", 1) # Tehir enaz, nce tamamlanr... sicim3 = sicimim (15, "Sicim-3", 2) # Sicimleri balatalm... sicim1.start() sicim2.start() sicim3.start() # Sicimleri tamamlamadan alttaki kodlamaya gemesin... sicim1.join() sicim2.join() sicim3.join() print ("\nSicimler tamamland. Programdan klyor!")
# coding:iso-8859-9 Trke # 3: Python3 - Basic Operators # Python Identity Operators a=10; b=10 doru=True; yanl=doru print ("a=10 ve b=20") print ("a is b:", a is b) print ("doru is yanl:", doru is yanl) print ("a is not doru:", a is not doru)
# coding:iso-8859-9 Trke # p_10601.py: Python ilemcileriyle yaplan ilem ktlar rnei. print ("Toplama ve karma (10+/-3):", 10+3, 10-3) print ("arpma, blme ve kalan (27*/+7):", 27*7, 27/7, 27%7) print ("Ksratsz (-+//) zemin blme ve -+int(10/3) kesik blmesi:", 10//3, int (10/3), -10//3.0, int (-10/3) ) print ("ebirsel -+ iareti:", -3, +3) print ("Bitvari negatifleme:", ~3-4, ~-4+3) print ("-+s (**):", -2.5**5.78, 2.5**(-5.78) ) print ("Boolean or/veya, and/ve ve not/deil:", not (True or (True and False)) ) print ("Eleman m (True/False)?", 4 in [1957, 4, 17] ) print ("Karlatrma (2 ila 5) operatrleri (<, <=, >, >=, ==, !=):", 2<5, 2<=5, 2>5, 2>=5, 2==5, 2!=5) print ("Bitvari |/veya, &/ve, ^/farklysa (6=110 ila 3=011):", 6|3, 6&3, 6^3) print ("Kaydrma << ve >> operatrleri (6=110'y 2 kez kaydr):", 6<<2, 6>>2) """kt: >python p_10601.py Toplama ve karma (10+/-3): 13 7 arpma, blme ve kalan (27*/+7): 189 3.857142857142857 6 Ksratsz (-+//) zemin blme ve -+int(10/3) kesik blmesi: 3 3 -4.0 -3 ebirsel -+ iareti: -3 3 Bitvari negatifleme: -8 6 -+s (**): -199.5690776400273 0.00501079632087968 Boolean or/veya, and/ve ve not/deil: False Eleman m (True/False)? True Karlatrma (2 ila 5) operatrleri (<, <=, >, >=, ==, !=): True True False Fal se False True Bitvari |/veya, &/ve, ^/farklysa (6=110 ila 3=011): 7 2 5 Kaydrma << ve >> operatrleri (6=110'y 2 kez kaydr): 24 1 """
# coding:iso-8859-9 # p_13706.py: Snf nesnesi metodlar, oklu tip deikenlerine deer atama ve okuma rnei. class Robot: def __init__ (self, ad = None, tarih = None): self.ad = ad self.imalat = tarih def selamlama (self): if self.ad: print ("\nMerhaba, benim adm " + self.ad + "!") else: print ("Merhaba, ben henz ad konmam bir robotum!") if self.imalat: print ("malat tarihim: " + str (self.imalat) ) else: print ("malat tarihim maalesef bilinmiyor!") def adKoy (self, ad): self.ad = ad def adAl (self): return self.ad def tarihKoy (self, imalTarihi): self.imalat = imalTarihi def tarihAl (self): return self.imalat x1 = Robot() x1.selamlama() x1.adKoy ("Robot Nihat") x1.selamlama() x3 = Robot ("Robot Mahmut Nihat", 19570417) x3.selamlama() """kt: >python p_13706.py Merhaba, ben henz ad konmam bir robotum! malat tarihim maalesef bilinmiyor! Merhaba, benim adm Robot Nihat! malat tarihim maalesef bilinmiyor! Merhaba, benim adm Robot Mahmut Nihat! malat tarihim: 19570417 """
# coding:iso-8859-9 Trke # 4: Python3 - Decision Making say = 100 if ( say == 100 ) : print ("Deikenin deeri = 100") print ("Gle gle!\n") if (say == 90): print ("Deikenin deeri = 90") elif (say == 80): print ("Deikenin deeri 80 deildir!") print ("say=", say) else: print ("Deikenin deeri 80 veya 90 deildir!") print ("say=", say) print ("Tekrar gle gle!")
# coding:iso-8859-9 Trke ondalk = int (input ("Bir ondalk tamsay girin: ")) print ("Binary/kili karl =", bin (ondalk)) print ("Octal/Sekizlik karl =", oct (ondalk)) print ("Hexal/Onaltlk karl =", hex (ondalk), "\n") k = input ("Herhangibir klavye karakteri girin: ") print ("[" + k + "]'nn ASCII kod karl = ", ord (k))
#coding:iso-8859-9 Trke from random import randint tesadfi = randint (0,100) kere=tahmin = alt = 0 st = 100 for i in range (10): if tahmin > alt: try: tahmin = eval (input ("Tahmininiz (" + str (tahmin - (st - alt)//2) + "): ")) if tahmin > st or tahmin < alt: tahmin = randint (alt, st) except Exception: tahmin -= (st - alt)//2 else: try: tahmin = eval (input ("Tahmininiz (" + str (tahmin + (st - alt)//2) + "): ")) if tahmin > st or tahmin < alt: tahmin = randint (alt, st) except Exception: tahmin += (st - alt)//2 kere +=1 if tahmin < tesadfi: print (kere, ": DAHA YKSEK [", tahmin, "->", st, "] GR", sep=""); alt = tahmin elif tahmin > tesadfi: print (kere, ": DAHA DK [", alt, "->", tahmin, "] GR", sep=""); st = tahmin else: print ("BRAVO! ", kere, '.tahminde ', tesadfi, "'yi buldunuz.", sep=""); break else: print ('\nMaalesef KAYBETTNZ. Doru tahmin', tesadfi, "olmalyd!")
# coding:iso-8859-9 Trke # p_40808.py: Canvas tuvalinde eit aralkl yatay-dikey zgara hatlar izimi rnei. from tkinter import * from p_315 import Renk def zgaralama (t, aralk, en, boy): # Dikey/boy ve yatay/en izgiler aralk/px mesafeli olacak... renk = Renk.renk() for x in range (aralk, en, aralk): t.create_line (x,0, x,boy, fill=renk) for y in range (aralk, boy, aralk): t.create_line (0,y, en,y, fill=renk) kk = Tk() kk.title ("Izgaralama") tuvalEni = 300 tuvalBoyu =100 tuval = Canvas (kk, width=tuvalEni, height=tuvalBoyu, bg=Renk.renk() ) tuval.pack() zgaralama (tuval,10, tuvalEni, tuvalBoyu) kk.mainloop()
# coding:iso-8859-9 Trke # p_13206.py: reduce(lambda fonk, liste) ile liste elemanlarnn toplam, arpm min-max' rnei. from random import randint from functools import reduce print ("'reduce' ile liste elemanlarn toplama:", "\n", "-"*40, sep="") print ("[47,11,42,13] 4 adet liste elemanlar toplam:", reduce (lambda x,y: x+y, [47,11, 42,13]) ) print ("[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597] 18 adet sral fibonaki liste elemanlar toplam:", reduce (lambda x,y: x+y, [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597]) ) print ("[randint(200) for i range(100)] 100 adet rasgele kapsaml liste elemanlar toplam:", reduce (lambda x,y: x+y, [randint (0, 200) for i in range (100)]) ) #--------------------------------------------------------------------------------------------------------- print ("\n'reduce' ile liste elemanlarnn byk veya knn tespiti:", "\n", "-"*61, sep="") lambdam = lambda a,b: a if (a > b) else b print ("[47,11,42,102,13] liste elemanlarnn by:", reduce (lambdam, [47,11,42,102,13]) ) print ("[47,11,42,102,13] liste elemanlarnn k:", reduce (lambda a,b: a if (a<b) else b, [47,11,42,102,13]) ) #--------------------------------------------------------------------------------------------------------- print ("\n'reduce' ile sral liste elemanlarnn toplam ve arpm:", "\n", "-"*58, sep="") print ("lk 100 say listesinin toplam:", reduce (lambda x,y: x+y, [i for i in range (1, 101)]) ) print ("lk 100 say listesinin arpm:", reduce (lambda x,y: x*y, [i for i in range (1, 101)]) ) #--------------------------------------------------------------------------------------------------------- print ("\nPiyangoda 49 ekiliten 6'sn kazanma ans:", end=" ") print (reduce (lambda x, y: x*y, range (44, 50)) / reduce (lambda x, y: x*y, range (1, 7)), "'da 1'dir.", sep="" ) """kt: >python p_13206.py 'reduce' ile liste elemanlarn toplama: ---------------------------------------- [47,11,42,13] 4 adet liste elemanlar toplam: 113 [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597] 18 adet sral fibonaki liste elemanlar toplam: 4180 [randint(200) for i range(100)] 100 adet rasgele kapsaml liste elemanlar toplam: 10169 'reduce' ile liste elemanlarnn byk veya knn tespiti: ------------------------------------------------------------- [47,11,42,102,13] liste elemanlarnn by: 102 [47,11,42,102,13] liste elemanlarnn k: 11 'reduce' ile sral liste elemanlarnn toplam ve arpm: ---------------------------------------------------------- lk 100 say listesinin toplam: 5050 lk 100 say listesinin arpm: 93326215443944152681699238856266700490715968264 38162146859296389521759999322991560894146397615651828625369792082722375825118521 0916864000000000000000000000000 Piyangoda 49 ekiliten 6'sn kazanma ans, dese de zrva: 13983816.0'da 1'dir. """
# coding:iso-8859-9 Trke # Python3 - Dictionary szlk1 = {'Ad': 'M.Nihat', 'soyad': 'Yava', 'Ya': 62, 'doum yeri': 'Yeilyurt'} szlk2 = {1: "Bir", 2:"ki", "":""} szlk3 = {} print ("szlk1['Ad']:", szlk1['Ad']) print ("szlk1['Ya']:", szlk1['Ya']) print ("szlk1['doum yeri']:", szlk1['doum yeri']) szlk1 ['Ya'] = 65; # gncelleme... szlk1['Doum Yl'] = 1957 # Yeni ierik girii... print ("szlk1['Ya']: ", szlk1['Ya']) print ("szlk1['Doum Yl']: ", szlk1['Doum Yl']) del szlk1['Ad'] # Tek ierik silinmesi... print (szlk1) szlk1.clear() # Tm ieriklerin silinmesi... print (szlk1) del szlk1 # Szln silinmesi... # print (szlk1) ==> NameError: name 'szlk1' is not defined szlk1 = {'Ad': 'Mahmut', 'soyad': 'Yava', 'Ya': 62, 'doum yeri': 'Yeilyurt', 'Ad': 'Nihat'} print (szlk1) print (len (szlk1)) print (szlk2) print (type (szlk3)) print (szlk1.keys()) print (szlk1.values()) print (szlk1.items()) szlk1.update (szlk2) print (szlk1)
#coding=utf-8 #ไธคไธชๅˆ—่กจ็›ธไน˜็›ธๅŠ  def list_multi(ls1,ls2): sum=0 for i in range(len(ls1)): sum+=ls1[i]*ls2[i] return sum #ไธคไธชๅˆ—่กจ็š„ๅ‡ๆณ• def list_sub(big,small): ls=[] for i in range(len(big)): ls.append(big[i]-small[i]) return ls #ๅˆ—่กจๅ ๅŠ ๅค„็† def list_add(ls): def sum(lista): sum=0 for i in range(len(lista)): sum+=lista[i] return sum lsa=[] for i in range(len(ls)): lsa.append(sum(ls[0:i+1:1])) return lsa def main(): print list_add([1,2,3,4]) print list_multi([0,0,0,1],[2,3,4,5]) if __name__=="__main__": main()
grupo1 = [ ] grupo2 = [ ] for i in range(6): aux = -1 while aux < 0: num = float(input(f'Informe a nota do {i+1}ยบ aluno: ')) if(num > 10): print('Tente novamente!') elif(num < 0): print('Tente novamente!') else: grupo1.append(num) aux = 1 for i in range(6): aux2 = -1 while aux2 < 0: num2 = float(input(f'Informe a nota do {i+1}ยบ aluno do 2ยบ grupo: ')) if (num2 < 0): print('Tente novamente!') elif(num2 > 10): print('Tente novamente!') else: grupo2.append(num2) aux2 = 1 maior1 = 0 menor1 = 99 posmenor = 0 posmaior = 0 for i in range(6): if grupo1[i] > maior1: maior1 = grupo1[i] posmaior = i if grupo1[i] < menor1: menor1 = grupo1[i] posmenor = i maior2 = 0 menor2 = 99 posmenor2 = 0 posmaior2 = 0 for i in range(6): if grupo2[i] > maior2: maior2 = grupo2[i] posmaior2 = i if grupo2[i] < menor2: menor2 = grupo2[i] posmenor2 = i print(grupo1) print('A maior nota foi {}, sua posiรงรฃo รฉ:{}, a menor nota:{}, sua posiรงรฃo รฉ:{}'.format(maior1,posmaior,menor1,posmenor)) print(grupo2) print('A maior nota do 2ยบ grupo foi:{} e sua posiรงรฃo รฉ:{}, a menor nota foi:{} e sua posiรงรฃo รฉ:{}'.format(maior2,posmaior2,menor2,posmenor2))
import sqlite3 # from .config import db # .config means import from this directory # Get datetime info when the user gets a location. Store it in the user class. db_path = 'api.db' db = db_path class API: def __init__(self): with sqlite3.connect(db) as conn: conn.execute ('CREATE TABLE IF NOT EXISTS User_Data(User_Email TEXT, Weather_API TEXT, YELP_API TEXT, CURRENCY_API TEXT, DATE TEXT)') conn.execute ('CREATE TABLE IF NOT EXISTS Users (User_Email TEXT, User_Password) ') print("init") def add_User_Data (self,User, location, weather,yelp, currency): insert_sql = "INSERT INTO User_Data (User_Email, Weather_API, Yelp_API, Currency_API, DATE) VALUES (?,?,?,?,?)" date = "" with sqlite3.connect(db) as conn: conn.execute(insert_sql, (User, weather, yelp ,currency, date ) ) #print("Success") commented out for clean look conn.close() def view_User_Data(self,User_Email): conn = sqlite3.connect(db) sql_view = ('SELECT * FROM User_Data WHERE User_Email = (?)') cur = conn.cursor() cur.execute(sql_view,(User_Email,) ) rows = cur.fetchall() for row in rows: print(row) conn.close() return def User_Login (self, User_Email, User_Password): read_sql = "SELECT User_Email , User_Password FROM Users WHERE User_Email = (?) AND User_Password = (?) " with sqlite3.connect(db) as conn : c = conn.cursor() c.execute (read_sql ,(User_Email,User_Password) ) all_rows = c.fetchall() # Checking if there are any Artwork and returning the proper values. if len (all_rows) == 0 : print(f'| {User_Email} has no profile here.') else: #print("| Profile exists") return True, User_Email def create_User(self, User_Email, User_Password): insert_sql = "INSERT INTO Users (User_Email, User_Password) VALUES (?,?)" insert_check_sql = " SELECT User_Email FROM Users WHERE User_Email =(?)" with sqlite3.connect(db) as conn: c = conn.cursor() c.execute (insert_check_sql, (User_Email,)) all_rows = c.fetchall() if len (all_rows) > 0: print(f'| {User_Email} is already in the User database. Account not created. ') else : conn.execute(insert_sql, (User_Email, User_Password)) print(f"| Added {User_Email}!") return True conn.close()
#Find the bigger and smaller number in a list lista_numeros = [] #contador = 0 #maior_valor = 0 #menor_valor = 0 novo_valor = True while novo_valor: numero = int(input('Qual o valor? ')) lista_numeros.append(numero) flag = input('Continua (y/n)? ') if flag != 'y': novo_valor = False # for index_numero in lista_numeros: # if index_numero == lista_numeros[0]: # maior_valor = index_numero # menor_valor = index_numero # else: # if maior_valor < index_numero: # maior_valor = index_numero # if menor_valor > index_numero: # menor_valor = index_numero print(lista_numeros) print('O maior valor รฉ: ', max(lista_numeros)) #mรฉtodos max e min print('O menor valor รฉ: ', min(lista_numeros))
r"""Generate a bunch of empty demofiles with date in filename, random extension. >>> python filenameWithDate 50 t a = filesWithDateName(howMany=50, pad=True, format_='American') => will create <50> random empty files with <padded American format date> in filename. Nguyen Thanh Hung - hungnt89@gmail.com hungntgrb""" from random import choice, randint import sys def randomMonth(pad=False): """Generate a random month either with padding or not.""" rm = randint(1, 12) if pad: return f"{rm:0>2}" else: return f"{rm}" def randomMonthBetween(m1=1, m2=12, pad=False): """Generate a random month in a range either with padding or not.""" rm = randint(m1, m2) if pad: return f"{rm:0>2}" else: return f"{rm}" def randomDay(pad=False): """Generate a random day either with padding or not.""" rd = randint(1, 31) if pad: return f"{rd:0>2}" else: return f"{rd}" def randomDayBetween(d1=1, d2=31, pad=False): """Generate a random day in a range either with padding or not.""" rd = randint(d1, d2) if pad: return f"{rd:0>2}" else: return f"{rd}" def randomYear(): """Generate a random year between 1900 and 2020.""" ry = randint(1900, 2020) return f"{ry}" def randomSeparator(): """A random separator either . - _""" rs = choice(('.', '-', '_')) return rs def randomExtension(): """Choose a random extension.""" re = choice(('txt','csv','json','html','css','js','py','mp3','mp4','docx','xlsx','pptx','yaml','png')) return re def randomAmericanDate(pad=False): """Generate a random American format date MM-DD-YYYY either with padding or not.""" rs = randomSeparator() rm = randomMonth(pad) rd = randomDay(pad) ry = randomYear() ad = f"{rm}{rs}{rd}{rs}{ry}" return ad def randomEuropeanDate(pad=False): """Generate a random European format date DD-MM-YYYY either with padding or not.""" rs = randomSeparator() rm = randomMonth(pad) rd = randomDay(pad) ry = randomYear() ed = f"{rd}{rs}{rm}{rs}{ry}" return ed def randomFilenameWithDate(pad=False, format_='European'): """Generate a random filename with either padded or non-padded 'American' or 'European' format date.""" if format_ == 'European': rD = randomEuropeanDate(pad) elif format_ == 'American': rD = randomAmericanDate(pad) rs = randomSeparator() fnwoe = choice((f"{rD}{rs}demoFile", f"demo{rs}{rD}{rs}File", f"demoFile{rs}{rD}")) re = randomExtension() fn = f"{fnwoe}.{re}" return fn def filesWithDateName(howMany=10, pad=True, format_='European'): """Generate n files <demoFile.ext> with date in filename.""" for i in range(howMany): fn = randomFilenameWithDate(pad, format_) with open(fn, 'wb') as f: print(f"Creating {fn}...") print('Done.') if __name__ == "__main__": a1 = int(sys.argv[1]) d2 = {'t': True, 'f': False} a2 = d2.get(sys.argv[2]) d3 = {'a': 'American', 'e': 'European'} a3 = d3.get(sys.argv[3]) filesWithDateName(howMany=a1, pad=a2, format_=a3)
# Simple tetris program! v0.2 # D. Crandall, Sept 2016 ''' For this problem we have implemented an AI for winning the Tetris game. The main idea behind this code is as follows: - for a given piece, create a search tree with all the possible boards considering all the possible locations and rotations for that piece. The successor function returns the new board, the goodness score of that board and the final location of the piece. - For each new board created in the successor function, we expand it again considereing the next piece (tetris.get_next_piece()). The final position of the current piece (given by tetris.get_piece()) is determined by the new board with max goodness score at this point. In this sense, we are evaluating the final position of the current piece conisdering as well the information of the next piece. - After we extracted the final destination, the piece is placed following the simple and animated version. - The goodness score is determined by various factors on the board such as the number of complete lines, the number of holes, the bumpiness, and the number of complete lines. This gives us an idea of how good is the current board. Note: We have also created a distribution table for the incoming pieces in order to learn that and try to estimate the move based on the incoming piece we believe will come. This incoming piece is determined based on the distribution table from which we extrac the piece with the highest probability. With this set, we expand the tree from the previous states and get the new score and final best move. This implementation had to be removed from the code since it takes a lot of time and he animated version is not able to run properly because of this. ''' from AnimatedTetris import * from SimpleTetris import * from kbinput import * import time, sys from random import randint import operator class HumanPlayer: def get_moves(self, tetris): print "Type a sequence of moves using: \n b for move left \n m for move right \n n for rotation\nThen press enter. E.g.: bbbnn\n" moves = raw_input() return moves def control_game(self, tetris): while 1: c = get_char_keyboard() commands = {"b": tetris.left, "n": tetris.rotate, "m": tetris.right, " ": tetris.down} commands[c]() ##### # This is the part you'll want to modify! # Replace our super simple algorithm with something better # class ComputerPlayer: all_rotations = {} piece_distribution = {} num_of_pieces = 0 def __init__(self): self.build_rotation_dic() self.build_piece_dist_dic() # This function should generate a series of commands to move the piece into the "optimal" # position. The commands are a string of letters, where b and m represent left and right, respectively, # and n rotates. tetris is an object that lets you inspect the board, e.g.: # - tetris.col, tetris.row have the current column and row of the upper-left corner of the # falling piece # - tetris.get_piece() is the current piece, tetris.get_next_piece() is the next piece after that # - tetris.left(), tetris.right(), tetris.down(), and tetris.rotate() can be called to actually # issue game commands # - tetris.get_board() returns the current state of the board, as a list of strings. # def get_moves(self, tetris): self.num_of_pieces += 1 piece = tetris.get_piece()[0] # updating distribution table # self.piece_distribution[tuple(piece)][0] += 1 # for key, value in self.piece_distribution.iteritems(): # value[1] = float(value[0]) / self.num_of_pieces board = tetris.get_board() piece = tetris.get_piece() next_piece = tetris.get_next_piece() succ_good = successors(tetris, board, piece[0]) # possible_next_piece = max(self.piece_distribution.iteritems(), key=operator.itemgetter(1))[0] final_succ = [] for b in succ_good: aux_succ = successors(tetris, b[-1], next_piece) for succ in aux_succ: succ = succ + [b[1], b[2]] final_succ += [succ] scores = [x[0] for x in final_succ] best_board_idx = scores.index(max(scores)) # getting the final col given by the move with highest goodness score final_col = final_succ[best_board_idx][-2] # getting the rotation id given by the move with highest goodness score rot_idx = final_succ[best_board_idx][-1] piece, piece_row, piece_col = tetris.get_piece() return self.get_cmd(piece_col, final_col, rot_idx) # This is the version that's used by the animted version. This is really similar to get_moves, # except that it runs as a separate thread and you should access various methods and data in # the "tetris" object to control the movement. In particular: # - tetris.col, tetris.row have the current column and row of the upper-left corner of the # falling piece # - tetris.get_piece() is the current piece, tetris.get_next_piece() is the next piece after that # - tetris.left(), tetris.right(), tetris.down(), and tetris.rotate() can be called to actually # issue game commands # - tetris.get_board() returns the current state of the board, as a list of strings. # def control_game(self, tetris): while 1: time.sleep(0.1) self.num_of_pieces += 1 piece = tetris.get_piece()[0] # self.piece_distribution[tuple(piece)][0] += 1 # self.piece_distribution[tuple(piece)][1] = float(self.piece_distribution[tuple(piece)][0]) / self.num_of_pieces board = tetris.get_board() piece = tetris.get_piece() next_piece = tetris.get_next_piece() succ_good = successors(tetris, board, piece[0]) final_succ = [] for b in succ_good: aux_succ = successors(tetris, b[-1], next_piece) # positions += [b[1], b[2]] for succ in aux_succ: succ = succ + [b[1], b[2]] final_succ += [succ] scores = [x[0] for x in final_succ] best_board_idx = scores.index(max(scores)) # getting the final col given by the move with highest goodness score final_col = final_succ[best_board_idx][-2] # getting the rotation id given by the move with highest goodness score rot_idx = final_succ[best_board_idx][-1] for idx in xrange(0, rot_idx): tetris.rotate() if (final_col < tetris.col): tetris.left() elif (final_col > tetris.col): tetris.right() else: tetris.down() # This function builds a static dictionary of pieces and its rotations # def build_rotation_dic(self): self.all_rotations[tuple(["xx", "xx"])] = [] self.all_rotations[tuple(["x", "x", "x", "x"])] = [] self.all_rotations[tuple(["x", "x", "x", "x"])].append(["xxxx"]) self.all_rotations[tuple(["xxxx"])] = [] self.all_rotations[tuple(["xxxx"])].append(["x", "x", "x", "x"]) self.all_rotations[tuple(["xx ", " xx"])] = [] self.all_rotations[tuple(["xx ", " xx"])].append([" x", "xx", "x "]) self.all_rotations[tuple([" x", "xx", "x "])] = [] self.all_rotations[tuple([" x", "xx", "x "])].append(["xx ", " xx"]) self.all_rotations[tuple(["xxx", " x"])] = [] self.all_rotations[tuple(["xxx", " x"])].append([" x", " x", "xx"]) self.all_rotations[tuple(["xxx", " x"])].append(["x ", "xxx"]) self.all_rotations[tuple(["xxx", " x"])].append(["xx", "x ", "x "]) self.all_rotations[tuple([" x", " x", "xx"])] = [] self.all_rotations[tuple([" x", " x", "xx"])].append(["x ", "xxx"]) self.all_rotations[tuple([" x", " x", "xx"])].append(["xx", "x ", "x "]) self.all_rotations[tuple([" x", " x", "xx"])].append(["xxx", " x"]) self.all_rotations[tuple(["x ", "xxx"])] = [] self.all_rotations[tuple(["x ", "xxx"])].append(["xx", "x ", "x "]) self.all_rotations[tuple(["x ", "xxx"])].append(["xxx", " x"]) self.all_rotations[tuple(["x ", "xxx"])].append([" x", " x", "xx"]) self.all_rotations[tuple(["xx", "x ", "x "])] = [] self.all_rotations[tuple(["xx", "x ", "x "])].append(["xxx", " x"]) self.all_rotations[tuple(["xx", "x ", "x "])].append([" x", " x", "xx"]) self.all_rotations[tuple(["xx", "x ", "x "])].append(["x ", "xxx"]) self.all_rotations[tuple(["xxx", " x "])] = [] self.all_rotations[tuple(["xxx", " x "])].append([" x", "xx", " x"]) self.all_rotations[tuple(["xxx", " x "])].append([" x ", "xxx"]) self.all_rotations[tuple(["xxx", " x "])].append(["x ", "xx", "x "]) self.all_rotations[tuple([" x", "xx", " x"])] = [] # T self.all_rotations[tuple([" x", "xx", " x"])].append([" x ", "xxx"]) self.all_rotations[tuple([" x", "xx", " x"])].append(["x ", "xx", "x "]) self.all_rotations[tuple([" x", "xx", " x"])].append(["xxx", " x "]) self.all_rotations[tuple([" x ", "xxx"])] = [] self.all_rotations[tuple([" x ", "xxx"])].append(["x ", "xx", "x "]) self.all_rotations[tuple([" x ", "xxx"])].append(["xxx", " x "]) self.all_rotations[tuple([" x ", "xxx"])].append([" x", "xx", " x"]) self.all_rotations[tuple(["x ", "xx", "x "])] = [] self.all_rotations[tuple(["x ", "xx", "x "])].append(["xxx", " x "]) self.all_rotations[tuple(["x ", "xx", "x "])].append([" x", "xx", " x"]) self.all_rotations[tuple(["x ", "xx", "x "])].append([" x ", "xxx"]) def build_piece_dist_dic(self): self.piece_distribution[tuple(["xx", "xx"])] = [0, 0] self.piece_distribution[tuple(["x", "x", "x", "x"])] = [0, 0] self.piece_distribution[tuple(["xxxx"])] = [0, 0] self.piece_distribution[tuple(["xx ", " xx"])] = [0, 0] self.piece_distribution[tuple([" x", "xx", "x "])] = [0, 0] self.piece_distribution[tuple(["xxx", " x"])] = [0, 0] self.piece_distribution[tuple([" x", " x", "xx"])] = [0, 0] self.piece_distribution[tuple(["x ", "xxx"])] = [0, 0] self.piece_distribution[tuple(["xx", "x ", "x "])] = [0, 0] self.piece_distribution[tuple(["xxx", " x "])] = [0, 0] self.piece_distribution[tuple([" x", "xx", " x"])] = [0, 0] self.piece_distribution[tuple([" x ", "xxx"])] = [0, 0] self.piece_distribution[tuple(["x ", "xx", "x "])] = [0, 0] # This function returns a string with the commands needed to perform the best move possible given by our algorithm # def get_cmd(self, piece_col, final_col, rot_idx): rot = "n" * rot_idx disp = '' if piece_col > final_col: disp = "b" * abs(piece_col - final_col) if piece_col < final_col: disp = "m" * abs(piece_col - final_col) commands = rot + disp return commands # This function rotates the tetris piece # It returns a list of the piece followed by its possible rotations given by the rotation dictionary # def rotations(tetris, piece): rotation = list(ComputerPlayer.all_rotations[tuple(piece)]) rotation.insert(0, piece) return rotation # This function generates successors for the given tetris piece. # - Given a piece and a board state, it generates all the possible boards and it calculates its goodness score based # on a heuristic function # def successors(tetris, board, piece): succ = [] ele = 'x' rot_idx = 0 base_row = len(board) for rotated_piece in rotations(tetris, piece): for all_locations in xrange(0, TetrisGame.BOARD_WIDTH - len(rotated_piece[0]) + 1): col = zip(*board)[all_locations] # returns a tuple for the specified 'all_locations' column row_to_put = col.index(ele) if ele in col else base_row if not TetrisGame.check_collision((board, 0), rotated_piece, row_to_put - len(rotated_piece), all_locations): succ_board, score = TetrisGame.place_piece((board, 0), rotated_piece, row_to_put - len(rotated_piece), all_locations) succ_heu = goodness(succ_board) succ.append([succ_heu, all_locations, rot_idx, succ_board]) rot_idx += 1 return succ # This function returns the goodness function for a given board. This goodness function consists of a linear combination of: # - number of aggregated heights: sum of height of each column. We try to minimize this value # - number of complete lines. This is a value we want to maximize # - number of holes in the given board. We try to minimize this value # - variation of board's column heights. We try to minimize this value as we want the board to be as monotone as possible # # Each of these values are weighted by a experimental factors which were determined following this blog: # https://codemyroad.wordpress.com/2013/04/14/tetris-ai-the-near-perfect-player/ but then modified based on our experiments # def goodness(board): agg = get_aggregate_height(board) lines = get_complete_lines(board) holes = get_holes_count(board) bumpiness = get_bumpiness_value(board) max_height = get_max_height(board) min_height = get_min_height(board) return float(agg) * -0.610066 \ + float(lines) * 0.760666 \ + float(holes) * -0.45663 \ + float(bumpiness) * -0.184483 def get_aggregate_height(board): ele = 'x' base_height = 0 column_height = 0 row = 0 for col in xrange(0, TetrisGame.BOARD_WIDTH): column = zip(*board)[col] column_height += TetrisGame.BOARD_HEIGHT - column.index(ele) if ele in column else base_height return column_height def get_max_height(board): ele = 'x' base_height = 0 column_height = [] row = 0 for col in xrange(0, TetrisGame.BOARD_WIDTH): column = zip(*board)[col] column_height.append(TetrisGame.BOARD_HEIGHT - column.index(ele) if ele in column else base_height) return max(column_height) def get_min_height(board): column_heights = [ min([ r for r in range(len(board)-1, 0, -1) if board[r][c] == "x" ] + [100,] ) for c in range(0, len(board[0]) ) ] index = column_heights.index(max(column_heights)) return index def get_bumpiness_value(board): ele = 'x' base_height = TetrisGame.BOARD_HEIGHT bumpiness = 0 for cols in xrange(0, TetrisGame.BOARD_WIDTH - 1): column1 = zip(*board)[cols] column2 = zip(*board)[cols + 1] column1_height = column1.index(ele) if ele in column1 else base_height column2_height = column2.index(ele) if ele in column2 else base_height bumpiness += abs(column1_height - column2_height) return bumpiness def get_holes_count(board): ele = 'x' base_height = TetrisGame.BOARD_HEIGHT holes_count = 0 for cols in xrange(0, TetrisGame.BOARD_WIDTH): column = zip(*board)[cols] holes_count += column[column.index(ele) if ele in column else base_height:base_height].count(' ') return holes_count def get_complete_lines(board): complete = [i for (i, s) in enumerate(board) if s.count(' ') == 0] return len(complete) ################### main program (player_opt, interface_opt) = sys.argv[1:3] try: if player_opt == "human": player = HumanPlayer() elif player_opt == "computer": player = ComputerPlayer() else: print "unknown player!" if interface_opt == "simple": tetris = SimpleTetris() elif interface_opt == "animated": tetris = AnimatedTetris() else: print "unknown interface!" tetris.start_game(player) except EndOfGame as s: print "\n\n\n", s
numero = int(input("Ingrese el nรบmero a calcular el factorial: ")) factorial = 1 while numero != 0: factorial*=numero numero-=1 print(factorial)
lista1 = [1,2,3,4,5,6,11] #Lista 1 en cuestiรณn lista2= [4,5,6,7,8,9,11,13,14] #Lista 2 en cuestiรณn listaIguales = list() #Creamos lista para almacenar datos iguales listaDistintos = list() #Creamos lista para almacenar datos distintos for i in lista1: #Entramos a lista1 para comenzar a comparar datos for j in lista2: #Entramos a lista2 para comenzar a comparar datos if i not in lista2: #Si el dato comparado desde lista1 no estรก en lista2 if i not in listaDistintos: #Si el dato comparado desde lista1 no estรก dentro de lista distintos listaDistintos.append(i) #Se agrega el valor a lista distintos else: if i not in listaIguales: #Hacemos este paso para que no se repitan los datos dentro de la lista al estar en un ciclo listaIguales.append(i) for i in lista2: #En este caso hacemos la comparaciรณn desde los elementos de la lista2 sobre la lista1 for j in lista1: if i not in lista1: if i not in listaDistintos: listaDistintos.append(i) #Aquรญ nos saltamos el else del ciclo anterior debido a que ya se almacenaron los datos iguales en ambas listas print("Elementos en ambas listas: ", listaIguales) print("Elementos diferentes en listas: ", listaDistintos)
from itertools import permutations import sys import time in_word = sys.argv[1] already_seen = [] #already seen is already found de jumbled word if len(sys.argv) > 2: already_seen = sys.argv[2:] #read from english word dictionary eng_dict = open("english3.txt", "r").read().split("\n") #generator for english word dictionary eng_dict_gen = (x for x in eng_dict) #finding all permutations of input word p = permutations(in_word) found = False perm_arr = [] for tup in list(p): perm_arr.append(''.join(tup).lower()) #sorting parmutations and removing duplicates perm_arr.sort() perm_arr = list(dict.fromkeys(perm_arr)) count = 0 t1 = time.time() while(count < len(eng_dict)): if found == False: w = str(next(eng_dict_gen)) for word in perm_arr: if word == w and word not in already_seen: found = True print(w) break count = count+1 else: break if found == False: print("sorry..not found") t2 = time.time() print(f"Time Elapsed: {t2-t1} seconds")
from tkinter import * import tkinter as tk from tkinter import filedialog from PIL import Image, ImageDraw, ImageFont, ImageTk BACKGROUND_COLOR = "#F7F7FF" BUTTON_COLOR = "#279AF1" EXIT_COLOR = "#C14953" def exit_program(): window.destroy() def watermark_text(): filename = filedialog.askopenfilename(initialdir='/Desktop', title='Select an Image: ', filetypes=(("JPG File", "*.jpg"), ("PNG file", "*.png"), ("All Files", "*.*"))) img = Image.open(filename) width, height = img.size draw = ImageDraw.Draw(img) text = "Sample Text Watermark" font = ImageFont.truetype('arial.ttf', 42) text_width, text_height = draw.textsize(text, font) # calculate the x,y coordinates of the text margin = 100 x = width - text_width - margin y = height - text_height - margin # draw watermark in the bottom right corner draw.text((x, y), text, font=font) # Save watermarked image img.save('watermark.jpg') # Show img in gui img = Image.open("watermark.jpg") img.thumbnail((450, 450)) img = ImageTk.PhotoImage(img) lbl.configure(image=img) lbl.image = img def watermark_image(): filename = filedialog.askopenfilename(initialdir='/Desktop', title='Select an Image: ', filetypes=(("JPG File", "*.jpg"), ("PNG file", "*.png"), ("All Files", "*.*"))) base_image = Image.open(filename) watermark = Image.open("water_logo.png") base_image.paste(watermark, (100, 100), mask=watermark) base_image.save("watermark.jpg") img = Image.open("watermark.jpg") img.thumbnail((450, 450)) img = ImageTk.PhotoImage(img) lbl.configure(image=img) lbl.image = img def result(): filename = filedialog.askopenfilename(initialdir='/Desktop', title='Select an Image: ', filetypes=(("JPG File", "*.jpg"), ("PNG file", "*.png"), ("All Files", "*.*"))) img = Image.open(filename) img.thumbnail((450, 450)) img = ImageTk.PhotoImage(img) lbl.configure(image=img) lbl.image = img window = Tk() window.title("Watermark App") window.config(padx=50, pady=50, bg=BACKGROUND_COLOR) canvas = Canvas(window, width=700, height=600, bg=BACKGROUND_COLOR, highlightthickness=0) canvas.grid(columnspan=3, rowspan=3) logo = Image.open("logo.png") logo = logo.resize((400, 400)) logo = ImageTk.PhotoImage(logo) logo_label = tk.Label(image=logo, bd=0) logo_label.image = logo logo_label.grid(column=1, row=1) lbl = Label(window) lbl.grid(column=1, row=1) text_btn = Button(window, text="Mark Text", font=('verdana', 10), width=10, height=1, bg=BUTTON_COLOR, fg='white', command=watermark_text) text_btn.grid(column=0, row=3) image_btn = Button(window, text="Mark Image", font=('verdana', 10), width=10, height=1, bg=BUTTON_COLOR, fg='white', command=watermark_image) image_btn.grid(column=1, row=2) result_btn = Button(window, text="Show image", font=('verdana', 10), width=10, height=1, bg=BUTTON_COLOR, fg='white', command=result) result_btn.grid(column=1, row=0) quit_btn = Button(window, text="Exit", font=('verdana', 10), width=10, height=1, bg=EXIT_COLOR, fg="white", command=exit_program) quit_btn.grid(column=2, row=3) window.mainloop()
# # Mazecraft: 2D and 3D Maze Generation for Minecraft # # (c) 2011 Lee Supe (lain_proliant) # Released for the GNU General Public License # import random def pathFlagsFromDiffCoords (diffCoords): """ Computes forward and backward path flags for the given difference between coordinates. """ pathFlags = 0 invFlags = 0 for R, n in enumerate (diffCoords): if n > 0: pathFlags |= (2 ** (2 * R)) invFlags |= (2 ** (2 * R + 1)) elif n < 0: pathFlags |= (2 ** (2 * R + 1)) invFlags |= (2 ** (2 * R)) return pathFlags, invFlags class Cell (object): def __init__ (self, maze, coords): self.maze = maze self.coords = coords self.paths = 0 self.visited = False def adjacent (self): """ Returns a list of all adjacent cells. """ cells = [] for R, coord in enumerate (self.coords): if coord + 1 < self.maze.dimensions [R]: adjCoords = list (self.coords) adjCoords [R] = coord + 1 cells.append (self.maze.cellAt (adjCoords)) if coord - 1 >= 0: adjCoords = list (self.coords) adjCoords [R] = coord - 1 cells.append (self.maze.cellAt (adjCoords)) return cells def adjacentUnvisited (self): """ Returns a list of all adjacent, unvisited cells. """ return [c for c in self.adjacent () if not c.visited] def diffCoords (self, cell): """ Computes the component difference between this cell and the specified cell. """ return [b - a for a, b in zip (self.coords, cell.coords)] def carveTo (self, destCell): """ Adds paths to this cell and the destination to allow for passage. """ diffCoords = self.diffCoords (destCell) pathFlags, invFlags = pathFlagsFromDiffCoords (diffCoords) self.paths |= pathFlags destCell.paths |= invFlags def __repr__ (self): return '<Cell %s %s>' % (str (self.coords), bin (self.paths)) class Maze (list): def __init__ (self, dimensions, ancestor = None, subdimension = ()): self.dimensions = dimensions for n in range (dimensions [0]): if ancestor is not None: maze = ancestor else: maze = self if len (dimensions) > 1: self.append (Maze (dimensions [1:], maze, subdimension + (n,))) else: self.append (Cell (maze, subdimension + (n,))) def cellAt (self, coords): """ Retrieves the cell at the given coordinates. """ if len (self.dimensions) > 1: return self [coords [0]].cellAt (coords [1:]) else: return self [coords [0]] def randomCell (self): """ Returns a random cell from the maze. """ return self.cellAt ([random.randint (0, n - 1) for n in self.dimensions]) def chaoticPath (self): """ Carves a random chaotic path from 0,0 center until reaching a dead end. """ cell = self.cellAt ([0 for x in self.dimensions]) while cell.adjacentUnvisited (): nextCell = random.choice (cell.adjacentUnvisited ()) cell.carveTo (nextCell) cell = nextCell cell.visited = True def growingTree (self, probabilityNew = 1.0): """ Carves a maze using the growing tree algorithm with the specified parameters. """ cell = self.randomCell () cell.visited = True stack = [cell] while stack: if random.random () > probabilityNew: cell = random.choice (stack) else: cell = stack [-1] adjacentCells = cell.adjacentUnvisited () if not adjacentCells: stack.remove (cell) continue destCell = random.choice (adjacentCells) destCell.visited = True cell.carveTo (destCell) stack.append (destCell) def print2D (self): """ Prints the maze as text. It must be in two dimensions. """ if not len (self.dimensions) == 2: raise Exception, "Maze is not two-dimensional." # Print the top line. line = ' ' for x in range (self.dimensions [0]): cell = self.cellAt ((x, 0)) if cell.paths & (2 ** (2 + 1)): line += ' ' else: line += '_ ' print line for y in range (self.dimensions [1]): line = '' for x in range (self.dimensions [0]): cell = self.cellAt ((x, y)) if cell.paths & (2 ** (0 + 1)): line += ' ' else: line += '|' if y == self.dimensions [1] - 1: if cell.paths & (2 ** 2): line += ' ' else: line += '_' else: below = self.cellAt ((x, y + 1)) if below.paths & 2 ** (2 + 1): line += ' ' else: line += '_' if x == self.dimensions [0] - 1: if cell.paths & (2 ** 0): line += ' ' else: line += '|' print line line = ' '
def main(): def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 if __name__ == '__main__': main() print("this part isn't meant to show")
#!/usr/bin/python import unittest def near_one_or_two_hundred(number_to_check): """ Given an int number_to_check, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number. """ pass class TestNear(unittest.TestCase): def test_89(self): self.assertFalse(near_one_or_two_hundred(89)) def test_90(self): self.assertTrue(near_one_or_two_hundred(90)) def test_110(self): self.assertTrue(near_one_or_two_hundred(110)) def test_111(self): self.assertFalse(near_one_or_two_hundred(111)) def test_189(self): self.assertFalse(near_one_or_two_hundred(189)) def test_190(self): self.assertTrue(near_one_or_two_hundred(190)) def test_210(self): self.assertTrue(near_one_or_two_hundred(210)) def test_211(self): self.assertFalse(near_one_or_two_hundred(211)) if __name__ == '__main__': unittest.main()
import pygame import random import math """ ScreenSaver with following features: 1. multi polylines, configure each separately (selected polyline is marked by yellow points, others - white points) 2. add a new polyline. support two classes: Polyline(pure base)/Knot 3. different polylines can have a different classes at the same time 4. delete polyline (currently selected). there should be at least one. 5. adjust speed (can be stopped for speed=0), knot points per each polyline separately 6. navigate/switch by Prev/Next actions 7. remove polyline point by mouse click (switch mouse click mode=add/delete) """ """ Classes structure: class Vec2d() - vector processing class Polyline() - base polyline class, draw in a given surface screen, standalone work class Knot(Polyline) - advanced polyline with knots class ScreenSaverHelp() - UI help processing, draw in a given surface screen class ScreenSaver() - main program to execute """ class Vec2d(): """2d zero-based vector""" def __init__(self, p): """Initialize from point (x, y)""" self.x, self.y = p def __add__(self, other): """Vectors addition""" return Vec2d((self.x + other.x, self.y + other.y)) def __sub__(self, other): """Vectors subtraction""" return Vec2d((self.x - other.x, self.y - other.y)) def __mul__(self, alpha): """Scalar multiplication""" return Vec2d((self.x * alpha, self.y * alpha)) def __len__(self): """Vector length""" return int(math.sqrt(self.x**2 + self.y**2)) def int_pair(self): """As an integer pair tuple (int, int)""" return (int(self.x), int(self.y)) class Polyline(): """Base polyline""" def __init__(self, surface_screen, steps=1, speed_factor=1): self.surface = surface_screen self.surface_sz = Vec2d(surface_screen.get_size()) self.points = [] self.polyline_points = None self.is_draw_polyline = True self.polyline_steps = steps self.speeds = [] self.speed_factor = speed_factor # 0-stop, >1 - accelerate self.width = 3 self.points_color = (255, 255, 255) self.lines_color = pygame.Color(0) def update_steps(self, delta): """Safety update polylines steps""" self.polyline_steps += delta if self.polyline_steps < 1: self.polyline_steps = 1 def update_speed_factor(self, delta): """Safety update speed factor""" self.speed_factor += delta if self.speed_factor < 0: self.speed_factor = 0 def reset(self): """Clear all points""" self.points = [] self.speeds = [] def add_point(self, v, s): """Add a new point""" self.points.append(Vec2d(v)) self.speeds.append(Vec2d(s)) def set_points(self, move=True): """Recalculate points""" for p in range(len(self.points)): if move: self.points[p] += self.speeds[p] * self.speed_factor if self.points[p].x > self.surface_sz.x or self.points[p].x < 0: self.speeds[p].x = -self.speeds[p].x if self.points[p].y > self.surface_sz.y or self.points[p].y < 0: self.speeds[p].y = -self.speeds[p].y def draw_points(self, line_width=None, line_color=None): """Draw points and polyline""" self.draw_points_only() self.draw_polyline_only(line_width, line_color) def draw_points_only(self): """Draw points""" for p in self.points: pygame.draw.circle( self.surface, self.points_color, p.int_pair(), self.width) def draw_polyline_only(self, width=None, color=None): """Draw polyline""" if not self.is_draw_polyline: return points = self.polyline_points or self.points width = width or self.width color = color or self.lines_color for p_n in range(-1, len(points) - 1): pygame.draw.line( self.surface, color, points[p_n].int_pair(), points[p_n + 1].int_pair(), width) class Knot(Polyline): """Knot-points for the Polyline""" def set_points(self, move=True): """Override Polyline.set_points()""" super().set_points(move) self.get_knot() def get_knot(self): """Recalculate polyline points""" self.polyline_points = [] self.is_draw_polyline = len(self.points) >= 3 if not self.is_draw_polyline: return for i in range(-2, len(self.points) - 2): ptn = [] ptn.append((self.points[i] + self.points[i + 1]) * 0.5) ptn.append(self.points[i + 1]) ptn.append((self.points[i + 1] + self.points[i + 2]) * 0.5) self.polyline_points.extend( self.__get_points(ptn, self.polyline_steps)) def __get_points(self, points, count): alpha = 1 / count res = [] for i in range(count): res.append(self.__get_point(points, i * alpha)) return res def __get_point(self, points, alpha, deg=None): if deg is None: deg = len(points) - 1 if deg == 0: return points[0] return points[deg] * alpha + \ self.__get_point(points, alpha, deg - 1) * (1 - alpha) class ScreenSaverHelp(): """Help screen for Polyline""" def __init__(self, screen_surface, polylines): self.surface = screen_surface self.polylines = polylines self.selected = 0 self.mouse_mode_deletion = False def draw(self): self.surface.fill((50, 50, 50)) font1 = pygame.font.SysFont("courier", 24) font2 = pygame.font.SysFont("serif", 24) data = [] data.append(["F1", "Show Help"]) data.append(["R", "Restart"]) data.append(["P", "Pause/Play"]) mouse_mode_str = 'delete' if self.mouse_mode_deletion else 'add' data.append(["C", f"Change mouse click mode (current={mouse_mode_str})"]) data.append(["A", "Add new polyline (class Polyline)"]) data.append(["S", "Add new polyline (class Knot)"]) data.append(["D", "Delete currently selected polyline"]) data.append(["N", "Select next polyline"]) data.append(["B", "Select previous polyline"]) data.append(["Num+", "More points"]) data.append(["Num-", "Less points"]) data.append(["X", "Faster"]) data.append(["Z", "Slower"]) data.append(["", ""]) data.append( [f'{str(self.selected + 1)}/{len(self.polylines)}', "Currently selected polyline (yellow points)"]) data.append( [f'{self.polylines[self.selected].__class__.__name__}', "Selected polyline's class"]) data.append( [str(self.polylines[self.selected].polyline_steps), "Selected polyline's points"]) data.append( [str(self.polylines[self.selected].speed_factor), "Selected polyline's speed factor (0=stop)"]) pygame.draw.lines(self.surface, (255, 50, 50, 255), True, [ (0, 0), (800, 0), (800, 600), (0, 600)], 5) for i, text in enumerate(data): self.surface.blit(font1.render( text[0], True, (128, 128, 255)), (100, 30 + 30 * i)) self.surface.blit(font2.render( text[1], True, (128, 128, 255)), (220, 30 + 30 * i)) class ScreenSaver(): """ScreenSaver""" def __init__(self, screen_dim=(800, 600), polyline_steps_default=5, speed_factor_default=1): pygame.init() self.surface = pygame.display.set_mode(screen_dim) pygame.display.set_caption("Anton Senyuta Screen Saver") self.polyline_steps_default = polyline_steps_default self.speed_factor_default = speed_factor_default self.polylines = [] self.selected = -1 self.points_color = (255, 255, 255) self.selected_points_color = (255, 255, 0) self.show_help = False self.help = ScreenSaverHelp(self.surface, self.polylines) self.pause = True self.mouse_precision = 10 self.mouse_mode_deletion = False self.reset() def __del__(self): pygame.display.quit() pygame.quit() def add_polyline(self, class_, steps=None, speed_factor=None): steps = steps or self.polyline_steps_default speed_factor = speed_factor or self.speed_factor_default self.polylines.append(class_(self.surface, steps, speed_factor)) self.selected = len(self.polylines) - 1 self.polylines[self.selected].set_points() def run_till_exit(self): while True: if not self.__process_events(): break self.__draw() if not self.pause: self.__set_points() if self.show_help: self.help.selected = self.selected self.help.mouse_mode_deletion = self.mouse_mode_deletion self.help.draw() pygame.display.flip() def __draw(self): self.surface.fill((0, 0, 0)) self.__draw_polylines() def __draw_polylines(self): if not len(self.polylines): return for i, p in enumerate(self.polylines): p.lines_color = self.__recalculate_line_color(p.lines_color) p.points_color = self.selected_points_color \ if i == self.selected else self.points_color p.draw_points() def __recalculate_line_color(self, color): hue = (color.hsla[0] + 1) % 360 color.hsla = (hue, 100, 50, 100) return color def __set_points(self): for p in self.polylines: p.set_points() def __process_events(self): force_setpoints = False for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return False if event.key == pygame.K_r: self.reset() if event.key == pygame.K_p: self.pause = not self.pause if event.key == pygame.K_c: self.mouse_mode_deletion = not self.mouse_mode_deletion if event.key == pygame.K_a: self.add_polyline(Polyline) if event.key == pygame.K_s: self.add_polyline(Knot) if event.key == pygame.K_d: if len(self.polylines) > 1: self.polylines.pop(self.selected) self.selected -= 1 \ if self.selected >= len(self.polylines) else 0 if event.key == pygame.K_KP_PLUS: self.polylines[self.selected].update_steps(1) force_setpoints = True if event.key == pygame.K_KP_MINUS: self.polylines[self.selected].update_steps(-1) force_setpoints = True if event.key == pygame.K_z: self.polylines[self.selected].update_speed_factor(-0.25) if event.key == pygame.K_x: self.polylines[self.selected].update_speed_factor(0.25) if event.key == pygame.K_b: self.selected -= 1 if self.selected > 0 else 0 if event.key == pygame.K_n: self.selected += 1 \ if self.selected < len(self.polylines) - 1 else 0 if event.key == pygame.K_F1: self.show_help = not self.show_help if event.type == pygame.MOUSEBUTTONDOWN: if self.mouse_mode_deletion: self.remove_point(event.pos) else: self.polylines[self.selected].add_point( event.pos, (random.random() * 2, random.random() * 2)) force_setpoints = True if force_setpoints and self.pause: self.polylines[self.selected].set_points(False) return True def remove_point(self, mouse_p): """Collect all candidate points by mouse precision and remove the nearest one""" mouse_p = Vec2d(mouse_p) candidates = [] for poly_i, poly in enumerate(self.polylines): for p_i, p in enumerate(poly.points): if len(mouse_p - p) <= self.mouse_precision: candidates.append((len(mouse_p - p), poly_i, p_i)) if len(candidates) > 0: poly_i, p_i = sorted(candidates)[0][1:3] self.polylines[poly_i].points.pop(p_i) if self.pause: self.__set_points() def reset(self): self.polylines.clear() self.add_polyline(Knot) if __name__ == "__main__": screen_saver = ScreenSaver() screen_saver.run_till_exit() exit(0)
def fib(n): a,b=1,1 for i in range (n-1): a,b = b,a+b return a print fib(10)
# ๅฎž็Žฐไธ€ไธช @timer ่ฃ…้ฅฐๅ™จ๏ผŒ่ฎฐๅฝ•ๅ‡ฝๆ•ฐ็š„่ฟ่กŒๆ—ถ้—ด๏ผŒ # ๆณจๆ„้œ€่ฆ่€ƒ่™‘ๅ‡ฝๆ•ฐๅฏ่ƒฝไผšๆŽฅๆ”ถไธๅฎš้•ฟๅ‚ๆ•ฐใ€‚ import time from functools import wraps def timer(func): @wraps(func) def decorated(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() running_time = end - start print(f"{func.__name__} running_time: {running_time}") return res return decorated @timer def sleep1(n): print(f'sleep1 start') time.sleep(n) print(f'sleep1 end') @timer def sleep2(*args, **kwargs): print(f'sleep2 start') print(f"args: {args}") print(f'kwargs: {kwargs}') time.sleep(len(args) + len(kwargs)) print(f'sleep2 end') if __name__ == "__main__": sleep1(1) sleep2(1, 2, age=20)
#!/bin/python3 import math import os import random import re import sys # Complete the jumpingOnClouds function below. def jumpingOnClouds(c): jump=0 a=0 for i in range(1,len(c)): if a==1: a=0 continue if(c[i]==0): jump+=1 else: a=0 continue if(c[i-1]==0 and c[i]==0): if(i+1!=len(c)): if(c[i+1]==0): a=1 return jump if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) c = list(map(int, input().rstrip().split())) result = jumpingOnClouds(c) fptr.write(str(result) + '\n') fptr.close() []
number1 = input("Enter an integer: ") n_list = list(number1) n_list.reverse() number2 = "".join(n_list) print('"Inverse" number: ', number2)
def max_local(text, max_loc=0, counter=0, max_lenght_words_pos=0): for x in text: if max_loc < len(x): max_loc = len(x) max_lenght_words_pos = counter counter += 1 return max_lenght_words_pos def min_local(text, counter=0, min_lenght_words_pos=0): min_local = len(text[0]) for x in text: if min_local > len(x): min_local = len(x) min_lenght_words_pos = counter counter += 1 return min_lenght_words_pos text = input("Input str with words: ") text = text.split() max_lenght_words_pos = 0 min_lenght_words_pos = 0 max_lenght_words_pos = max_local(text) min_lenght_words_pos = min_local(text) line_t = text[max_lenght_words_pos] text[max_lenght_words_pos] = text[min_lenght_words_pos] text[min_lenght_words_pos] = line_t text_output = "" for x in text: text_output += x print(text_output)
def arithmetic_arranger(problems, ok=False): # check problem list first = '' second = '' sum_x = '' lines = '' # check if there are more than 5 problems if len(problems) > 5: return 'Error: Too many problems.' # split problems to single problem for i in problems: a = i.split() n1 = a[0] n2 = a[2] sign = a[1] # check the length of the number (max 4) if len(n1) > 4 or len(n2) > 4: return "Error: Numbers cannot be more than four digits." # check the input as valid digits if not n1.isnumeric() or not n2.isnumeric(): return "Error: Numbers must only contain digits." if sign == '+' or sign == '-': if sign == "+": sums = str(int(n1) + int(n2)) else: sums = str(int(n1) - int(n2)) # set length of sum and top, bottom and line values length = max(len(n1), len(n2)) + 2 top = str(n1).rjust(length) bottom = sign + str(n2).rjust(length - 1) line = '' res = str(sums).rjust(length) for s in range(length): line += '-' # add to the overall string if i != problems[-1]: first += top + ' ' second += bottom + ' ' lines += line + ' ' sum_x += res + ' ' else: first += top second += bottom lines += line sum_x += res else: return "Error: Operator must be '+' or '-'." # using rstrip function for right align first.rstrip() second.rstrip() lines.rstrip() if ok: sum_x.rstrip() arranged_problems = first + '\n' + second + '\n' + lines + '\n' + sum_x else: arranged_problems = first + '\n' + second + '\n' + lines return arranged_problems
value = input("Please Enter the number: ") print("Your Entered number is " +value) if int(value) in range (1, 100): print ("Positive Number") else: print ("Negative number")
person = input ("Please Enter your name :") print("Hello " +person)
import time import Suspect def intro(): print("A game of guesses") introText() def introText(): # Suspect.set_difficulty() #skipIntro = input("Want to skip intro?") #if skipIntro == "yes": # gameplayStart() #else: time.sleep(3) print("You are a detective in the 10th century.\n") time.sleep(5) print("In the middle of the dinner a page stumbles through your door.\n") time.sleep(5) print("""There's been a murder! The king is dead! Can you help us find the one guilty of this horrible deed?\n""") time.sleep(5) print("""You follow the page through the city and up to the castle and into a secluded room. In the room there are five others. The Queen, A noble, the local priest, a chef and a blacksmith. The page says that these are the suspects and only one of them is guilty but the others could be involved in several ways and you have to find out what happened and who's guilty of the deed by questioning them.\n""") time.sleep(10) print("""First you pick who to question, then you can ask the suspect about other suspects including the one you're talking to. You can also ask them about their relationship with the king by simply typing king. \n""") time.sleep(10) gameplayStart() def gameplayStart(): q6 = input("Who'd you like to start question? 'queen', 'noble', 'priest', 'chef', 'blacksmith'") if q6 == "queen": Suspect.queen.startup(0) elif q6 == "noble": Suspect.noble.startup(0) elif q6 == "priest": Suspect.priest.startup(0) elif q6 == "chef": Suspect.chef.startup(0) elif q6 == "blacksmith": Suspect.blacksmith.startup(0) else: print("Unvalid action") gameplayStart()
import json from grid import * class GridDisplay: def __init__(self, grid): self.grid = grid def __str__(self): out = [] for row in range(self.grid.height): out2 = [] for col in range(self.grid.width): out2.append("{" + str(self.grid.grid[row][col]) + "}") out2.append(chr(row + 65)) # chr(row+65) generates the ASCII char for the capital letter out.append(out2) out.append(["-" + str(col + 1) + "-" for col in range(self.grid.width)]) return ('\n').join([' '.join(x) for x in out]) """ Method that takes a filepath to a valid Grid *.txt file as its parameter, then reads it character by character and parses that into a list of lists for easy Grid construction. """ def read_grid(filepath): # read a grid from a txt file and use that to populate our grid try: file = open(filepath, "r") list = [] list2 = [] # loops until it sees that there is no further characters available, i.e. hits EOF while True: # read in each byte at a time ch = file.read(1) # hits EOF if not ch: list.append(list2) # append the last inner list before breaking break # if it sees a newline char, it terminates the inner list and appends it to the outer list elif(ch == "\n"): list.append(list2) list2 = [] # restart the inner list else: list2.append(ch) return list except IOError as e: print("Cannot open " + filepath) return [] ####################################### # TEST AREA ####################################### if __name__ == "__main__": print("hello world") newGrid = Grid(9, 9) print(str(newGrid)) data = get_cell_data('cell_bank.json') grid_data = read_grid("state_rec_1.txt") print(grid_data) newGrid.populate_grid_from_file(data, grid_data) print(newGrid) display = GridDisplay(newGrid) print(str(display))
# -*- coding:utf-8 -*- import json import argparse import os def importingargs(): """ importing args """ parser = argparse.ArgumentParser( description="Reverse the file by DESC by col3") parser.add_argument( "--inputfilepath", help="This is the filepath of input file") parser.add_argument("--outputfilepath", help="This is the outputfilepath") args = parser.parse_args() assert os.path.exists(args.inputfilepath), "inputfilepath is not found" return args.inputfilepath, args.outputfilepath def import_jsonfile(inputfilepath): """ Read file """ with open(inputfilepath,"r") as f: inputlist = [ line.strip() for line in f.readlines() ] return inputlist def extract_target_json_data(inputlist, target): """ Extracting of jsondata """ for tmpdata in inputlist: jsondata = json.loads(tmpdata) if jsondata['title'] == target: return jsondata['text'] def output(outputfilepath,outputdata): """ Outputting """ with open(outputfilepath,"w") as of: of.write(outputdata) def main(): print("Start") inputfilepath, outputfilepath = importingargs() inputlist = import_jsonfile(inputfilepath) outputdata = extract_target_json_data(inputlist,'ใ‚คใ‚ฎใƒชใ‚น') output(outputfilepath,outputdata) print("Finish") if __name__ == "__main__": main()
import argparse import os def importingargs(): """ importing args """ parser = argparse.ArgumentParser( description="Searching the different first literals") parser.add_argument( "--inputfilepath", help="This is the filepath of input file") parser.add_argument("--linesnum",help="This is the lines num",type=int) args = parser.parse_args() assert args.inputfilepath,"inputfilepath is not found" assert type(args.linesnum) == int, "linesnum must be int" return args.inputfilepath,args.linesnum def countfilelines(inputfilepath,linesnumshell): #: count the lines num linesnum = len([1 for line in open(inputfilepath,"r")]) #: check the this program is correct or not assert linesnum == linesnumshell,"This define is not correct" print("lines num by shell : %s" % linesnumshell) print("lines num by python : %s" % linesnum) def main(): inputfilepath,linesnum = importingargs() countfilelines(inputfilepath,linesnum) if __name__ == "__main__": main()
from sys import argv def average_word_length(file_name): with open(file_name, 'r') as file: contents = file.read() split = contents.split(' ') return sum([len(word) for word in split]) / float(len(split)) if __name__ == '__main__': filename = argv[1] avg_word_length = average_word_length(filename) print "Average word length '{}' is {}".format(filename, avg_word_length)
# https://www.hackerrank.com/challenges/python-division/problem n1 = int (input()) n2 = int (input()) print(n1 // n2) print (n1 /n2)
# https://www.hackerrank.com/challenges/merge-the-tools/problem from collections import OrderedDict z= input() k = int(input()) a = int(len(z)/k) store = [] for i in range(a): temp = z[i * k : (i+1) * k ] store.append(temp) for items in store: print("".join(OrderedDict.fromkeys(items)))
#Print a hashtag pyramid from cs50 import get_int #Get user input for pyramid height while True: height = get_int("height: ") width = height if height >= 0 and height < 24: break #Iterate through layers of pyramid for i in range(1, height + 1): hashes = i spaces = width - hashes print(" " * spaces, end="") print("#" * hashes, end="") print(" ", end="") print("#" * hashes) #Another implementation #for i in range(height): #for j in range(2 * width + 2): #if j - i > height + 2: #print("", end="") #elif j == height or j == height + 1 or i + j < height - 1: #print(" ", end="") #else: #print("#", end="") #print()
#!/usr/bin/env python # coding: utf-8 # In[3]: # Imports import math import numpy as np import pandas as pd import scipy.stats get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt plt.style.use('ggplot') import seaborn as sns # In[4]: housingdf = pd.read_csv('AmesHousing.csv') housingdf.head() # In[5]: print('Our training dataset has {} rows and {} columns.'.format(housingdf.shape[0], housingdf.shape[1])) # In[12]: #numerical & categorical columns catcols = housingdf.select_dtypes('object').columns numcols = housingdf.select_dtypes('number').columns print("Categorical variable count: ", len(catcols)) print("Numerical variable count: ", len(numcols)) # In[14]: print("Categorical variables: ", catcols) print("Numerical variables: ", numcols) # ### EDA # In[11]: print('The cheapest house sold for ${:,.0f} and the most expensive for ${:,.0f}'.format( housingdf.SalePrice.min(), housingdf.SalePrice.max())) print('The average sales price is ${:,.0f}, while median is ${:,.0f}'.format( housingdf.SalePrice.mean(), housingdf.SalePrice.median())) housingdf.SalePrice.hist(bins=75, rwidth=.8, figsize=(14,4)) plt.title('How expensive are houses?') plt.show() # In[16]: # When were the houses built? print('Oldest house built in {}. Newest house built in {}.'.format(housingdf['Year Built'].min(), housingdf['Year Built'].max())) housingdf['Year Built'].hist(bins=14, rwidth=.9, figsize=(12,4)) plt.title('When were the houses built?') plt.show() # housingdf['Year Built'] # In[21]: # Let's start with our dependent variable, SalePrice plt.figure(figsize=(10,6)) sns.distplot(housingdf['SalePrice']) plt.show() print('Skewness Score:', (housingdf['SalePrice'].skew())) print('Kurtosis Score:', (housingdf['SalePrice'].kurtosis())) # We can see data is postively skewed therefore there are outliers with this feature majorly towards the right side i.e higher sale prices # We will deal with these outliers while doing multivariate analysis. We will do univariate analysis on the data first to look over # #### Univariate Analysis for Categorical Variables # we will draw historgrams to understand the distribution of numerical values # In[28]: plt.figure() housingdf.hist(layout=(8,5),color='k', alpha=0.5, bins=50,figsize=(20,30)); # We can see some numerical features have no variance so they will not be useful for our analysis - # MasVNRArea BsmtFinSF2, 2ndFlrSF, LowQualFinSF, BsmtHalfBath, MiscVal, PoolArea, ScreenPorch,3SsnPorch, EnclosedPorch # # we will determine the correlation of these features to our target variable. We will plot a heatmap later to determine the correlation # #### Univariate Analysis for Categorical Variables # In[26]: # Plot bar plot for each categorical feature fig, axes =plt.subplots(10,4, figsize=(20,40)) axes = axes.flatten() for ax, catplot in zip(axes, housingdf.dtypes[catcols].index): sns.countplot(y=catplot, data=housingdf, ax=ax) plt.tight_layout() plt.show() # 1. As we can see, some of the categorical variables have no use to us. SO we can remove these # MSZoning, LotShape, LotConfig, Neighborhood, Condition1, BldgType, Housestyle, Roofstyle, ExterQual, # ExterCond, BsmtCond, BsmtFinType1, HeatingQC, CentralAir, KitchenQual, GarageType, GarageQual # # 2. we note that there are plenty of feature were one value is heavily overrpresented, this might be helpful in detecting outliers # # 3. categorical features actually contain rank information in them and should thus be converted to discrete quantitative features. # #### Bivariate and multivariate analysis # In[ ]:
""" Osbert Lee, Yui Suzuki, Yukito Shida CSE 163 Section AA This file serves to produce quantifiable values that the user can interpret. Specifically, the probabilities file should be able to produce the results of a machine learning prediction and also a confidence interval to test the 911 dials between seasons. """ from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split import pandas as pd import numpy as np import scipy.stats as stats class Probabilities: """ The Probabilities class is a culmination of two separate statistical calculations that each provide insight into how we should interpret the given data. """ def __init__(self, dataset, address=None, month=None): """ Initalizes the probability class by taking in a location and time. If there is no location and time inputted, assume they are None. The initialization should also take in the given dataset to be used in the future. These values are stored. """ self._df = dataset if address is not None: self._data = {"address": [address], "datetime": [month]} self._address = address self._month = month def predict(self): """ Uses two machine learning models to determine a prediction based on a given dataset, location, and time. The prediction will be the likelihood of having a certain type of 911 dial. Function will return a tuple of (the type of 911 dial, the percent likeilhood). If the inputted location and time are not within the dataset, or if the dataset cannot draw meaningful conclusions, the function will return a tuple of and empty string and a unrelated percent value. Assume that the given month parameter will be a real month. Assume case sensitive. """ cleaned = self._df.loc[:, ["datetime", "type", "address"]] cleaned["datetime"] = self._df["datetime"].str[5:7].str.lstrip("0") cleaned["datetime"] = cleaned['datetime'].astype(int) conversion = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"} cleaned["datetime"] = cleaned["datetime"].replace(conversion) dt = cleaned[cleaned["address"] == self._address] if (len(dt) == 0): return ("", 0) input_df = pd.DataFrame(self._data) features = cleaned.loc[:, ["datetime", "address"]] features.append(self._data, ignore_index=True) features = pd.get_dummies(features) input_df = features.iloc[-1] input_df = input_df.values.reshape(1, -1) labels = pd.get_dummies(cleaned.loc[:, "type"]) features_train, features_test, labels_train, labels_test = ( train_test_split(features, labels, test_size=0.2)) dtc_model = DecisionTreeClassifier() rfc_model = RandomForestClassifier() dtc_model.fit(features_train, labels_train) rfc_model.fit(features_train, labels_train) pred_dtc = dtc_model.predict(features_test) pred_rfc = rfc_model.predict(features_test) pred_input = rfc_model.predict(input_df) accuracy_dtc = accuracy_score(labels_test, pred_dtc) accuracy_rtc = accuracy_score(labels_test, pred_rfc) average_accuracy = (accuracy_dtc + accuracy_rtc) / 2 * 100 percent = str(average_accuracy) index = np.where(pred_input == 1.) if len(index[0]) == 0: return ("", percent) else: index = index[1][0] name = labels.columns[index] return (name, percent) def conf_interval(self): """ Computes and prints out the 95% confidence interval of proportion of cases in the spring months vs the proportion of cases in the fall months """ cleaned = self._df.loc[:, ["datetime"]] cleaned["datetime"] = self._df["datetime"].str[5:7].str.lstrip("0") cleaned["datetime"] = cleaned['datetime'].astype(int) shuffle = cleaned.sample(frac=1) result = np.array_split(shuffle, 2) spring_data = result[0].head(100) fall_data = result[1].head(100) spring = (spring_data["datetime"] == 3) | ( spring_data["datetime"] == 4) | (spring_data["datetime"] == 5) fall = (fall_data["datetime"] == 9) | ( fall_data["datetime"] == 10) | (fall_data["datetime"] == 11) spring_size = spring_data[spring].size fall_size = fall_data[fall].size confidence = 0.95 spring_total = 100 fall_total = 100 prop_spring = float(spring_size) / spring_total prop_fall = float(fall_size) / fall_total var = prop_spring * (1 - prop_spring) / spring_total + \ prop_fall * (1 - prop_fall) / fall_total se = np.sqrt(var) significance = 1 - confidence z = stats.norm(loc=0, scale=1).ppf(confidence + significance / 2) prop_diff = prop_spring - prop_fall confint = prop_diff + np.array([-1, 1]) * z * se return list(confint)
#!/usr/bin/env python # -*- coding: utf-8 -*- import random def main(): print "Welcome to the Lottery numbers generator" st_stevilk = int(raw_input("Please enter how many random numbers would you like to have:")) loto = [] while True: if len(loto) == st_stevilk: break else: stevilo = random.randint(1,39) if stevilo not in loto: loto.append(stevilo) print loto print "End" if __name__ == '__main__': main()
from os.path import isfile, exists import os import shutil def makeFolders(): foldersNeeded = ['Documents', 'Pictures'] # Just add whatever folders are required here for folder in foldersNeeded: if(not exists(folder)): os.mkdir(folder) def sortFiles(): files = [f for f in os.listdir() if isfile(f)] for file in files: if (file.endswith('.pdf') or file.endswith('.docx')): shutil.move(file, 'Documents') elif (file.endswith('.jpg') or file.endswith('.png') or file.endswith('.jpeg')): shutil.move(file, 'Pictures') if __name__ == "__main__": path = "/home/manantaneja/Downloads" os.chdir(path) makeFolders() ## need to run this only once or when you require a new folder sortFiles()
from .Algorithm import Algorithm class CreateLoop(Algorithm): def __init__(self,start,end,step,inner_code): self.start=start self.end=end self.step=step self.inner_code=inner_code def python3(self): return f'for i in range({self.start},{self.end},{self.step}){self.inner_code}' def python2(self): return f'for i in range({self.start},{self.end},{self.step}){self.inner_code}' def cpp(self): return f'for(int i={self.start};i<{self.end};{"i++" if self.step=="1" else "i=i+"+self.step}){self.inner_code}' def php(self): return f'for($i={self.start};$i<{self.end};i+={self.step}){self.inner_code}' def java(self): return f'for(int i={self.start};i<{self.end};{"i++" if self.step=="1" else "i=i+"+self.step}){self.inner_code}' def csharp(self): return f'for(int i={self.start};i<{self.end};{"i++" if self.step=="1" else "i=i+"+self.step}){self.inner_code}' def golang(self): return f'for i:={self.start};i<{self.end};{"i++" if self.step=="1" else "i=i+"+self.step}{self.inner_code}' def javascript(self): return f'for(let i={self.start};i<{self.end};{"i++" if self.step=="1" else "i=i+"+self.step}){self.inner_code}' def C(self): return f'for(int i={self.start};i<{self.end};{"i++" if self.step=="1" else "i=i+"+self.step}){self.inner_code}' def ruby(self): return f'for i in {self.start}..({self.end}) do{self.inner_code}'
import math class Distribution: def __init__(self): self.quantity = 0 self.percentage = 0 self.range = [0, 0] self.totalBits = 0 self.flowerNumber = 0 def add(self): self.quantity += 1 #Setter def setQuantity(self, total): self.quantity = total def setPercentage(self, total): self.percentage = (self.quantity / total)*100 def setRange(self, min): self.range[0] = min self.range[1] = math.floor(min + self.totalBits*(self.percentage/100) - 1) def setMaxRange(self, max): self.range[1] = max def setTotal(self, total): self.totalBits = total def setFlowerNumber(self, num): self.flowerNumber = num #Getter def getRangeMin(self): return self.range[0] def getRangeMax(self): return self.range[1] def getQuantity(self): return self.quantity def getPercentage(self): return self.percentage def getFloweNumber(self): return self.flowerNumber def print(self): print("[", self.getQuantity(), " ", "%", self.getPercentage(), " (" , self.getRangeMin(), self.getRangeMax(), ")", " #", self.getFloweNumber(), "]")
def calc(x, y, op): res = 0 if op == '+': res = x + y elif op == '-': res = x - y elif op == '*': res = x * y elif op == '/': res = x / y return res while True: data = input('Type formula like \'x + y\' or \'quite\' to exit: ') if data == 'quit': break elif data == '': continue o = data.split(' ') try: x = float(o[0]) y = float(o[2]) print('{0} = {1}'.format(data, calc(x, y, o[1]))) except ValueError: print('Please, use numeric values for operands.')
# ะ—ะฐะดะฐั‡ะฐ-1: # ะ”ะฐะฝ ัะฟะธัะพะบ ั„ั€ัƒะบั‚ะพะฒ. # ะะฐะฟะธัˆะธั‚ะต ะฟั€ะพะณั€ะฐะผะผัƒ, ะฒั‹ะฒะพะดัั‰ัƒัŽ ั„ั€ัƒะบั‚ั‹ ะฒ ะฒะธะดะต ะฝัƒะผะตั€ะพะฒะฐะฝะฝะพะณะพ ัะฟะธัะบะฐ, # ะฒั‹ั€ะพะฒะฝะตะฝะฝะพะณะพ ะฟะพ ะฟั€ะฐะฒะพะน ัั‚ะพั€ะพะฝะต. # ะŸั€ะธะผะตั€: # ะ”ะฐะฝะพ: ["ัะฑะปะพะบะพ", "ะฑะฐะฝะฐะฝ", "ะบะธะฒะธ", "ะฐั€ะฑัƒะท"] # ะ’ั‹ะฒะพะด: # 1. ัะฑะปะพะบะพ # 2. ะฑะฐะฝะฐะฝ # 3. ะบะธะฒะธ # 4. ะฐั€ะฑัƒะท # ะŸะพะดัะบะฐะทะบะฐ: ะฒะพัะฟะพะปัŒะทะพะฒะฐั‚ัŒัั ะผะตั‚ะพะดะพะผ .format() fruit = ["ัะฑะปะพะบะพ", "ะฑะฐะฝะฐะฝ", "ะบะธะฒะธ", "ะฐั€ะฑัƒะท"] for t in range(len(fruit)): print('{}.{:>7}'.format(t+1, fruit[t])) # ะ—ะฐะดะฐั‡ะฐ-2: # ะ”ะฐะฝั‹ ะดะฒะฐ ะฟั€ะพะธะทะฒะพะปัŒะฝั‹ะต ัะฟะธัะบะฐ. # ะฃะดะฐะปะธั‚ะต ะธะท ะฟะตั€ะฒะพะณะพ ัะฟะธัะบะฐ ัะปะตะผะตะฝั‚ั‹, ะฟั€ะธััƒั‚ัั‚ะฒัƒัŽั‰ะธะต ะฒะพ ะฒั‚ะพั€ะพะผ ัะฟะธัะบะต. a = list('~?Hello World!? mmm') b = list('m ~?') print("ะกะฟะธัะพะบ ะดะพ ะพะฑั€ะฐะฑะพั‚ะบะธ: {}".format(a)) for x in b: while x in a: a.remove(x) print("ะกะฟะธัะพะบ ะฟะพัะปะต ะพะฑั€ะฐะฑะพั‚ะบะธ: {}".format(a)) # ะ—ะฐะดะฐั‡ะฐ-3: # ะ”ะฐะฝ ะฟั€ะพะธะทะฒะพะปัŒะฝั‹ะน ัะฟะธัะพะบ ะธะท ั†ะตะปั‹ั… ั‡ะธัะตะป. # ะŸะพะปัƒั‡ะธั‚ะต ะะžะ’ะซะ™ ัะฟะธัะพะบ ะธะท ัะปะตะผะตะฝั‚ะพะฒ ะธัั…ะพะดะฝะพะณะพ, ะฒั‹ะฟะพะปะฝะธะฒ ัะปะตะดัƒัŽั‰ะธะต ัƒัะปะพะฒะธั: # ะตัะปะธ ัะปะตะผะตะฝั‚ ะบั€ะฐั‚ะตะฝ ะดะฒัƒะผ, ั‚ะพ ั€ะฐะทะดะตะปะธั‚ัŒ ะตะณะพ ะฝะฐ 4, ะตัะปะธ ะฝะต ะบั€ะฐั‚ะตะฝ, ั‚ะพ ัƒะผะฝะพะถะธั‚ัŒ ะฝะฐ ะดะฒะฐ. t = [12, 49, 8, 96, 17, 22, 10, 37] s = [] for x in t: if x % 2 == 0: s.append(x / 4) else: s.append(x * 2) print(s)
""" This module illustrates how to use Matplolib subplots routine. This recipe is useful when there is necessary to plot multiple related plots within the same figure, side by side. """ import numpy as np import matplotlib.pyplot as plt def generate_newton_iters(x0, number): """ This function represents a Newton's method applied to the f(x)=x**2 - 1, with an initial value x0 """ iterates = [x0] errors = [abs(x0 - 1.)] for _ in range(number): x0 = x0 - (x0*x0 - 1.)/(2*x0) iterates.append(x0) errors.append(abs(x0 - 1.)) return iterates, errors # initial guess x0 = 2, 5 iterations iterates, errors = generate_newton_iters(2.0, 5) # 1 row, 2 columns fig, (ax1, ax2) = plt.subplots(1, 2, tight_layout=True) ax1.plot(iterates, "x") ax1.set_title("Iterates") ax1.set_xlabel("$i$", usetex=True) ax1.set_ylabel("$x_i$", usetex=True) # plot y on a logarithmic scale ax2.semilogy(errors, "x") ax2.set_title("Error") ax2.set_xlabel("$i$", usetex=True) ax2.set_ylabel("Error") plt.show()
""" Linear regression is a tool for modeling the dependence between two sets of data so that we can eventually use this model to make predictions. The name comes from the fact that we form a linear model (straight line) of one set of data based on a second. In the literature, the variable that we wish to model is frequently called the response variable, and the variable that we are using in this model is the predictor variable. This module illustrates how to use the statsmodels package to perform a simple linear regression to model the relationship between two sets of data. """ import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt from numpy.random import default_rng rng = default_rng(12345) x = np.linspace(0, 5, 25) rng.shuffle(x) trend = 2.0 shift = 5.0 y1 = trend * x + shift + rng.normal(0, 0.5, size=25) y2 = trend * x + shift + rng.normal(0, 5, size=25) fig, ax = plt.subplots() ax.scatter(x, y1, c="b", label="Good correlation") ax.scatter(x, y2, c="r", label="Bad correlation") ax.legend() ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_title("Scatter plot of data with best fit lines") pred_x = sm.add_constant(x) model1 = sm.OLS(y1, pred_x).fit() model2 = sm.OLS(y2, pred_x).fit() print(model1.summary()) print(model2.summary()) model_x = sm.add_constant(np.linspace(0, 5)) model_y1 = model1.predict(model_x) model_y2 = model2.predict(model_x) ax.plot(model_x[:, 1], model_y1, 'b') ax.plot(model_x[:, 1], model_y2, 'r') plt.show()
""" This module provides examples of Numpy's universal functions (ufunc), which are routines that can operate efficiently on Numpy array types. """ import numpy as np arr_a = np.array([1, 2, 3, 4]) arr_b = np.array([1, 0, -3, 1]) arr_a + arr_b # array([2, 2, 0, 5]) arr_a - arr_b # array([0, 2, 6, 3]) arr_a * arr_b # array([1, 0, -9, 4]) arr_b / arr_a # array([1., 0., -1., 0.25]) arr_b ** arr_a # array([1, 0, -27, 1]) arr = np.array([1, 2, 3, 4]) new = 2 * arr print(new) # [2, 4, 6, 8]
""" Correctly keeping track of units in calculations can be very difficult, particularly if there are places where different units can be used. For example, it is very easy to forget to convert between different units โ€“ feet/inches into meters โ€“ or metric prefixes โ€“ converting 1 km into 1,000 m, for instance. This module illustrates how to use the Pint package to keep track of units of measurement in calculations. """ import pint ureg = pint.UnitRegistry(system="mks") @ureg.wraps(ureg.meter, ureg.second) def calc_depth(dropping_time): # s = u*t + 0.5*a*t*t # u = 0; a = 9.81 return 0.5*9.81*dropping_time*dropping_time distance = 5280 * ureg.feet print(distance.to("miles")) print(distance.to_base_units()) print(distance.to_base_units().to_compact()) depth = calc_depth(0.05 * ureg.minute) print("Depth:", depth) # Depth 44.144999999999996 meter
""" Networks are also useful in scheduling problems, where you need to arrange ctivities into different slots so that there are no conflicts. For example, we could use networks to schedule classes to make sure that students who are taking different options do not have to be in two classes at once. In this scenario, the nodes will represent the different classes and the edges will indicate that there are students taking both classes. The process we use to solve these kinds of problems is called network coloring. """ import networkx as nx import matplotlib.pyplot as plt G = nx.complete_graph(3) G.add_nodes_from(range(3, 7)) G.add_edges_from([ (2, 3), (2, 4), (2, 6), (0, 3), (0, 6), (1, 6), (1, 5), (2, 5), (4, 5) ]) coloring = nx.greedy_color(G) print(f"Coloring: {coloring}") # Coloring: {2: 0, 0: 1, 1: 2, 5: 1, 6: 3, 3: 2, 4: 2} different_colors = set(coloring.values()) print(f"Different colors: {different_colors}") # Different colors: {0, 1, 2, 3} fig, ax = plt.subplots() nx.draw_circular(G, ax=ax, with_labels=True) ax.set_title("Scheduling network") plt.show()
""" This module contains code that creates n-dimensional arrays """ import numpy as np mat = np.array([[1, 2], [3, 4]]) vec = np.array([1, 2]) mat.shape # (2, 2) vec.shape # (2,) mat.reshape(4,) # array([1, 2, 3, 4]) mat1 = [[1, 2], [3, 4]] mat2 = [[5, 6], [7, 8]] mat3 = [[9, 10], [11, 12]] arr_3d = np.array([mat1, mat2, mat3]) arr_3d.shape # (3, 2, 2) mat[0, 0] # 1 - top left element mat[1, 1] # 4 - bottom right element mat[:, 0] # array([1, 3]) print(arr_3d)
""" This module illustrates how to solve a simple system of differential equations. Consider the following, classic, Prey-Predator example: dP/dt = 5*P - 0.1*W*P dW/dt = 0.1*W*P - 6*W where P is the prey specie and W, the predators. Note that this system is a compete predator-prey example. """ import numpy as np import matplotlib.pyplot as plt from scipy import integrate def predator_prey_system(t, y): return np.array( [5*y[0] - 0.1*y[1]*y[0], 0.1*y[1]*y[0] - 6*y[1]]) p = np.linspace(0, 100, 25) w = np.linspace(0, 100, 25) P, W = np.meshgrid(p, w) dp, dw = predator_prey_system(0, np.array([P, W])) fig, ax = plt.subplots() ax.quiver(P, W, dp, dw) ax.set_title("Population dynamics for two competing species") ax.set_xlabel("P") ax.set_ylabel("W") initial_conditions = np.array([85, 40]) sol = integrate.solve_ivp(predator_prey_system, (0., 5.), initial_conditions, max_step=0.01) ax.plot(initial_conditions[0], initial_conditions[1], "ko") ax.plot(sol.y[0, :], sol.y[1, :], "k", linewidth=0.5) plt.show() fig, ax = plt.subplots() ax.plot(sol.t, sol.y[0, :], 'k', label='P') ax.plot(sol.t, sol.y[1, :], 'k-.', label='W') ax.set_xlabel('t') ax.set_ylabel('Population') ax.set_title('Population against time') ax.legend() plt.show()
def welcome(msg="welcome to python"): print(msg) welcome("Nice to have you here") def not_welcome(msg="welcome to python"): print(msg) not_welcome() #CLASS means classification/ a group of methods are placed in CLASS print('--------------------- Class -------------------------')
""" init variable while condition: Statements ... """ #alternative of For loop #while loop i=1 while i<=5: print(i,end='\t') i = i+1 print("\n") print(40*"_") j=10 while j<=20: print(j,end="\t") j = j+1 print("\n") print(50*"_") z=10 while z<=20: print(z,end="\t") z = z+2 print("\n") print(50*"_") f=20 while True: #infinity loop if f>=40: break #breaking infinity loop print(f,end="\t") f = f+1 #creating a menu while True : print("====== Main Menu ======") print("1. Add") print("2. List") print("3. Edit") print("4. Exit") print("Enter your selection : ",end="") choice = input() if choice =="1": print("Add New Record") elif choice == "2": print("List Record") elif choice == "3": print("Edit Record") elif choice == "4": print("Exit from program") break else: print("Invalid Selection")
from collections import deque graph = {} graph["Sherif"] = ["Toqa", "Amr", "Zakaria"] graph["Amr"] = ["Zizo", "Selim"] graph["Toqa"] = ["Sherif", "Dodo", "Mohamed"] graph["Zakaria"] = [] graph["Dodo"] = [] graph["Mohamed"] = [] graph["Zizo"] = [] graph["Selim"] = [] def search(name): search_queue = deque() search_queue += graph[name] searched = [] while search_queue: person = search_queue.popleft() if not person in searched: if person_is_seller(person): print(person + " is a mango seller!") return True else: search_queue += graph[person] searched.append(person) return False def person_is_seller(person): if person.endswith("o"): return True else: return False search("Sherif")
"""Coin guess and math game!""" __author__ = "730449914" from random import randint points: int = 1 player: str NAMED_CONSTANT: str = '\U0001F600' NAMED_CONSTANT_1: str = '\U0001F62A' def greet() -> None: """Welcome message!""" print(f"Welcome stranger! You have now entered the game {NAMED_CONSTANT}.") global player player = (input("Please enter your name: ")) def math(b: int, c: int) -> int: """Multiplication function!""" global player yes_no = input(f"You are now inside the powerful calculator {player}. Are you sure that you want to continue? ") if len(yes_no) > 2: print("I love your courage!") else: print("Haha it is already too late, the powerful calculator can't be stopped now!") return b * c def coin() -> None: """Coin function.""" global player global points print(f"You have now entered the coin game {player}. Your goal is to guess wheater the coin will land heads (1) or tails (2). To win, you need to guess right three times in a row.") print(f"One correct answer will give you five points. If you win the game, you will gain 50 - 150 points. However, if you guessed incorrectly, you will lose all your points. Good luck!{NAMED_CONSTANT}") a: int = 0 while a < 3: guess: str = input("Enter your guess: ") if randint(1, 2) == int(guess): print("You guessed correct!") points = points + 50 a = a + 1 else: print(f"You guessed incorrectly {NAMED_CONSTANT_1}. Try again") points = a * (-5) a = 0 def main() -> None: """This is the important function!""" global player global points greet() i: int = 1 while i > 0: print(f"You are now in the game lobby {player}, at this moment you have {points} points. You have the following choices!") print("Coin game: Enter 1. Math game: Enter 2. Quit the game: Enter 3") choice: str = input("Enter one of the numbers to continue: ") if 1 == int(choice): coin() print(f"You are a superstar {player}") print(f"At this moment you have {points} points.") else: if 2 == int(choice): print(f"You have now entered the math game {player}. In this game, you will encounter multiplication questions. You will multiply your current points with a value of your choice. If you guessed correctly, the total sum will be added to your points. However, if you guess incorrectly, your points will stay the same. Good luck!") qop: int = int(input("if you want to play one round of the game, Enter 1. If you want to go back to lobby, Enter 2: ")) while 1 == int(qop): print(f"At this moment you have {points} points.") n_1: int = int(input("Enter the number you want to multiply your points with: ")) print(f"At this moment you have {points} points.") answer: str = input(f"What is {points} * {n_1}? ") if int(answer) == math(int(n_1), int(points)): print(f"{player}, you guessed correctly {NAMED_CONSTANT}. You answered {answer} and the correct answer was {math(int(n_1), int(points))}!") points = points + (n_1 * points) con: str = input("If you want to play one more round of the game, enter 0. If you want to go back to lobby, Enter 1: ") qop = qop + int(con) else: print(f"You guessed incorrectly {NAMED_CONSTANT_1}. You answered {answer} and the correct answer was {math(int(n_1), int(points))}") con_1: str = input("If you want to play one more round of the game, enter 0. If you want to go back to lobby, Enter 1: ") qop = qop + int(con_1) else: i = 0 if __name__ == "__main__": main()
"""Repeating a beat in a loop.""" __author__ = " 730449914" Counter: int = 0 beat: str = str(input("What beat do you want to repeat? ")) frequence: int = int(input("How many times do you want to repeat it? ")) if frequence > 0: while Counter < frequence: if Counter < frequence - 1: print(beat + " ", end="") else: print(beat) Counter = Counter + 1 else: print("No beat...")
class Node(object): ''' Node object. This object corresponds to an orginal node: a single metabolite or reaction. Initialization -------------- node_id: string. Node name. e.g. 'glu__D_e', 'ATPM' node_type: int, 0 or 1. Node type. type = 0, metabolites. type = 1, reactions. Other Attributes ---------------- inNeighbors: dictionary { Node: float }. Key: neighbor Node Value: inweight (neighbor -> self): float outNeighbors: dictionary { Node: float }. Key: neighbor Node Value: outweight (self -> neighbor): float inMetanodes: dictionary { MetaNode: float } Key: neighbor MetaNode Value: inweight (metanode -> self): float outMetanodes: dictionary { MetaNode: float } Key: neighbor MetaNode Value: outweight (self -> metanode): float metanode: MetaNode The metanode this node belongs to. ''' def __init__(self, node_id, node_type): self.id = node_id self.type = node_type self.inNeighbors = {} self.outNeighbors = {} self.inMetanodes = {} self.outMetanodes = {} def setMetanode(self, metanode): '''Set allegiance to metanode''' self.metanode = metanode class MetaNode(object): ''' MetaNode object. This object represents one vertex in each graph. Usually contains multiple Nodes. Initialization -------------- member_nodes: list of Nodes Node members of this metanode. Other Attributes ---------------- type: int, 0 or 1. Metanode type, based on its members' type. type = 0, metabolites. type = 1, reactions. inNeighbors: dictionary { MetaNode: float }. Key: neighbor MetaNode Value: inweight (neighbor -> self): float outNeighbors: dictionary { MetaNode: float }. Key: neighbor MetaNode Value: outweight (self -> neighbor): float inComm: dictionary { Community: float } Key: neighbor Community Value: inweight (community -> self): float outComm: dictionary { Community: float } Key: neighbor Community Value: outweight (self -> community): float inDegree: float The total weight that are coming into this metanode. outDegree: float The total weight that are going out of this metanode. community: Community The community this metanode belongs to. ''' def __init__(self, member_nodes): self.members = member_nodes self.type = member_nodes[0].type self.inNeighbors = {} self.outNeighbors = {} self.inComm = {} self.outComm = {} self.inDegree = None self.outDegree = None def setCommunity(self, community): '''Set allegiance to community''' self.community = community def updateInComm(self, metanode, fromComm, toComm): '''Update the inComm attribute of self, when its inNeighbor metanode is moved from fromComm to toComm.''' if metanode in self.inNeighbors: self.inComm[fromComm] -= self.inNeighbors[metanode] if self.inComm[fromComm] < 1e-5: del self.inComm[fromComm] if toComm not in self.inComm: self.inComm[toComm] = self.inNeighbors[metanode] else: self.inComm[toComm] += self.inNeighbors[metanode] def updateOutComm(self, metanode, fromComm, toComm): '''Update the outComm attribute of self, when its outNeighbor metanode is moved from fromComm to toComm.''' if metanode in self.outNeighbors: self.outComm[fromComm] -= self.outNeighbors[metanode] if self.outComm[fromComm] < 1e-5: del self.outComm[fromComm] if toComm not in self.outComm: self.outComm[toComm] = self.outNeighbors[metanode] else: self.outComm[toComm] += self.outNeighbors[metanode] class Community(object): ''' Community object. This object represents clusters in each graph. Usually contains multiple MetaNodes. Initialization -------------- community_id: int Community ID. member_metanodes: list of MetaNodes MetaNode members of this community. Other Attributes ---------------- type: int, 0 or 1. Community type, based on its members' type. type = 0, metabolites. type = 1, reactions. inNeighbors: dictionary { Community: float }. Key: neighbor Community Value: inweight (neighbor -> self): float outNeighbors: dictionary { MetaNode: float }. Key: neighbor Community Value: outweight (self -> neighbor): float inDegree: float The total weight that are coming into this community. outDegree: float The total weight that are going out of this community. coCluster: Community The co-cluster of this community. modContribution: float The modularity contribution of this community. ''' def __init__(self, community_id, member_metanodes): self.id = community_id self.members = member_metanodes self.type = member_metanodes[0].type self.inNeighbors = {} # dict. Community: weight = neighbor->self self.outNeighbors = {} # dict. Community: weight = self->neighbor self.inDegree = None self.outDegree = None def setCoCluster(self, cocluster): '''Set co-cluster''' self.coCluster = cocluster def setModContribution(self, modContribution): '''Set modularity contribution''' self.modContribution = modContribution def addMetaNode(self, metanode): '''Add metanode into this community''' self.members.append(metanode) for c, w in metanode.inComm.items(): if c not in self.inNeighbors: self.inNeighbors[c] = w else: self.inNeighbors[c] += w for c, w in metanode.outComm.items(): if c not in self.outNeighbors: self.outNeighbors[c] = w else: self.outNeighbors[c] += w self.inDegree += metanode.inDegree self.outDegree += metanode.outDegree def removeMetaNode(self, metanode): '''Remove metanode from this community''' self.members.remove(metanode) for c, w in metanode.inComm.items(): self.inNeighbors[c] -= w if self.inNeighbors[c] < 1e-5: del self.inNeighbors[c] for c, w in metanode.outComm.items(): self.outNeighbors[c] -= w if self.outNeighbors[c] < 1e-5: del self.outNeighbors[c] self.inDegree -= metanode.inDegree self.outDegree -= metanode.outDegree def updateIn(self, metanode, fromComm, toComm): ''' A metanode is moved from fromComm and toComm, and self is metanode's outComm.''' self.inNeighbors[fromComm] -= metanode.outComm[self] if self.inNeighbors[fromComm] < 1e-5: del self.inNeighbors[fromComm] if toComm not in self.inNeighbors: self.inNeighbors[toComm] = metanode.outComm[self] else: self.inNeighbors[toComm] += metanode.outComm[self] def updateOut(self, metanode, fromComm, toComm): ''' A metanode is moved from fromComm and toComm, and self is metanode's inComm.''' self.outNeighbors[fromComm] -= metanode.inComm[self] if self.outNeighbors[fromComm] < 1e-5: del self.outNeighbors[fromComm] if toComm not in self.outNeighbors: self.outNeighbors[toComm] = metanode.inComm[self] else: self.outNeighbors[toComm] += metanode.inComm[self] class Graph(object): ''' Graph object. Reprensents a network with metanodes as vertices. Initialization -------------- metanodes: list of MetaNodes. This is the list of vertices of the network. Other Attributes ---------------- communitiies: dictionary {int: Community}. Key: community id: int Value: Community This is the communities of the network, constructed based on the metanodes' allegiance to communities. ''' def __init__(self, metanodes): self.metanodes = metanodes def updateCommunity(self): '''Update community active in this network''' self.communities = {} for metanode in self.metanodes: if metanode.community.id not in self.communities: self.communities[metanode.community.id]=metanode.community
import csv import argparse def remove_uncategorized_products(file_input): try: with open(file_input, newline='') as csvfile: reader = csv.DictReader(csvfile) return [row for row in reader if row["Categories"]] except FileNotFoundError: err = f"{file_input} does not exist on your root dirctory." raise FileNotFoundError(err) def export_categorized_products(file_input, file_output): categorized_products = remove_uncategorized_products(file_input) if not categorized_products: return None with open(file_output, 'w', newline='') as csvfile: fieldnames = list(categorized_products[0].keys()) writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for product in categorized_products: writer.writerow(product) def is_csv(filename): return 'csv' == filename.split('.')[-1] def process_file(file_input, file_output): try: if not is_csv(file_input): print(f"{file_input} is not a valid csv file.") return if not is_csv(file_output): print(f"{file_output} is not a valid csv file.") return export_categorized_products(file_input, file_output) print(f"successfully process file {file_input}", end=' ') print(f"results can be found at {file_output}") except FileNotFoundError as e: print(e) parser = argparse.ArgumentParser(description='Products CSV Reader and Writer') parser.add_argument('--file-input', type=str, required=True, help='The file to be read') parser.add_argument('--file-output', type=str, required=True, help='The exported csv file with categorized products.') args = parser.parse_args() process_file(args.file_input, args.file_output)
''' An integer d is a divisor of an integer n if the remainder of n % d = 0. Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occurring within the integer. Note: Each digit is considered to be unique, so each occurrence of the same digit should be counted (e.g. for n=111,1 is a divisor of 111 each time it occurs so the answer is 3). Function Description Complete the findDigits function in the editor below. It should return an integer representing the number of digits of d that are divisors of d. findDigits has the following parameter(s): n: an integer to analyze Input Format The first line is an integer, t, indicating the number of test cases. The t subsequent lines each contain an integer, n. Constraints 1 <= t <= 15 0 < n < 10^9 Output Format For every test case, count the number of digits in n that are divisors of n. Print each answer on a new line. Sample Input 2 12 1012 Sample Output 2 3 Explanation The number 12 is broken into two digits, 1 and 2. When 12 is divided by either of those two digits, the remainder is 0 so they are both divisors. The number 1012 is broken into four digits, 1, 0, 1, and 2. 1012 is evenly divisible by its digits 1, 1, and 2, but it is not divisible by 0 as division by zero is undefined. ''' #!/bin/python3 import os # Complete the findDigits function below. def findDigits(n): count = 0 ch_div = [char for char in str(n)] for ch_d in ch_div: if int(ch_d) != 0 and n % int(ch_d) == 0: count += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) result = findDigits(n) fptr.write(str(result) + '\n') fptr.close()
'''Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty. The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]). The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2]. If a[i] > b[i], then Alice is awarded 1 point. If a[i] < b[i], then Bob is awarded 1 point. If a[i] = b[i], then neither person receives a point. Comparison points is the total points a person earned. Given a and b, determine their respective comparison points. Example a = [1, 2, 3] b = [3, 2, 1] For elements *0*, Bob is awarded a point because a[0] . For the equal elements a[1] and b[1], no points are earned. Finally, for elements 2, a[2] > b[2] so Alice receives a point. The return array is [1, 1] with Alice's score first and Bob's second. Function Description Complete the function compareTriplets in the editor below. compareTriplets has the following parameter(s): int a[3]: Alice's challenge rating int b[3]: Bob's challenge rating Return int[2]: Alice's score is in the first position, and Bob's score is in the second. Input Format The first line contains 3 space-separated integers, a[0], a[1], and a[2], the respective values in triplet a. The second line contains 3 space-separated integers, b[0], b[1], and b[2], the respective values in triplet b. Constraints 1 โ‰ค a[i] โ‰ค 100 1 โ‰ค b[i] โ‰ค 100 Sample Input 0 5 6 7 3 6 10 Sample Output 0 1 1 Explanation 0 In this example: Now, let's compare each individual score: , so Alice receives point. , so nobody receives a point. , so Bob receives point. Alice's comparison score is , and Bob's comparison score is . Thus, we return the array . Sample Input 1 17 28 30 99 16 8 Sample Output 1 2 1 Explanation 1 Comparing the elements, so Bob receives a point. Comparing the and elements, and so Alice receives two points. The return array is . ''' #!/bin/python3 import os # Complete the compareTriplets function below. def compareTriplets(a, b): ar=[0,0] for x in range(3): if a[x] > b[x]: ar[0]+=1 elif a[x] < b[x]: ar[1]+=1 return ar if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) result = compareTriplets(a, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
""" You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest. Example candles = [4, 4, 1, 3] The maximum height candles are 4 units high. There are 2 of them, so return 2. Function Description Complete the function birthdayCakeCandles in the editor below. birthdayCakeCandles has the following parameter(s): int candles[n]: the candle heights Returns int: the number of candles that are tallest Input Format The first line contains a single integer, n, the size of candles[]. The second line contains space-separated integers, where each integer describes the height of . Constraints Sample Input 0 4 3 2 1 3 Sample Output 0 2 Explanation 0 Candle heights are [3, 2, 1, 3]. The tallest candles are 3 units, and there are 2 of them. """ #!/bin/python3 import math import os import random import re import sys # # Complete the 'birthdayCakeCandles' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY candles as parameter. # def birthdayCakeCandles(candles): max = 0 count = 0 for x in candles: if x > max: max = x for x in candles: if x == max: count += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') candles_count = int(input().strip()) candles = list(map(int, input().rstrip().split())) result = birthdayCakeCandles(candles) fptr.write(str(result) + '\n') fptr.close()
""" Staircase detail This is a staircase of size : # ## ### #### Its base and height are both equal to . It is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size . Function Description Complete the staircase function in the editor below. staircase has the following parameter(s): int n: an integer Print Print a staircase as described above. Input Format A single integer, , denoting the size of the staircase. Constraints . Output Format Print a staircase of size using # symbols and spaces. Note: The last line must have spaces in it. Sample Input 6 Sample Output # ## ### #### ##### ###### Explanation The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of . """ #!/bin/python3 import math import os import random import re import sys # Complete the staircase function below. def staircase(n): for i in range(0, n): print(((n - i - 1) * " ") + ((i + 1) * "#")) if __name__ == '__main__': n = int(input()) staircase(n)
numero=15 while numero>0: print(numero) numero=numero-1 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 a=2 while numero>0: print(numero) numero=numero-a while numero>0: print(numero) numero=numero-2 numero=14 a=2 while numero>0: print(numero) numero=numero-a 14 12 10 8 6 4 2
numero=1 if (numero==1): print('nรบmero รฉ igual a 1') if (numero==2): print('numero รฉ igual a 2') numero=2 if (numero==1): print ('numero รฉ igual a 1') else: print('numero nรฃo รฉ 1') nome=input('insira o nome:') if ('t'in nome): print('o nome tem um t') elif ('l' in nome): print('o nome tem um l') else: pass
numero=int(input()) #para inverter, um meio รฉ transformar o int em str numero=str(numero) #fazendo: print('datatype',type(numero)) #tenho confirmaรงรฃo: datatype <class 'str'> oremun=''.join(reversed(numero)) print(oremun) #รฉ algo como ".join reversed faz a reversรฃo como itens de lista, e join serve pra juntar ela de volta em str"
var = "hello world!" var1 = 5 var2 = 5.0 var3 = True print(type(var)) print(type(var1)) print(type(var2)) print(type(var3)) reverse_var = var[::-1] splitted = var.split(" ") var = "agam" if var.islower() == True: print("string with lower chars") elif var.isupper() == True: print("string with upper chars") else: pass lst = [1, 2, 3, 4, 5] # print(lst.count(1)) for i in lst: print(i) for i in range(100): print(i) i = 0 while i < 10: print("idan") i += 1 type(lst) user_input = input("please enter an input\n") y = "yotam"
x = set() num_set = {0,1,2,3,4,5} num_list = [0,1,2,3,4,5] for n in num_list: print(n)
formula = str(input("Please enter a formula:\n")) formula_list = formula.split() #1 + 1 print(formula_list) formula_list[0] = number1 formula_list[1] = operator formula_list[2] = number2
lst1 = [10, 20, 30] #global variable def changeme(lst1): lst1 = [1, 2, 3, 4] # local variable print("the values inside lst1 are:", lst1) changeme(lst1) print("the values outside of the function are:", lst1)
from random import randint import time /Users/BOF/Desktop/Education/algorithms/bubble_sort/bubble_sort.py def bubble(array): for i in range(N-1): for j in range(N-i-1): if array[j] > array[j+1]: buff = array[j] array[j] = array[j+1] array[j+1] = buff N = 10000 a = [] for i in range(N): a.append(randint(1, 10000)) print(a) print('\n') start = time.time() bubble(a) end = time.time() print(a) print(end - start)
# #!/usr/bin/env python3 # -- coding: utf-8 -- # --------------------------------------------------------------------------------- # Copyright (c) 2019. Oraldo Jacinto Simon # #---------------------------------------------------------------------------------- # All rights reserved. # # # This is free software; you can do what the LICENCE file allows you to. import os class DrawBoard(object): """ Draw the game board. Print the board in the form of lines of characters """ def __init__(self): self._row1 = ' {0} | {1} | {2} \n _____|_____|_____\n' self._row2 = ' {0} | {1} | {2} \n _____|_____|_____\n' self._row3 = ' {0} | {1} | {2} \n | | ' def set(self, board): self.board = board def update_board(self, board): self.board = board self.draw() @staticmethod def clear_board(): os.system('cls' if os.name == 'nt' else 'clear') def draw(self, show_positions=False): if show_positions: row_position1 = [1, 2, 3] row_position2 = [4, 5, 6] row_position3 = [7, 8, 9] else: row_position1 = [pos.value for pos in self.board.positions[:3]] row_position2 = [pos.value for pos in self.board.positions[3:6]] row_position3 = [pos.value for pos in self.board.positions[6:9]] DrawBoard.clear_board() row1 = self._row1.format(*row_position1) row2 = self._row2.format(*row_position2) row3 = self._row3.format(*row_position3) print("Board: ") print(row1 + row2 + row3)
def get(dict1: dict, string: str) -> str: if string in dict1: return str(dict1[string]) return "" commands = [] def get_dict(_dict: dict) -> str: """ helper function - get dict in format printable :type _dict: dict """ result = "" for key, value in _dict.items(): if isinstance(value, dict): result += "\n" + str(key) + "--\n" + get_dict(value) + "\n" elif isinstance(value, list): result += "\n" + key + "--\n" for j in range(0, len(value)): if isinstance(value[j], dict): result += str(j) + ": " + get_dict(value[j]) + "\n" else: result += "\n" + str(key) + ": " + str(value) return result[1:]
#Cosmeticos ventas={} precioF=0 respuestaW=1 respuesta=1 yellow = '\033[33m' white = '\033[37m' green = '\033[32m' while respuesta==1: print(green) print("||| Bienvendio al Menรบ |||") print(white) print("ยฟQue accion vas a realizar?") print("1-Registrar ventas") print("2-Consultar ventas") print("3-Salir del programa") seleccion=int(input("Ingrese una accion: \n")) if seleccion==1: while respuestaW==1: if ventas: NumVenta = max(ventas) + 1 else: NumVenta = 1 Articulo=input("ยฟQue cosmetico se ha vendido?: \n") pcs=int(input("ยฟCuantas piezas fueron vendidas?: \n")) price=int(input(f"ยฟA que precio fue vendido el {Articulo}?: \n")) Recibo=[Articulo,pcs,price] ventas[NumVenta]=Recibo PrecioFinal=(precioF+price*pcs) print(yellow) print(f"El precio a pagar es de: ${PrecioFinal}") print(white) respuestaW=int(input("Quiere realizar otra venta?: 1 - SI o 0 - NO\n")) if seleccion==2: BuscarVenta=int(input("Que venta quieres buscar?: \n")) if BuscarVenta in ventas.keys(): print(yellow) print(ventas[BuscarVenta]) print(white) respuestaW=int(input("Quiere realizar otra busqueda?: 1 - SI o 0 - NO\n")) else: print(green + "No se ha realizado alguna venta con ese numero de venta") respuestaW=int(input(white + "Quiere realizar otra venta?:\n 1 - SI o 0 - NO \n" )) if seleccion==3: print(green + "Ha finalizado correctamente el programa, gracias por haber comprado.") break
import webbrowser import pyautogui from time import sleep def open_website(): """ Opens Henry Ford Hospital MyChart Scheduling link. :return: n/a """ webbrowser.open('https://mychart.hfhs.org/MyChart/Scheduling') sleep(4) def click_button(button_image, delay=1): """ :param button_image: image name string (must be stored in same directory as code) :param delay: delay in seconds after button is clicked :return: n/a """ location = pyautogui.locateCenterOnScreen(button_image, confidence=.5) pyautogui.moveTo(location) pyautogui.click() sleep(delay) def check_appointment(): """ Checks for "no available appointments" image on screen. :return: returns coordinate location if "no available appointments" image is found, returns None if appointments found """ return pyautogui.locateOnScreen('no_appointment.png', confidence=.5) def main(): """ Main function that performs the correct sequence to auto-fill forms and check if there are available appointments. :return: n/a """ try: open_website() while True: click_button('covid19.png') click_button('no.png') click_button('continue.png') click_button('no.png') click_button('continue.png') click_button('teacher.png') click_button('continue.png') click_button('yes.png') click_button('continue.png') click_button('no.png') click_button('continue.png') click_button('no.png') click_button('continue.png') click_button('no.png') click_button('continue.png') click_button('questions.png') click_button('yes2.png') click_button('yes2.png') click_button('yes2.png') click_button('continue.png', delay=3) click_button('location.png') click_button('continue.png') no_appointment = check_appointment() if no_appointment: click_button('start_over.png', delay=3) continue else: print("Appointments available!!!") break except Exception as e: print(f'main error: {e}') if __name__ == '__main__': main()
class Point(tuple): def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) @property def x(self): return self.__getitem__(0) @property def y(self): return self.__getitem__(1) def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def __repr__(self): return f"Point{tuple.__repr__(self)}"
''' 12. Write a Python program to extract all the text from a given web page. ''' import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' html = requests.get(url).text soup = BeautifulSoup(html,"html.parser") print(soup.get_text().strip())
''' 35. Write a Python program to wrap an element in the specified tag and create the new wrapper. ''' from bs4 import BeautifulSoup soup = BeautifulSoup("<p>Python exercises.</p>", "lxml") print("Original Markup:") print(soup.p.string.wrap(soup.new_tag("i"))) print("\nNew Markup:") print(soup.p.wrap(soup.new_tag("div")))
''' 32. Write a Python program to extract a tag or string from a given tree of html document. ''' from bs4 import BeautifulSoup html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>' soup = BeautifulSoup(html_content, "lxml") print("Original Markup:") print(soup.a) i_tag = soup.i.extract() print("\nExtract i tag from said html Markup:") print(i_tag)
from dataclasses import dataclass from exceptions import EmployeeDictError fields = { "employee_id": "Employee ID", "name": "Employee Name", "department": "Department", "designation": "Designation", "salary": "Salary", "sales": "Sales" } @dataclass(order=True) class Employee: employee_id: int '''The id of the employee''' name: str '''The name of the employee''' department: str '''The department of the employee''' designation: str '''The designation of the employee''' salary: float '''The name of the employee''' sales: int '''The number of sales done by the employee''' @classmethod def from_dict(cls, employee_dict: dict): """ Create a new employee object from a dictionary. :param employee_dict: The dict to deserialize. """ # Check if the keys of the dictionary entered match the headers of the CSV File. if set(fields.keys()) != set(employee_dict.keys()): raise EmployeeDictError() employee_id = int(employee_dict['employee_id']) name = employee_dict['name'] department = employee_dict['department'] designation = employee_dict['designation'] salary = float(employee_dict['salary']) sales = int(employee_dict['sales']) return Employee(employee_id, name, department, designation, salary, sales) def get_formatted_salary(self) -> str: """ Formats the employee salary in the format $5,195,432.25 :return: A string of the formatted salary. """ return f'${self.salary:,.2f}' def get_formatted_sales(self) -> str: """ Formats the employee sales in the format 2,000,000. :return: A string of the formatted sales. """ return f'{self.sales:,}' def meets_raise_quota(self) -> bool: return self.sales > 500000 def meets_fire_quota(self) -> bool: return self.sales >= 100000 def to_dict(self) -> dict: """ Serialize an employee object into a dictionary. :return: The serialized dictionary. """ return {field: self.__getattribute__(field) for field in fields.keys()} def __str__(self): string = list() for key, value in fields.items(): item = self.__getattribute__(key) if key == 'salary': item = self.get_formatted_salary() elif key == 'sales': item = self.get_formatted_sales() + ' sales' string.append(f'{value:14}: {item}\n') return ''.join(string)
""" ๋ณธ ์—ฐ์Šต๋ฌธ์ œ์—์„œ๋Š” m^n์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค. ์ž…๋ ฅ์œผ๋กœ๋Š” m, nm,n์ด ์ฐจ๋ก€๋Œ€๋กœ ์ž…๋ ฅ๋ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ getPower ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜ ๊ฐ’์ด 1,000,000,007 ๋ณด๋‹ค ํด ๊ฒฝ์šฐ, ๋ฐ˜ํ™˜ ๊ฐ’์„ 1,000,000,007๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”. ์ž…๋ ฅ ์˜ˆ์‹œ 3 4 ์ถœ๋ ฅ ์˜ˆ์‹œ 81 """ LIMIT_NUMBER = 1000000007 def getPower(m, n): ''' m^n ์„ LIMIT_NUMBER๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”. ''' return 1 def main(): ''' ์ด ๋ถ€๋ถ„์€ ์ˆ˜์ •ํ•˜์ง€ ๋งˆ์„ธ์š”. ''' myList = [int(v) for v in input().split()] print(getPower(myList[0], myList[1])) if __name__ == "__main__": main()
""" ์ •์ˆ˜๋“ค์˜ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์˜ต๋‹ˆ๋‹ค. ์ด ์ •์ˆ˜๋“ค์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ผ๋ถ€๋ถ„๋งŒ ์ž˜๋ผ๋‚ด์–ด ๋ชจ๋‘ ๋”ํ–ˆ์„ ๋•Œ์˜ ๊ฐ’์„ ๋ถ€๋ถ„ํ•ฉ์ด๋ผ ๋ถ€๋ฆ…๋‹ˆ๋‹ค. ์ด๋•Œ ๊ฐ€์žฅ ํฐ ๋ถ€๋ถ„ํ•ฉ์„ ๊ตฌํ•ด๋ด…์‹œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, [-10, -7, 5, -7, 10, 5, -2, 17, -25, 1]์ด ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์™”๋‹ค๋ฉด [10, 5, -2, 17]์„ ๋ชจ๋‘ ๋”ํ•œ 30์ด ์ •๋‹ต์ด ๋ฉ๋‹ˆ๋‹ค. """ import numpy as np def maxSubArray(nums): arr = [] for i in range(len(nums)): subArray = np.cumsum(nums[i:]) result = max(subArray) arr.append(result) return max(arr) def main(): print(maxSubArray([-10, -7, 5, -7, 10, 5, -2, 17, -25, 1])) # 30์ด ๋ฆฌํ„ด๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค # test_array = [1,2,3] # test = np.cumsum(test_array) # print(test) if __name__ == "__main__": main()
""" ์ž…๋ ฅ์œผ๋กœ n๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋ฉด, quick sort๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”. ์ž…๋ ฅ ์˜ˆ์‹œ 10 2 3 4 5 6 9 7 8 1 ์ถœ๋ ฅ ์˜ˆ์‹œ 1 2 3 4 5 6 7 8 9 10 """ def quickSort(array): ''' ํ€ต์ •๋ ฌ์„ ํ†ตํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ array๋ฅผ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”. ''' if len(array) <= 1: return array pivot = array[0] left = getSmall(array[1:], pivot) right = getLarge(array[1:], pivot) return quickSort(left) + [pivot] + quickSort(right) def getSmall(array, pivot): data = [] for a in array: if a <= pivot: data.append(a) return data def getLarge(array, pivot): data = [] for a in array: if a >= pivot: data.append(a) return data def main(): line = [int(x) for x in input().split()] print(*quickSort(line)) if __name__ == "__main__": main()
""" try: ์‹คํ–‰ํ•  ๋ช…๋ น except ์˜ˆ์™ธ as ๋ณ€์ˆ˜: ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ๋ฌธ else: ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์„ ๋•Œ์˜ ์ฒ˜๋ฆฌ """ str = "89์ " try: score = int(str) print(score) except: # ๋ชจ๋“  ์˜ˆ์™ธ์— ๋Œ€ํ•ด print("์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.") print("์ž‘์—…์™„๋ฃŒ") print() str = "89" try: score = int(str) a = str[5] except ValueError: print("์ ์ˆ˜์˜ ํ˜•์‹์ด ์ž˜๋ชป๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") except IndexError: print("์ฒจ์ž ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") print("์ž‘์—…์™„๋ฃŒ") print() try: score = int(str) a = str[5] except(ValueError, IndexError): print("์ ์ˆ˜์˜ ํ˜•์‹ ๋˜๋Š” ์ฒจ์ž ์˜ค๋ฅ˜") print("์ž‘์—…์™„๋ฃŒ") print() str = "90์ " try: score = int(str) except ValueError as e: # e.print() # Stack Overflow print(e) except IndexError as e: # e.print() print(e) print("์ž‘์—…์™„๋ฃŒ") print() def test(str): score = int(str) print(score) def work1(): str = "89์ " try: test(str) except Exception as e: print(e) work1()
""" ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ชจ๋ฐ”์ผ์€ ๊ฐœ์ธ์ •๋ณด ๋ณดํ˜ธ๋ฅผ ์œ„ํ•ด ๊ณ ์ง€์„œ๋ฅผ ๋ณด๋‚ผ ๋•Œ ๊ณ ๊ฐ๋“ค์˜ ์ „ํ™”๋ฒˆํ˜ธ์˜ ์ผ๋ถ€๋ฅผ ๊ฐ€๋ฆฝ๋‹ˆ๋‹ค. ์ „ํ™”๋ฒˆํ˜ธ๊ฐ€ ๋ฌธ์ž์—ด phone_number๋กœ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ „ํ™”๋ฒˆํ˜ธ์˜ ๋’ท 4์ž๋ฆฌ๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์ˆซ์ž๋ฅผ ์ „๋ถ€ *์œผ๋กœ ๊ฐ€๋ฆฐ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด์ฃผ์„ธ์š”. """ def solution(phone_number): answer = "" length = len(phone_number) - 4 for i in range(length): answer = answer + "*" answer = answer + phone_number[-4:] return answer a = solution("01087651234") print(a)
array = [1,3,5,6,9] sum = 0 for x in array: sum += x print("sum: ",sum)
""" ์ž์—ฐ์ˆ˜ n์„ ๋’ค์ง‘์–ด ๊ฐ ์ž๋ฆฌ ์ˆซ์ž๋ฅผ ์›์†Œ๋กœ ๊ฐ€์ง€๋Š” ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ๋ฆฌํ„ดํ•ด์ฃผ์„ธ์š”. ์˜ˆ๋ฅผ๋“ค์–ด n์ด 12345์ด๋ฉด [5,4,3,2,1]์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. """ def solution(n): answer = [] s = str(n) l = len(s) - 1 for i in range(l,-1,-1): answer.append(int(s[i])) return answer a = solution(12345) print(a)
stack = [None,None,None,None,None] top = -1 # push top += 1 stack[top] = 'A' top += 1 stack[top] = 'B' top += 1 stack[top] = 'C' print(stack) # pop data = stack[top] print(data) stack[top] = None top -= 1 print(stack)
""" ๋ฌธ์ž์—ด s๋Š” ํ•œ ๊ฐœ ์ด์ƒ์˜ ๋‹จ์–ด๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ๋‹จ์–ด๋Š” ํ•˜๋‚˜ ์ด์ƒ์˜ ๊ณต๋ฐฑ๋ฌธ์ž๋กœ ๊ตฌ๋ถ„๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ๋‹จ์–ด์˜ ์ง์ˆ˜๋ฒˆ์งธ ์•ŒํŒŒ๋ฒณ์€ ๋Œ€๋ฌธ์ž๋กœ, ํ™€์ˆ˜๋ฒˆ์งธ ์•ŒํŒŒ๋ฒณ์€ ์†Œ๋ฌธ์ž๋กœ ๋ฐ”๊พผ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”. ๋ฌธ์ž์—ด ์ „์ฒด์˜ ์ง/ํ™€์ˆ˜ ์ธ๋ฑ์Šค๊ฐ€ ์•„๋‹ˆ๋ผ, ๋‹จ์–ด(๊ณต๋ฐฑ์„ ๊ธฐ์ค€)๋ณ„๋กœ ์ง/ํ™€์ˆ˜ ์ธ๋ฑ์Šค๋ฅผ ํŒ๋‹จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. ์ฒซ ๋ฒˆ์งธ ๊ธ€์ž๋Š” 0๋ฒˆ์งธ ์ธ๋ฑ์Šค๋กœ ๋ณด์•„ ์ง์ˆ˜๋ฒˆ์งธ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ฒ˜๋ฆฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. """ def solution(s): answer = '' i = 0 for n in s: if n == " ": answer = answer + " " i = 0 else: if i % 2 == 0: answer = answer + n.upper() else: answer = answer + n.lower() i += 1 return answer a = solution("try hello wOrld") print(a)
import sys def getSlope(a, b): return abs((b[1] - a[1]) / (b[0] - a[0])) def maxSlope(points): points.sort() result = 0 for i in range(len(points) - 1): result = max(result, getSlope(points[i], points[i + 1])) return result def main(): n = int(input()) points = [] for i in range(n): line = [int(x) for x in input().split()] points.append((line[0], line[1])) print("%.3lf" % maxSlope(points)) if __name__ == "__main__": main()
#Here are the excercises listed in the 'Try It Yourself' section at the end of Chapter 2: #See Python Crash Course (pages 28-29) for more details on each exercise. #Written By: Kaila Stevenson #Last Edited: 04/27/2019 #2-3. Personal Message first_name = "Kaila" print("Hello, " + first_name + ", would you like to learn some Python today?") #It's getting a little crowded. #Let's make some room! print("________________________\n") #2-4. Name Cases dva_name = "Hana Song" print(dva_name.upper()) print(dva_name.lower()) print(dva_name.title()) #It's getting a little crowded. #Let's make some room! print("________________________\n") #2-5. Famous Quote I print("Isaac Newton said, \"If I have seen further than others, it is by standing on the shoulders of giants.\"") #2-6. Fmaous Quote II famous_person = "Isaac Newton" message = "said, \"If I have seen further than others, it is by standing on the shoulders of giants.\"" print(famous_person +" "+message) #It's getting a little crowded. #Let's make some room! print("________________________\n") #2-7. Stripping Names full_name = " Kaila Stevenson " print("\t" + full_name) print("\n" + full_name) #It's getting a little crowded. #Let's make some room! print("\n") print("\n\t" + full_name) print(full_name.lstrip()) print(full_name.rstrip()) print(full_name.strip()) print("________________________\n") #2-8. Number Eight #Write addition, subtraction, multiplication, and division operations that each result in the number 8. #Addition: print(5+3) #Subtraction: print(100-92) #Multiplication: print(2*4) #Division: print(64/8) print("________________________\n") #2-9. Favorite Number: #Store your favorite number in a variable. Then, using that variable, create a message that reveals your favorite number. favorite_number = 3 print("My favorite number is..." + str(favorite_number) +"!") print("________________________\n") #2-10. Adding Comments #Add some Comments! :) print("________________________\n")
#3-1. Names: names = ['Ami', 'Christina', 'Tim', 'Elena', 'Bradley', 'Zon', 'Joshua'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4]) print(names[5]) print(names[6]) print("________________________\n") #3-2. Greetings: names = ['Ami', 'Christina', 'Tim', 'Elena', 'Bradley', 'Zon', 'Joshua'] print(names[0] + " is...niftypants!") print(names[1] + " is...awesomesauce!") print(names[2] + " is...swankalicious!") print(names[3] + " is...friendlydendly!") print(names[4] + " is...radical!") print(names[5] + " is...sassypancakes!") print(names[6] + " is...chill!") print("________________________\n") #3-3. Your Own List #Blegh. Cars. cars = ['Honda', 'Mazda', 'Toyota', 'Aston Martin', 'Lambourghini'] print("If I could drive, I would like to own a " + cars[0] + ".") print("If I could drive, I would like to own a " + cars[1] + ".") print("If I could drive, I would like to own a " + cars[2] + ".") print("If I could drive, I would like to own an " + cars[3] + ".") print("If I could drive, I would like to own a " + cars[4] + ".") print("________________________\n") #3-4. Guest List #If you could invite anyone, living or deceased, to dinner, who would you invite? #Make a list that is at least three people of who you would like to invite to dinner. #Then use your list to print a message to each person, inviting them to dinner. guests = ['J.K. Rowling', 'Elton John', 'Marie Curie', 'Ada Lovelace', 'Isaac Newton', 'Thor'] print("Dear " + guests[0] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[1] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[2] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[3] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[4] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[5] + ": \nPlease attend my dinner party!\n") print("________________________\n") #3-5. Changing Guest List guests = ['J.K. Rowling', 'Elton John', 'Marie Curie', 'Ada Lovelace', 'Isaac Newton', 'Thor'] cannot_attend = guests.pop(0) print("Oh noooooo! " + cannot_attend + " can't make it. Well, Seanan McGuire is the better author anyway. What was I thinking?") print(guests) guests.append('Seanan McGuire') print("Here is the new and improved guest list...") print(guests) print("Dear " + guests[0] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[1] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[2] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[3] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[4] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[5] + ": \nPlease attend my dinner party!\n") print("________________________\n") #3-6. More Guests! print("We went on OfferUp and found a bigger dinner table! Let's invite MOAR PEOPLE!!!") guests.insert(0, 'Albert Einstein') guests.insert(3, 'Hermione Granger') guests.append('Twilight Sparkle') print(guests) print("Dear " + guests[0] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[1] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[2] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[3] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[4] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[5] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[6] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[7] + ": \nPlease attend my dinner party!\n") print("Dear " + guests[8] + ": \nPlease attend my dinner party!\n") #3-7. Shrinking Guest List: print("Two-day shipping costs HOW much?! Consarnit, OfferUp! ALright, looks like we can only invite two.") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) rescind_invite = guests.pop(0) print("Sorry, " + rescind_invite + ", but you are the weakest dinner guest. Good-bye!") print(guests) print("Luckily, " + guests[0] + " and " + guests[1] + " are of Superior Dinner Guest Quality.") print(guests[0] + ", you are still invited! Please attend my dinner party. <3") print(guests[1] + ", you are still invited! Please attend my dinner party. <3") del guests[0] del guests[0] print(guests) print("________________________\n") #3-8. Seeing the World # Think of at least FIVE places in the world you'd like to visit. #Store locations in a list & print: locations = ['ireland', 'scotland', 'greece', 'portugal', 'brazil'] print(locations) #Apply the sorted function: print(sorted(locations)) #Show that your list is still stored in its original order by printing it again print(locations) #Print your list in reverse using sorted Function print(sorted(locations, reverse = True)) #Show that your list is still stored in its original order by printing #it again: print(locations) #Use reverse() Method to sort your list in reverse order & print to #show that the order has changed: locations.reverse() print(locations) #Use reverse() Method to change the order of your list agian & print to #show the list back in its original order: locations.reverse() print(locations) #Use sort() Method to change your list so it's stored in alphabetical #order & print the list to show that the order has been changed: locations.sort() print(locations) #Use sort() Method to change your list so that it's stored in reverse #alphabetical order & print the list to show that the order has changed: locations.sort(reverse = True) print(locations) print("________________________\n") #3-9 Dinner Guests #Using one of the programs from Exercises 3-4 through 3-7, use len() #Function to print a message indicating the number of people attending #your dinner party: guests = ['J.K. Rowling', 'Elton John', 'Marie Curie', 'Ada Lovelace', 'Isaac Newton', 'Thor'] print(len(guests)) print('There are ' + str(len(guests)) + ' guests attending my dinner party') print("________________________\n") #3-10. Every Function #Think of something you could store in a list. Write a program that #creates a list containing these items & then uses each Function #contained in this chapter at least once. print("________________________\n") #3-11. Intentional Error #If you haven't received an index error in one of your programs yet, try #to make one happen. Change an index in one of your programs to produce #an index error. MAKE SURE TO CORRECT THE ERROR BEFORE CLOSING THE #PROGRAM!!! doggos = ['cocker spaniels', 'yorkies', 'golden retrievers', 'labradoodles', 'westies', 'australian shepherds'] print(doggos[5])
#!/usr/bin/env python def is_vowel(s): length = 0 vowel = ["a", "e", "i" ,"o", "u"] for itm in s: length +=1 if length == 1: if itm in vowel: print "yes it is vowel " else: print "no this is not a vowel" else: print " Entered input is not a single character " return length if __name__=="__main__": ch = str(raw_input("Enter a single charchter: ")) is_vowel(ch)
# ###1: # def info(name, hometown, skill): # print("This is ", name, " of ", howetown, " undefeated in ", skill, "!") # # ###2: # def p_suggest(p_old): # if p_old > 100: # p = p_old*1.05 # else: # p = p_old*1.1 # print("The total price is suggested to be", p, " when the price is ", p_old) # # p_suggest(20) # ###3: # import random # list = ["rich", "smart", "lucky", "super strength"] # print(random.choice(list)) ###4: # def count(n, m): # list = [] # for i in range(n, m+1, 1): # list.append(i) # print(list) # # count(3, 10) ###5: # def up_case(): # string = str(input("what's the word?")) # print(string.upper()) # up_case() # ###6: def roversprak(): string = str(input("what's the word?")) l = list(string) lnew = "" for i in l: print(i) if i not in ["a", "e", "i", "o", "u"]: lnew += i + "o" + i else: lnew += i print(lnew) roversprak()
""" Write a function that recursively walks through a directory, printing its contents. Indent with spaces based on recursion depth. (max 10 lines) """ from pathlib import Path def show_path(path, level=0): if not path.is_dir(): return for p in path.iterdir(): print("{}{}".format(" " * level, p.name)) if p.is_dir(): show_path(p, level + 1) if __name__ == "__main__": show_path(Path("/usr/local/lib"))
import pygame from mazeSolver import * class MazeSolverRecursive(MazeSolver): def __init__(self, maze): super().__init__(maze) self.current = self.start print(self.current, self.end) # set the state self.state = [[0 for y in range(self.height)] for x in range(self.width)] def _can_step(self, location): return not self.maze[location[0]][location[1]] def _in_path(self, location): return location in self.path def _valid_next_step(self, location): ''' determine if the next attempted location is open and is not in the path previously traversed ''' if not self._valid_loc(location): return False if not self._can_step(location): return False if self._in_path(location): return False return True def step(self): if self.complete or self.current == self.end: self.complete = True return cell_state = self.state[self.current[0]][self.current[1]] # move into the next state self.state[self.current[0]][self.current[1]] += 1 if (cell_state >= 4): self.current = self.path.pop() return elif (cell_state == 0): # try left next_step = (self.current[0] + 1, self.current[1]) elif (cell_state == 1): # try right next_step = (self.current[0] - 1, self.current[1]) elif (cell_state == 2): # try up next_step = (self.current[0], self.current[1] - 1) elif (cell_state == 3): # try down next_step = (self.current[0], self.current[1] + 1) else: print("something went wrong / unsolvable") # print(self.path) # move into the next square if it's open if self._valid_next_step(next_step): self.path.append(self.current) self.current = next_step else: self.step() # move again if the last step failed pass def draw(self, surface, scale, offset): ''' draw the solving process on the maze ''' line_path = [(x * scale[0] + offset[0], y * scale[1] + offset[1]) for x, y in self.path] line_path.append((self.current[0] * scale[0] + offset[0], self.current[1] * scale[1] + offset[1])) pygame.draw.lines(surface, (0, 0, 0), False, line_path, 3)
#this program says hello and asks to print my age print ('Hello World') print ('what is your name?') myName = input() print ('nice to have you here ' + myName) print ('the length of your name is ') print (len(myName)) print ('what is your age?') myAge = input() myAge = int(myAge) + 1 myAge = str(myAge) print ('you will be ' + myAge + ' after one year!')