blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
a16a99abd5d197bb93f5d17c11d014c27a8424d3
mit-mc-clas12/clas12osg
/client/options.py
1,066
3.625
4
# Import packageds/modules import argparse # This function will return all command line arguemnts as an object def get_args(): # Initalize an argparser object. Documentation on the argparser module is here: # https://docs.python.org/3/library/argparse.html argparser = argparse.ArgumentParser(prog='Submit', usage='%(prog)s [options]') # adding argument nargs='+' would make this option an array argparser.add_argument('scardFile', metavar='scard', type=str, help='Steering card text file') # Add ability for user to specify that they want to use SQLite, instead of MySQL database # Also, lets user specify the name and path of the SQLite DB file to use argparser.add_argument('--sqlite', help="use SQLITE file as DB", type=str, default=None) # Boolean arguement of using TEST MySQL DB or the main MySQL DB argparser.add_argument('--test', action='store_true', help='Use table CLAS12TEST instead of default CLAS12OCR', default=False) # Convert the arguement strings into attributes of the namespace args = argparser.parse_args() return args
9f94ef405e1ec63735e1e17bca483e706a86b3f9
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/continuedenemeleri.py
126
3.953125
4
liste = list(range(10)) for x in liste: if(x==3 or x== 6): continue print(x,"için değer sağlanmadı")
616234224c32a4d65e39ccc22ec1a7ae629adc20
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/atm_mak.py
815
3.5625
4
print("""************************* ATM Makinesine Hoşgeldiniz. işlemler; 1. Bakiye Sorgulama 2. Para Yatırma 3. Para Çekme Programdan çıkmak için "q" tuşlayın. *********************""") bakiye=1000 while True: işlem=input("İşlem Girin:") if(işlem=="q"): print("Yine Bekleriz...") break elif(işlem=="1"): print("Bakiye : {} tl dir".format(bakiye)) elif(işlem=="2"): miktar=int(input("miktar girin")) print("Yeni bakiye : {}".format(bakiye+miktar)) bakiye+=miktar elif(işlem=="3"): miktar=int(input("miktar girin")) if(bakiye-miktar<0): print("Bakiye yetersiz") continue bakiye-=miktar else: print("Geçersiz İşlem....")
4ed1796d9ce52c82fa6a4c7b79f706567ccd38db
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/basithesapmak.py
635
4.0625
4
print("""************************* Basit Hesap Makinesi Programı İşlemler; 1.Toplama İşlemi 2.Çıkarma İşlemi 3.Çarpma İşlemi 4.Bölme İşlemi ************************* """) a=int(input("Birinci Sayı:")) b=int(input("İkinci Sayı:")) işlem=input("İşlemi giriniz:") if (işlem=="1"): print("{} ile {} toplamı = {}".format(a,b,a+b)) pass elif(işlem=="2"): print("{} ile {} farkı = {}".format(a,b,a-b)) elif(işlem=="3"): print("{} ile {} çarpımı = {}".format(a,b,a*b)) elif(işlem=="4"): print("{} ile {} bölümü = {}".format(a,b,a/b)) else: print("Geçersiz İşlem")
388977d7fb69ba87b4074e8e31afe89d45b7a1fc
mebaysan/LearningKitforBeginners-Python
/ozelMethodlar.py
809
4.03125
4
class Fruits(): def __init__(self,name,calories): # bu sınıf initialize olduğunda yani türetildiğinde içine gelen parametreler bu sınıfın attribute'ları olacak self.name = name self.calories = calories def __str__(self): # bu sınıf türetildiğinde instance.name demeden bize bu sınıfın name'ini döndürür(burada öyle yazdığımız için bkz. 15. satır) return self.name def __len__(self): # bu sınıf türetildiğinde instance.calories demeden bize bu sınıfın calories'ini döndürür(burada öyle yazdığımız için bkz. 16. satır) return self.calories fruit = Fruits("banana",300) print(fruit) print(len(fruit)) # daha detaylı bilgi için google'da arama yapabilirsiniz. Diğer özel methodlara daha rahat ulaşırsınız
9a95bd01ae50049a5a8ecf46bf7d0f0ecd8d9e7d
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/fordöngüdenemeleri.py
805
3.78125
4
print("for döngü denemeleri") liste=[1,2,3,4,5,6] for denelem in liste: print(denelem) print("**********************") liste1=[2,123,132,432,123,543,753,123,76,986,10980,123,6,7,8,88,12,43,54] toplam = 0 print(liste1,"\nBu liste için:") for eleman in liste1: toplam = toplam + eleman print("Toplam: {} Eleman: {}".format(toplam,eleman)) print("****************************") liste2=[123,231,531,123,513,647,8975,123321,4452,124123,2,4,12,24,34,45,56,67,78] for cift in liste2: if(cift%2==0): print(cift) print("*************************************") x="Sanane Lan Mal" for harf in x: print(harf) print("*********************************") x="Sanane Lan Mal" for harf in x: print(harf*3) print("*****************************")
7ea8ef1011dbc1b781cf98c8f93dc4f079b0fcfc
mebaysan/LearningKitforBeginners-Python
/python_ders10_ileriseviye_veriyapıları_objeler/ileriseviye_kümeler.py
3,958
4.34375
4
print(""" İleri Seviye Kümeler (Sets) Kümeler, matematikte olduğu gibi bir elemandan sadece bir adet tutan bir veritipidir. Bu açıdan kullanıldıkları yerlerde çok önemli bir veritipi olmaktadırlar. x = set() # boş küme aynı zamanda x={\\1,2,3,1,2,3,1,2,3} dersekte küme oluşur yani {\\} süslü parantez liste = [1,2,3,3,1,1,2,2,2] # Aynı elemanı birçok defa barındıran bir liste x = set(liste) # Veri tipi dönüşümü print(x) ÇIKTISI: """) liste=[1,2,3,3,1,1,2,2,2] x=set(liste) print(x) print(""" y = set("Python Programlama Dili") # Aynı karakterler tek bir karaktere indirgendi. print(y) ÇIKTISI: """) y = set("Python Programlama Dili") print(y) print(""" For döngüsüyle Gezinmek Kümeler de tıpkı sözlükler gibi sırasız bir veri tipidir. Bunu for döngüsüyle görebiliriz. z= {"Python","Php","Java","C","Javascript"} for i in z: print(i) ÇIKTISI: """) z= {"Python","Php","Java","C","Javascript"} for i in z: print(i) print(""" Kümelerin Metodları Eleman Eklemek : add() metodu Kümeye eleman eklemimizi sağlar. Aynı eleman eklenmeye çalışırsa hata vermez ve herhangi bir ekleme işlemi yapmaz. x={1,2,3,4} x.add(4) -> şeklinde kullanılır ***************************************************** difference() metodu: Bu metod birinci kümenin ikinci kümeden farkını döner. küme1.difference(küme2) # Küme1'in Küme2'den farkı küme1={1,2,3,4,5,6,-1,-2,-16} küme2={2,3,4,5,6,7} küme1.difference(küme2) -> kullanım bu şekildedir. ************************************************************* difference_update() metodu Bu metod birinci kümenin ikinci kümeden farkını dönerek birinci kümeyi bu farka göre günceller. küme1.difference_update(küme2) # Küme1'in Küme2'den farkı küme1={1,2,3,4,5,6,-1,-2,-16} küme2={2,3,4,5,6,7} küme1.difference_update(küme2) -> şeklinde kullanılır/kısaca küme1 ve küme 2'nin farkının küme1'e atanması **************************************************************** discard() metodu İçine verilen değeri kümeden çıkartır. Eğer kümede öyle bir değer yoksa, bu metod hiçbir şey yapmaz(Hata vermez). küme1 = {1,2,3,4,5,6} küme1.discard(7) -> şeklinde kullanılır ********************************************************** intersection() metodu Bu metod iki kümenin kesişimleri bulmamızı sağlar. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.intersection(küme2) -> şeklinde kullanılır ************************************************************** intersection_update() metodu Bu metod birinci kümeyle ikinci kümenin kesişimlerini bulur ve birinci kümeyi bu kesişime göre günceller. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.intersection_update(küme2) -> şeklinde kullanılır ************************************************************** isdisjoint() metodu Bu metod, eğer iki kümenin kesişim kümesi boş ise True, değilse False döner. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.isdisjoint(küme2) -> şeklinde kullanılır ************************************************** Alt kümesi mi ? : issubset() metodu Bu metod , birinci küme ikinci kümenin alt kümesiyse True, değilse False döner. küme1 = {1,2,3} küme2 = {1,2,3,4} küme1.issubset(küme2) -> şeklinde kullanılır ****************************************************** union() metodu Bu metod, iki kümenin birleşim kümesini döner. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.union(küme2) -> şeklinde kullanılır *************************************************************** Birleşim Kümesi ve update : update() metodu Bu birinci kümeyle ikinci kümenin birleşim kümesini döner ve birinci kümeyi buna göre günceller. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.update(küme2) -> şeklinde kullanılır """)
d420487746d453766dba6c07946925311fba04ce
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/döngüler ödev dosyası/100ekadar3ebölünensayılar.py
382
3.828125
4
print(""" ************************* 1'den 100'e kadar olan sayılardan sadece 3'e bölünen sayıları ekrana bastırın. Bu işlemi continue ile yapmaya çalışın ************************* for i in range(1,101): if (i % 3 != 0): continue print(i) """) for i in range(1,101): if (i % 3 != 0): continue print(i)
81651c545870eb4c63fc32d1efa43f939755e07c
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/listcomprehension.py
863
3.890625
4
liste1=[1,2,3,4,5,6,7,8,9] liste2=list() for eleman in liste1: liste2.append(eleman) print(liste1,liste2) print("***************************") liste3=[1,2,3,4,5] liste4=[eleman for eleman in liste3] print(liste4) print("***********************") liste5=[3,4,5,6] liste6=[z*2 for z in liste5] print(liste6) print("***********************") a="BAYSAN" denlist=[k*2 for k in a] print(denlist) print("*******************************") denemelistesi=[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]] for v in denemelistesi: print("denemelistesi içindeki v değeri : ", v) print("*********************") denemelistesi=[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]] for v in denemelistesi: for m in v: print("v içindeki m değeri : ", m) print("LISTCOMPREHENSION KAYNAK KODLARDA DAHA DETAYLI")
13b2b73f35314cd4c54953ab352aecccc3536064
PC-reloaded/dsmp-pre-work
/Et-tu-Preetus/code.py
1,289
3.6875
4
# -------------- # Code starts here class_1=['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2=['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class= class_1+class_2 #new_class =class_1.extend(class_2) print(new_class) #n=class_1.append('preeti') #print(class_1) new_class.append("Peter Warden") print(new_class) new_class.remove("Carla Gentry") print(new_class) # Code ends here # -------------- # Code starts here courses= {'Math': 65, 'English':70, 'History':80, 'French':70, 'Science':60} #Math=courses['Math'] #English= courses['English'] #History=courses['History'] #French= courses['French'] #Science=courses['Science'] #total=Math + English + History + French+ Science total=sum(courses.values()) print(total) percentage=total*100/500 print(percentage) # Code ends here # -------------- # Code starts here mathematics= {'Geoffrey Hinton': 78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75} topper= max(mathematics,key=mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here #first_name=topper[0:6] first_name=topper.split()[0] #print(first_name) last_name=topper.split()[1] #print(last_name) full_name=last_name+" "+first_name certificate_name=full_name.upper() print(certificate_name) # Code ends here
fa28369256363fc99fc9dbc34c8759d4b257226c
huai8551516/PythonPractice
/practice/3.py
559
3.765625
4
#!/usr/bin/python #-*- coding: utf-8 -*- #Author: hz #Environment: Linux & Ubuntu 17.10 #Filetype: Python Source Code #Tool: Vim #Date: #Decription: 一个整数,它加上100和加上268后都是一个完全平方数, # 请问该数是多少? from math import sqrt max = int(raw_input("你要求n以内的整数:")) num_seq = [] for i in range(max): num1 = int(sqrt(i + 100)) num2 = int(sqrt(i + 268)) if num1 ** 2 == i + 100 and \ num2 ** 2 == i + 268: num_seq.append(i) print num_seq
7992912bc6663e6485469094e125dc8d624a0ea0
epitaciosilva/estudosProgramacao
/lp2/atividadeHeranca/questao2/figura.py
594
3.609375
4
class Figura: def __init__(self, lado1, lado2): self.lado1 = lado1 self.lado2 = lado2 def __str__(self): return "Lado 1: {} \nLado 2: {} \nÁrea da figura: {}".format(self.lado1, self.lado2, self.calcularArea()) def calcularArea(self): return self.lado1*self.lado2 @property def lado1(self): return self.__lado1 @lado1.setter def lado1(self, lado1): self.__lado1 = lado1 @property def lado2(self): return self.__lado2 @lado2.setter def lado2(self, lado2): self.__lado2 = lado2
93e646aecd279d4479ad3e285a64307fec5f1560
epitaciosilva/estudosProgramacao
/lp2/atividadePolimorfismo/questao1/main.py
428
3.578125
4
class Viajante: def __init__(self, cls): self.__cls = cls def dizerOla(self): self.__cls.dizerOla(self) class Brasileiro(Viajante): def dizerOla(self): print("Olá") class Espanhol(Viajante): def dizerOla(self): print("Hola") class Americano(Viajante): def dizerOla(self): print("Hello") v1 = Viajante(Americano) v2 = Viajante(Espanhol) v3 = Viajante(Brasileiro) v1.dizerOla() v2.dizerOla() v3.dizerOla()
6a05ff59530c8b61f12c66d45a5a1d116a68f48b
Nick-Ohman/Intro-Python-II
/src/adv.py
5,620
3.5
4
from room import Room from player import Player from items import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] ## create items items = { "food": Item("Sherbet Lemon", "You might need food if you get lost"), "water": Item("Water", "You might be thirsty with all this walking"), "Light": Item("Light of Eärendil's star", "May it be a light to you in dark places, when all other lights go out."), "Sword": Item("sword of gondor", "Protection for yourself"), "goldpiece": Item("Gold Piece", "Found your first piece"), "helmate": Item("Chest Armour", "Protection") } room["foyer"].items = [items["goldpiece"], items["Light"]] room["overlook"].items = [items["Sword"], items["food"]] room["narrow"].items = [items["water"]] room["treasure"].items = [items["water"]] # # Main # # Make a new player object that is currently in the 'outside' room. # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. # directions will ne N S E W # follow step 1 define room # after that take a name prompt needhelp = ''' \n How to play: \n\n, Type \'n\' to move north\n, Type \'s\' to move south\n, Type \'w\' to move west\n, Type \'e\' to move east\n, Type \'q\' at any time to quit\n Type \'h\' for help ''' def start_game(): player = Player(name = input('Enter name to start '), current_room = room['outside'], items = [items["helmate"]]) print(player) def grabdrop(): choice = input(f'This room has: {player.current_room.printitems()} \n ') print(choice) if choice == 'ok': pass elif choice == 'get': player.getItem(f'{choice[5:]}') elif choice == 'drop': player.dropItem(f'{choice[6:]}') else: pass # while not(player.in_treasure): while not(player.in_treasure): gamer_input = input( "\nWhich direction would you like to move? ") print('\n') if gamer_input == 'q': print('\n !! Thanks for playing !!\n') exit() elif gamer_input == 'h': print(needhelp) elif gamer_input == 'n': try: player.current_room = player.current_room.n_to if player.current_room.name == "Treasure Chamber": print(f' You are now in {player.current_room.name}, {player.current_room.description}') print('You have found the treasure') won_game = input('Would you like to play again? Type y for yes, n for no... ') if won_game == 'w': start_game() else: print('\n !! Thanks for playing !!\n') exit() else: print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print("There is no room to the north") gamer_input elif gamer_input == 's': try: player.current_room = player.current_room.s_to print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print('There is no room to the south.') gamer_input elif gamer_input == 'e': try: player.current_room = player.current_room.e_to print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print('There is no room to the east.') elif gamer_input == 'w': try: player.current_room = player.current_room.w_to print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print('There is no room to the west.') gamer_input start_game()
d7cb0e91a9a37a49840f85845d499a92cafb85ca
cwang-armani/learn-python
/04 python核心/10 闭包.py
786
4.03125
4
''' 如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。 一个闭包就是你调用了一个函数A,这个函数A返回了一个函数B的引用给你。 这个返回的函数B就叫做闭包。你在调用函数A的时候传递的参数就是自由变量 ''' def test(number): print("---1---") def test_in(number2): print("---2---") print(number+number2) print("---3---") return test_in a = test(100) a(20) a(100) a(200) ''' #闭包可以简化调用过程,有些参数只需调用一次 def test(a,b): def test_in(x): print(a*x+b) return test_in line1 = test(1,1) line2 = test(10,4) line1(0) line2(0) '''
5327645fe2ad9a4bff50f3347cc8937c7c5b8645
cwang-armani/learn-python
/02 面向对象/8 继承.py
512
3.6875
4
class Animal(): def eat(self): print("吃") def drink(self): print("喝") def sleep(self): print("睡") def run(self): print("跑") '''继承父类的名字,直接打在里面,前面定义的就不用重写''' '''调用方法 先子类 后父类''' class Dog(Animal): def bark(self): print("汪汪叫") class Cat(Animal): def catch(self): print("抓老鼠") a=Animal() a.eat() wangcai = Dog() wangcai.eat() wangcai.bark() tom=Cat() tom.eat() tom.catch()
1eb433504868fbaa75faaa7bac81000f9431dee6
cwang-armani/learn-python
/09 数据结构与算法/5 栈.py
699
4.1875
4
class Queue(object): '''定义一个栈''' def __init__(self): self.__item = [] def is_empty(self): # 判断列表是否为空 return self.__item == [] def enqueue(self,item): # 入队 self.__item.append(item) return item def dequeue(self): # 出队 return self.__item .pop(0) def size(self): return len(self.__item) if __name__ == "__main__": q = Queue() print(q.enqueue(1)) print(q.enqueue(2)) print(q.enqueue(3)) print(q.enqueue(4)) print("-"*20) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue())
1cb3ec8f915657b3df448ea3f05b7705e69a1823
cwang-armani/learn-python
/04 python核心/15 带有参数的装饰器.py
443
3.703125
4
def func_args(arg): def func(function_name): def func_in(): print("日志 arg = %s"%arg) if arg == "hehe": function_name() function_name() else: function_name() return func_in return func #先执行@func_args("hehe"),返回了func的引用 #test=@func(test) @func_args("hehe") def test(): print("---test---") @func_args("haha") def test2(): print("---test2---") test() test2()
687c1ddb9719b34698ac3cb7f0bbfa158ac35760
cwang-armani/learn-python
/10 MySQL/1 表的创建.py
2,641
3.671875
4
数据库命令: 创建create database 数据库名 charset=utf8; 删除drop database 数据库名; 查看所有数据库:show databases; 使用数据库:use 数据库名; ---------------------------------------- 表命令: create table 表名(列...); 唯一标识的要求:id 类型:int unsigned 约束1:not null 约束2:primary key 约束3:auto_increment 列的格式:列的名称 类型 约束 create table students( -> id int not null primary key auto_increment, -> name varchar(10) not null, -> gender bit default 1, -> birthday datetime, -> isDelete bit default 0, -> ); 查看创建语法:show create table students; 查看表:show tables; 查看表结构:desc students; 修改表:alter table students add|modify|drop 列名 类型 约束; mysql> alter table students add isDelete bit default 0; 删除表:drop table 表名; ---------------------------------------- 添加数据:(必然会新增一行) mysql> insert into students values(0,'郭靖',1,'1990-1-1',0); mysql> insert into students(name,gender) values('黄蓉',0); mysql> insert into students(name,gender,birthday) values('杨过',0,'1989-03-20'); 修改数据: mysql> update students set birthday='1990-1-1' where id = 2; 删除数据: delete from students where id = 3 逻辑删除,并查看: mysql> update students set isDelete=1 where id=3; mysql> update students set isDelete=1 where id=3; 备份: mysql> mysqldump -uroot -p students > ~Desktop/bak.sql 恢复: mysql -uroot -p py31 < bak.sql ---------------------------------------- 外键设置: create table course( course_id varchar(20), deptnames varchar(20), credits int, foreign key(deptnames) references department(dept_name)); create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) ); 外键的级联操作 在删除students表的数据时,如果这个id值在scores中已经存在,则会抛异常 推荐使用逻辑删除,还可以解决这个问题 可以创建表时指定级联操作,也可以在创建表后再修改外键的级联操作 语法 alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade; 级联操作的类型包括: restrict(限制):默认值,抛异常 cascade(级联):如果主表的记录删掉,则从表中相关联的记录都将被删除 set null:将外键设置为空 no action:什么都不做
0ff2bdb2f351f3b15b54683fb4abed165d7f4dfa
cwang-armani/learn-python
/09 数据结构与算法/8 冒泡排序法.py
561
3.921875
4
# coding:utf-8 def bubble_sort(a_list): '''冒泡排序法''' n = len(a_list) for i in range(n-1): count = 0 # 中间的某次已经排序好了,直接跳出循环 for j in range(n-i-1): # 游标 if a_list[j] > a_list[j+1]: a_list[j],a_list[j+1] = a_list[j+1], a_list[j] count += 1 if count == 0: break print(a_list) if __name__ == "__main__": a = [13,45,675,123,7,32,89,312,45432] print(a) bubble_sort(a) '''最优时间复杂度O(n),一次成型''' '''最坏时间复杂度O(n^2)''' '''稳定性好'''
b66fd6478fd1c2a2fa3714dd3f6ce463cea6b48b
lisseta/Algorithm-Analysis_FESAr.
/problemaUno.py
676
3.84375
4
# Solución para el problema N° 1 de Diseño y Análisis de Algoritmos # Autor: SouYui # ! Requiere una lista de elementos tipo str # R Devuelve el indice del primer elemento que su predecesor es menor a él def primerElementoMenor(lista): if(type(lista) == list and len(lista) > 1): for i in range(1, len(lista)): if(len(lista[i]) > len(lista[i - 1])): return [i] else: print("No es una lista, verifique su entrada.") listaPrueba = ["Samuel", "Emilia", "Erick","Samuel", "Emmanuel"] result = primerElementoMenor(listaPrueba) print(f"El índice de la lista donde se encuentra el elemento es: {result}")
c5f0af436ab49400f930ec8436b3264e45f598b8
bobbykwariawan/m26415067
/PR/PR Minggu 4/Python Basic Exercises/list1.py/A.py
180
4.125
4
#!/usr/bin/python def match_ends(words): a=words if len(a)>2 and a[0]==a[len(a)-1]: a=len(a) else: a=0 return a print(match_ends(raw_input('Input words: ')))
ceb2b2a2b5d2a0bd0b2d1d52ce9b4973f5b9559b
UrviMalhotra/Inventory-Management-System
/shop.py
5,071
3.625
4
import json shop=open("shoprecored.json","r") sale=open("sales.json","r") shop_data=shop.read() sale_data=sale.read() record = json.loads(shop_data) record_sale=json.loads(sale_data) shop.close() sale.close() def check_inventory_item(): print("\n\n") Item_ID = input("Enter Item ID: ") if Item_ID in record.keys(): print(f"Yes!! {Item_ID} is present") print(f"Product ID: {Item_ID}") print(f"Product Name: " ,record[Item_ID]["Item Name"]) print(f"Price: " ,record[Item_ID]["Price"]) print(f"Quantity: " ,record[Item_ID]["Quantity"]) else: print(f"No!! {Item_ID} is not present") def update_item_inventory(): print("\n\n") Item_ID = input("Enter Item ID: ") if Item_ID in record.keys(): print(f"Product ID: {Item_ID}") print(f"Product Name: " ,record[Item_ID]["Item Name"]) print(f"Price: " ,record[Item_ID]["Price"]) print(f"Quantity: " ,record[Item_ID]["Quantity"]) change=int(input("\nPress:\n1. Update Price:\n2.Update Quantity: ")) if change==1: pr=int(input("Enter updated Price: ")) record[Item_ID] = {"Item Name": record[Item_ID]["Item Name"], "Quantity": record[Item_ID]["Quantity"], "Price": pr, "Weight": record[Item_ID]["Weight"], "Category": record[Item_ID]["Category"], "Brand": record[Item_ID]["Brand"] } update_inventory() elif change==2: qn=int(input("Enter updated Quantity: ")) record[Item_ID] = {"Item Name": record[Item_ID]["Item Name"], "Quantity": qn, "Price": record[Item_ID]["Price"], "Weight": record[Item_ID]["Weight"], "Category": record[Item_ID]["Category"], "Brand": record[Item_ID]["Brand"] } update_inventory() else: print("Invalid option selected") else: print(f"No!! {Item_ID} is not present") def check_sales_item(): print("\n\n") count=0 mob = input("Enter Mobile No: ") for m_key in record_sale: if(record_sale[m_key]['Mobile']==mob): count=1 if count==1: print(f"Customer ID: " ,m_key) print(f"Mobile: " ,record_sale[m_key]["Mobile"]) print(f"Product Name: " ,record_sale[m_key]["Customer_Name"]) print(f"Mobile: " ,record_sale[m_key]["Mobile"]) else: print(f"No customer with {mob} exists") def add_data(): print("\n\n") Item_ID = input("Enter Item ID: ") Item_Name = input("Enter Item Name: ") qn = int(input("Enter Quantity: ")) pr = int(input("Enter Price: ")) w = input("Enter Weight: ") cate = input("Enter Category: ") brand = input("Enter Brand: ") record[Item_ID] = {"Item Name": Item_Name, "Quantity": qn, "Price": pr, "Weight": w, "Category": cate, "Brand": brand } update_inventory() def check_inventory(): print(record) def check_sales(): print(record_sale) def purchase(): print("\n\n") name=input("Your name please: ") phone=input("Your number please: ") Item_ID = input("Enter Item ID: ") if Item_ID in record.keys(): qn = int(input("Enter Quantity: ")) if qn<=int(record[Item_ID]["Quantity"]): print(f"Product ID: {Item_ID}") print(f"Product Name: " ,record[Item_ID]["Item Name"]) print(f"Price: " ,record[Item_ID]["Price"]) print(f"Total Amount: " ,record[Item_ID]["Price"]*qn) record[Item_ID]["Quantity"]=record[Item_ID]["Quantity"] - qn #print(f"Updated Quantity " ,record[Item_ID]["Quantity"]) update_inventory() record_sale[len(record_sale)+1] = {"Customer_Name": name, "Mobile": phone, "Item ID": Item_ID, "Quantity": qn, "Total_amount": record[Item_ID]["Price"]*qn } update_sales() else: print("Not that amount of item in stock") else: print(f"No item with {Item_ID} exists") def update_inventory(): js = json.dumps(record) fd = open("shoprecored.json",'w') fd.write(js) fd.close() def update_sales(): js = json.dumps(record_sale) fd1 = open("sales.json",'w') fd1.write(js) fd1.close() print("\n\n Welcome to Inventary Management System\n\n") c=1 while(c==1): print("\n\n MAIN MENU\n\n") switch=int(input("Press:\n1. Check Inventary record\n2. Check Sales record\n3. Add item in inventory\n4. Make an Purchase\n5. Check Inventary Item\n6. Check Customer details\n7. Update Inventary Item\n8. Exit: ")) if(switch==1): check_inventory() elif switch==2: check_sales() elif switch==3: add_data() elif switch==4: purchase() elif switch==5: check_inventory_item() elif switch == 6: check_sales_item() elif switch ==7: update_item_inventory() elif switch == 8: c=0 else: ("Undefined Input")
5de9cfb12de98f8b6a7c76464769c66a3114981b
cesaralmeida93/python_settings
/src/start.py
303
3.828125
4
def soma(num_1: int, num_2: int) -> int: """Somando dois numeros :param - num_1: primeiro numero da soma - num_2: segundo numero da soma :return - Soma entre dois numeros """ soma_dois_numeros = num_1 + num_2 return soma_dois_numeros SOMA_DOIS_NUMEROS = soma(1, 2)
9b9c346df8541a4277617683cc140410632d6fe1
casteluc/space-invaders
/src/entities.py
3,271
3.546875
4
import pygame from pygame.locals import * FRIEND, ENEMY = 0, 1 UP, DOWN = 1, -1 START, STOP = 0, 1 RIGHT, LEFT = 0, 1 BIG, SMALL = 0, 1 # Loads game images shipImg = pygame.image.load("C:\casteluc\coding\spaceInvaders\img\ship.png") enemyImg = pygame.image.load("C:\casteluc\coding\spaceInvaders\img\enemy.png") brokenEnemy = pygame.image.load("C:\casteluc\coding\spaceInvaders\img\enemyBroken.png") class Ship(): def __init__(self, size, x, y, speed): self.size = size self.x = x self.y = y self.speed = speed self.hasAmmo = False self.isAlive = True self.hitBox = (self.x + 7, self.y + 5, 50, 54) # Moves the ship and updates its hitbox def move(self, direction): if direction == RIGHT: self.x += self.speed else: self.x -= self.speed self.hitBox = (self.x + 7, self.y + 5, 50, 54) # Draws the ship in the screen def draw(self, screen): screen.blit(shipImg, (self.x, self.y)) class Enemy(Ship): def __init__(self, size, x, y, speed, life): super().__init__(size, x, y, speed) self.direction = RIGHT self.life = life self.previousDirection = LEFT self.hitBox = (self.x + 3, self.y + 8, 57, 45) if life == 2: self.type = BIG else: self.type = SMALL # Move the enemy ship and updates its hitbox def move(self, direction): if direction == RIGHT: self.x += self.speed elif direction == LEFT: self.x -= self.speed elif direction == DOWN: self.y += 10 self.hitBox = (self.x + 3, self.y + 8, 57, 45) # Draw enemy on screen def draw(self, screen): if self.type == BIG: if self.life == 2: screen.blit(enemyImg, (self.x, self.y)) else: screen.blit(brokenEnemy, (self.x, self.y)) else: screen.blit(enemyImg, (self.x, self.y)) class Bullet(): def __init__(self, ship, direction, shooter): self.size = (2, 20) self.surface = pygame.Surface(self.size) self.surface.fill((255, 255, 255)) self.x = ship.x + (32) self.y = ship.y self.speed = 5 self.inScreen = True self.hasCollided = False self.direction = direction self.shooter = shooter if self.shooter == ENEMY: self.surface.fill((255, 0, 0)) # Moves the bullet and checks if its of the screen def move(self): if self.y + 10 > 0 or self.y + 10 > 600: self.y -= self.speed * self.direction else: self.inScreen = False # Draws the bullet in the screen def draw(self, screen): screen.blit(self.surface, (self.x, self.y)) # Checks if the bullet collided with an enemy. Returns True # if it collided and False if not def collidedWith(self, ship): onWidth = self.x < ship.hitBox[0] + ship.hitBox[2] - 1 and self.x > ship.hitBox[0] - 2 onHeight = self.y < ship.hitBox[1] + ship.hitBox[3] and self.y + 20 > ship.hitBox[1] if onWidth and onHeight: return True else: return False
2588dfde5582125de98eb50ab20e76762e01be8d
pragatij17/General-Coding
/Day 1/si_ci.py
447
4
4
# Create a program to calculate simple interest and compound interest, take input from the user. def simple_interest(p, r, t): si = (p * r * t)/100 return si def compound_interest(p, r, t): amount = p*(pow((1+r/100),t)) ci = amount-p return ci p=int(input('The principal is: ')) t=float(input('The time period is: ')) r=int(input('The rate of interest is: ')) print(simple_interest(p, r, t)) print(compound_interest(p, r, t))
985bb44337d98dcf1b07803b84ae7417f48c0015
pragatij17/General-Coding
/Day 6/python/sum_of_numbers.py
256
4.25
4
# Write a program that asks the user for a number n and prints the sum of the numbers 1 to n. def sum_of_number(n): sum = 0 for i in range(1,n+1): sum =sum + i return sum n = int(input('Last digit of sum:')) print(sum_of_number(n))
67e3db0c3723dccacf09bbdcf56f8e4aae14cbcd
CarelHernandez/chatter-bot
/Chatter bot.py
1,506
3.984375
4
print(" hi my name is Car-two-el, I am here to help you get comftorable with talking to people so dont get intrigued. So whats your name?) Name == input () print (" Hi there" + Name + " so I heard your shy? its okay let me help you get comfortable?" ) answer = input () if answer == "okay" or answer == "fine" answer == "I guess" answer == "ok" print ("okay then lets get started" ) elif anser == "no" or answer == "na" or answer == "its okay im fine" break print (" what sport do you like?" sport == input() print (" okay, imagine I was playing" + sport + " and you wanted to play with me, how would you approach me?") input () if input == "idk" or input == "nothing" print (" come on you got this, just think") print (" ok let try actually having a normal conversation, just relax and breathe." ) print (" lets start off again by, What is something cool about you that you think someone would be amazed about?") input () if input !== "idk" print " that's amazing, yeah share that with someone new you meet! with me I would say that I am a 17 year old robot made by a human to help a human" ) print (" would you need anymore help with being comfortable while interacting with humans?" ) Hmm = input () if Hmm == "no thanks" or Hmm == "no" or Hmm == "na" or Hmm == "nope" break print (" I am gonna go to rest, i am over heating, have a good day!")
79580d10f09043e7703f0f49c88116037f0c4e48
kartikhans/competitiveProgramming
/Min_Stack.py
643
3.578125
4
class MinStack: def __init__(self): """ initialize your data structure here. """ self.arr=[] self.prr=[] self.mini=100000000000 def push(self, x: int) -> None: self.arr.append(x) if(x<self.mini): self.mini=x self.prr.append(self.mini) def pop(self) -> None: self.arr=self.arr[:-1] self.prr=self.prr[:-1] if(len(self.prr)>0): self.mini=self.prr[-1] else: self.mini=100000000000 def top(self) -> int: return(self.arr[-1]) def getMin(self) -> int: return(self.prr[-1])
448d642fc8db9bd6bc2f4fd654cff693dcc77f25
kartikhans/competitiveProgramming
/missing_Number.py
192
3.65625
4
def missingNumber(nums): n=len(nums) arr=[0]*(n+1) for i in nums: arr[i]=1 for i in range(n+1): if(arr[i]==0): return(i)
c84859d03e6df77d8575dddd7192f2f36852ba31
RojieEmanuel/intro-python
/102.py
2,170
4.1875
4
weekdays = ['mon','tues','wed','thurs','fri'] print(weekdays) print(type(weekdays)) days = weekdays[0] # elemento 0 days = weekdays[0:3] # elementos 0, 1, 2 days = weekdays[:3] # elementos 0, 1, 2 days = weekdays[-1] # ultimo elemento test = weekdays[3:] # elementos 3, 4 weekdays days = weekdays[-2] # ultimo elemento (elemento 4 days = weekdays[::] # all elementos days = weekdays[::2] # cada segundo elemento (0, 2, 4) days = weekdays[::-1] # reverso (4, 3, 2, 1, 0) all_days = weekdays + ['sat','sun'] # concatenar print(all_days) # Usando append days_list = ['mon','tues','wed','thurs','fri'] days_list.append('sat') days_list.append('sun') print(days_list) print(days_list == all_days) list = ['a', 1, 3.14159265359] print(list) print(type(list)) print('\n\t') # list.reverse() # print(list) ######### print('#############################################################################################################################') print( 'Exercicios - Listas') # Faca sem usar loops ######### # Como selecionar 'wed' pelo indice? print('\n1') print(days_list[2]) # Como verificar o tipo de 'mon'? print('\n2') print(type(days_list[0])) # Como separar 'wed' até 'fri'? print('\n3') print(days_list[2:5]) # Quais as maneiras de selecionar 'fri' por indice? print('\n4') print(days_list[4]) print(days_list[4:5]) # Qual eh o tamanho dos dias e days_list? print('\n5') dias = len(days) listaD= len(days_list) print('tamanho de dias: ', dias) print('tamanho de days_list: ', listaD) # Como inverter a ordem dos dias? print('\n6') print(weekdays[::-1]) # Como atribuir o ultimo elemento de list na variavel ultimo_elemento e remove-lo de list? print('\n 10') ultimo_elemento = list[-1] print(ultimo_elemento) list.remove(list[-1]) print(list) # Como inserir a palavra 'zero' entre 'a' e 1 de list? print('\n7') list.insert(1,'zero') print(list) # Como limpar list? print('\n8') print(list.clear()) # Como deletar list? print('\n9') print() print('######################################### FIM ##############################################################################')
714406f52f4bd8bd2569626d6ac185aadea1e33e
Worcester-Preparatory-School-Comp-Sci/python-2-for-loop-with-input-KurtLeinemann
/PigLatin.py
265
3.921875
4
## Kurt Leinamann Pig Latin September 26 2019 word=input("Pick a word") vowelList=['a','e','i','o','u'] if word[0] in vowelList: print(word +"yay") #yikes... print(print... also didn't need to select a slice of word.. just whole word else: print(word[1:] + word[0] + "ay")
e3c4390df61f4a0bc49568058e76bcbec10b4c24
Ram-cs/Interview-prep-Cracking-the-coding-solutions-by-chapter
/Inheritance.py
1,328
4.03125
4
# class Vehicle: def __init__(self,brake=0, accelerate=0): self.brake = brake self.accelerate = accelerate def accelerate(self, accelerate): self.accelerate = accelerate def brake(self, brake): self.brake = brake class Car(Vehicle): def __init__(self, brake, accelerate): Vehicle.accelerate(accelerate) Vehicle.brake(brake) class Person: def __init__(self): self.firstName = "" self.lastName = "" self.__private = 0 #private member can not access from outside even with the instance of Person Object def assignName(self,first,last): self.firstName = first self.lastName = last def getName(self): return self.firstName + " " + self.lastName class Employee(Person): def __init__(self,first, last, number): self.employee = number Person.__init__(self) Person.assignName(self,first,last) def getName(self): print(Person.getName(self)) print(self.employee) class C: def __init__(self): Person.__init__(self) self.ok = 5 e = Employee("Ram","Yadav", 1001) e.getName() e.firstName = "Changed" e.lastName = "Changes" e.getName() print(e.firstName) print(e.lastName) print(e.employee) Person.getName() c = C() print(c.firstName)
fbe429daf028265ea14c3a945938f8b0b4a2d6f0
Akif-Mufti/Machine-Learning-with-Python
/plot1Barhist.py
522
3.59375
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 26 14:23:46 2017 @author: user """ from collections import Counter from matplotlib import pyplot as plt grades = [83,95,67,54,23] decile = lambda grade:grade // 10*10 histogram = Counter(decile(grade) for grade in grades) plt.bar([x-4 for x in histogram.keys()], histogram.values(),8) plt.axis([-5,105,0,5]) plt.xticks([10*i for i in range(11)]) plt.xlabel("Decline") plt.ylabel("# of students") plt.title("Distribution of Exam one grade") plt.show()
c1503433697543bdd5f5a3bd16ffd47a86574dbd
Akif-Mufti/Machine-Learning-with-Python
/FS3.py
522
3.515625
4
# Feature Extraction with PCA from pandas import read_csv from sklearn.decomposition import PCA # load data filename = 'pima-indians-diabetes.data.csv' names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = read_csv(filename, names=names) array = dataframe.values X = array[:,0:8] Y = array[:,8] # feature extraction pca = PCA(n_components=3) fit = pca.fit(X) # summarize components print("Explained Variance: %s"% fit.explained_variance_ratio_) print(fit.components_)
14acca9d50adbf5c80ae0b1884ec5236410c5138
captain204/Python-notes
/circle_rectangle.py
542
3.8125
4
from circle import Circle from rectangle import Rectangle class ShapeDemo(): @classmethod def main(cls, arg): width = 2 length = 3 radius =10 rectangle= Rectangle(width,length) print("Rectangle with:",width,"Length",length, "Rectangle area",rectangle.area(),rectangle.perimeter()) circle = Circle(radius) print("Circle radius", radius, "Circle area", circle.area,"Circle Perimeter",circle.perimeter()) if __name__ == "__main__": import sys ShapeDemo.main(sys.argv)
b32bde9d8552deda474e649b149e96dda4262915
Tu-Jiawei/For-study
/CNN for mnist.py
3,517
3.859375
4
''' from book 'Tensorflow+Keras 深度学习人工智能实践应用' TensorFlow MNIST数据集,卷积神经网络 ''' import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) def weight(shape): return tf.Variable(tf.truncated_normal(shape,stddev=0.1),name='W') def bias(shape): return tf.Variable(tf.constant(0.1,shape=shape),name='b') def conv2d(x,W): return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') with tf.name_scope('optimizer'): y_label=tf.placeholder("float",shape=[None,10],name="y_label") loss_function=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=y_predict,labels=y_label)) optimizer=tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss_function) with tf.name_scope("evaluate_model"): correct_prediction=tf.equal(tf.argmax(y_predict,1),tf.argmax(y_label,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float")) trainEpochs = 30 batchSize = 100 totalBatchs = int(mnist.train.num_examples/batchSize) epoch_list=[];accuracy_list=[];loss_list=[]; from time import time startTime=time() sess = tf.Session() sess.run(tf.global_variables_initializer()) for epoch in range(trainEpochs): for i in range(totalBatchs): batch_x, batch_y = mnist.train.next_batch(batchSize) sess.run(optimizer,feed_dict={x: batch_x, y_label: batch_y}) loss,acc=sess.run([loss_function,accuracy],feed_dict={x:mnist.validation.images, y_label:mnist.validation.labels}) epoch_list.append(epoch);loss_list.append(loss);accuracy_list.append(acc) print("Trian Epoch:",'%02d'%(epoch+1),"Loss=","{:.9f}".format(loss),"Accuracy:",acc) duration=time()-startTime print("Train Finished takes:",duration) #the loss about epoch %matplotlib inline import matplotlib.pyplot as plt fig=plt.gcf() fig.set_size_inches(10,5) plt.plot(epoch_list,loss_list,label='loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['loss'], loc='upper left') #the accuracy about epoch plt.plot(epoch_list, accuracy_list,label="accuracy" ) fig = plt.gcf() fig.set_size_inches(10,5) plt.ylim(0.8,1) plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend() plt.show() #test model in test datasets of mnist len(mnist.test.images) print("Accuracy:",sess.run(accuracy,feed_dict={x:mnist.test.images,y_label:mnist.test.labels})) prediction_result=sess.run(tf.argmax(y_predict,1),feed_dict={x:mnist.test.images[:50],y_label:mnist.test.labels}) print(prediction_result[:20]) #result show in photoes import numpy as np def show_images_labels_predict(images,labels,prediction_result): fig=plt.gcf() fig.set_size_inches(8,10) for i in range(0,20): ax=plt.subplot(5,5,1+i) ax.imshow(np.reshape(images[i],(28,28)),cmap='binary') ax.set_title("label=" +str(np.argmax(labels[i]))+ ",predict="+str(prediction_result[i]) ,fontsize=9) plt.show() show_images_labels_predict(mnist.test.images,mnist.test.labels,prediction_result) #save the model saver=tf.train.Saver() save_path=saver.save(sess,"saveModel/CNN_model1") print("Model saved in file: %s" % save_path) #export to tensorboard merged=tf.summary.merge_all() train_writer=tf.summary.FileWriter('log/CNN',sess.graph)
65307d9013fa55f166c2c669bd7290547c4e986b
DavidFitoussi/InheritanceSample
/Person.py
1,433
3.734375
4
from enum import Enum class TypePerson(Enum): student = 1 worker = 2 class Person: def __init__(self,name ="ingonito", age = None , height = None ): self.name = name # if name != None else "incognito" self.age = age self.height = height def WhoIam(self): print("person1.name={} is a{}".format(self.name,type(self))) class Student(Person): def __init__(self,department): Person.__init__(self, name="new student") self.department = department class Worker(Person): def __init__(self,salary): Person.__init__(self, name="new Worker") self.salary = salary class AbstactPerson(): def __init__(self, typePerson , globalname ): self.myPerson = Person() self.typePerson = typePerson if (typePerson == TypePerson.student ): self.myPerson = Student(globalname) else : self.myPerson = Worker(globalname) def getPerson(self): return self.myPerson instanceAbs = AbstactPerson(TypePerson.student,"dav") instanceAbs.getPerson().WhoIam() Person1 = Person(age=22,height=1.88) Person2 = Student("Computer Science") Person2.WhoIam() # function # create MobilePhone class # in init print("creating a phone") # create methods: ring, powerOn, # powerOff # create secret method: factoryRestart # create 2 phones
5a2c158aeb9c35af7c7cc3d5b2f8c08afc6200d5
GVK289/aws_folders
/backend-PY/car1.py
492
3.53125
4
class Car: def __init__(self, in_color,car_type, car_acc): #print('GVK') self.color = in_color self.accleration = car_acc self.type = car_type self.current_speed = 100 self.decelerate = 15 def accelerate(self): self.current_speed += self.accleration def brake(self): if self.current_speed>15: self.current_speed -= self.decelerate elif self.current_speed<15: self.current_speed = 0
1b1e1d95577219087180b5ef9f66c08fa339fc59
GVK289/aws_folders
/backend-PY/robo-main.py
1,146
3.59375
4
class Employee: bonous = 10000 no_of_employees = 0 raise_amount = 1.04 def __init__(self,first_name, last_name, salary): self.first_name = first_name self.last_name = last_name self.salary = salary self.email = first_name + '.' + last_name + '@gmail.com' Employee.no_of_employees +=1 def fullname(self): return '{} {}'.format(self.first_name,self.last_name) def apply_bonous(self): self.bonous = int(self.bonous + self.salary) def apply_raise(self): self.salary = int(self.salary * self.raise_amount) # @classmethod # def from_string(cls, emp_str): # first_name, last_name, salary = emp_str.split(' ') # return cls(first_name, last_name, salary) class Developer(Employee): raise_amount = 1.10 def __init__(self, first_name, last_name, salary, prog_lang): super().__init__(first_name, last_name, salary) self.prog_lang = prog_lang emp1 = Developer('vinay', 'kumar', 50000, 'Python') emp2 = Developer('vvv', 'kkkk', 60000, 'HTML') print(emp1.email) print(emp2.email)
1343e30afb43c35c44b16ddf3abf57dcae7ce2de
GVK289/aws_folders
/clean_code/clean_code_submissions/clean_code_assignment_002/test_car.py
10,605
3.546875
4
import pytest from car import Car ########### ******** Testing wether One object is creating ******** ########### def test_car_creating_one_car_object_with_given_instances_creates_car_object(): # Arrange color = 'Black' max_speed = 200 acceleration = 30 tyre_friction = 7 car_obj = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Act result = isinstance(car_obj, Car) # Assert assert result is True ########### ******** Testing wether Multiple objects are creating ******** ########### def test_car_creating_multiple_car_objects_with_given_instances_creates_car_objects(): # Arrange car_obj1 = Car(color='Red', max_speed=250, acceleration=50, tyre_friction=10) car_obj2 = Car(color='Black', max_speed=200, acceleration=40, tyre_friction=7) # Act creation_of_car_object1 = isinstance(car_obj1, Car) creation_of_car_object2 = isinstance(car_obj2, Car) result = car_obj1 == car_obj2 # Assert assert creation_of_car_object1 is True assert creation_of_car_object2 is True assert result is False ########### Testing the class Atrribute values Formats ########### def test_car_object_color_when_color_type_is_invalid_raises_exception(): """test that exception is raised for invalid color format""" # Arrange color = 1 max_speed = 30 acceleration = 10 tyre_friction = 3 # Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == "Invalid value for color" """ **** Testing Exceptions of class Atrribute values if not Positive type and Non-Zero **** """ @pytest.mark.parametrize("max_speed, acceleration, tyre_friction", [(-1, 10, 3), (0, 30, 10), ('1', 30, 20)]) def test_car_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction): # Arrange color = 'Red' # Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == 'Invalid value for max_speed' @pytest.mark.parametrize("max_speed, acceleration, tyre_friction", [(210, '10', 3), (100, 0, 10), (180, -30, 20)]) def test_car_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction): # Arrange color = 'Red' # Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == 'Invalid value for acceleration' @pytest.mark.parametrize("max_speed, acceleration, tyre_friction", [(210, 30, '10'), (100, 20, -1), (180, 40, 0)]) def test_car_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction): # Arrange color = 'Red' #Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == 'Invalid value for tyre_friction' ########### ******** Multiple Testings ******** ########### @pytest.fixture def car(): # Our Fixture function # Arrange color = 'Red' max_speed = 200 acceleration = 40 tyre_friction = 10 car_obj = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) return car_obj def test_car_object_when_engine_is_started_returns_true(car): # Arrange car.start_engine() # Act car_engine_start = car.is_engine_started # Assert assert car_engine_start is True def test_car_object_when_engine_is_started_twice_returns_true(car): # Arrange car.start_engine() car.start_engine() # Act car_engine_start = car.is_engine_started # Assert assert car_engine_start is True def test_car_object_when_engine_is_stop_returns_false(car): # Arrange car.stop_engine() # Act car_engine_stop = car.is_engine_started # Assert assert car_engine_stop is False def test_car_object_when_engine_is_stop_twice_returns_false(car): # Arrange car.stop_engine() car.stop_engine() # Act car_engine_stop = car.is_engine_started # Assert assert car_engine_stop is False def test_car_object_accelerate_when_engine_is_started_returns_current_speed(car): # Arrange car.start_engine() current_speed = 40 # Act car.accelerate() # Assert assert car.current_speed == current_speed def test_car_object_accelerate_when_car_object_current_speed_is_equal_to_car_object_max_speed_limit_returns_max_speed(car): # Arrange car.start_engine() max_speed = 200 car.accelerate() car.accelerate() car.accelerate() car.accelerate() # Act car.accelerate() # Assert assert car.current_speed == max_speed # ***** New capsys terminology ******* # def test_car_object_accelerate_when_car_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, car): # Act car.accelerate() captured = capsys.readouterr() # Assert assert captured.out == 'Start the engine to accelerate\n' def test_car_object_sound_horn_when_engine_is_started_returns_Beep_Beep(capsys, car): # Arrange car.start_engine() # Act car.sound_horn() captured = capsys.readouterr() # Assert assert captured.out == 'Beep Beep\n' def test_car_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_horn(capsys, car): # Act car.sound_horn() captured = capsys.readouterr() # Assert assert captured.out == 'Start the engine to sound_horn\n' ######## *********** Testing Encapusulation *********** ######## def test_encapsulation_of_car_object_color(car): # Act with pytest.raises(Exception) as e: car.color = 'Black' # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_acceleration(car): # Act with pytest.raises(Exception) as e: car.acceleration = 20 # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_max_speed(car): # Act with pytest.raises(Exception) as e: car.max_speed = 400 # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_tyre_friction(car): # Act with pytest.raises(Exception) as e: car.tyre_friction = 40 # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_is_engine_started(car): # Act with pytest.raises(Exception) as e: car.is_engine_started = True # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_current_speed(car): # Act with pytest.raises(Exception) as e: car.current_speed = 300 # Assert assert str(e.value) == "can't set attribute" #---------------------------------------# @pytest.mark.parametrize( "color, max_speed, acceleration, tyre_friction, current_speed", [ ('Red', 1, 1, 1, 1), ('Blue', 150, 30, 10, 20), ('Black', 200, 40, 10, 30)]) def test_car_object_accelerate_when_car_object_current_speed_is_more_than_car_object_max_speed_limit_returns_max_speed(color, max_speed, acceleration, tyre_friction, current_speed): # Arrange car = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) car.start_engine() car.accelerate() car.accelerate() car.accelerate() car.accelerate() car.accelerate() car.accelerate() # Act car.accelerate() # Asset assert car.current_speed == max_speed def test_car_object_current_speed_when_car_object_is_in_idle_postion_intially_returns_zero(): # Arrange car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4) # Act car_idle_initial_speed = car.current_speed # Act assert car_idle_initial_speed == 0 def test_car_object_current_speed_when_car_object_engine_is_stopped_from_motion_returns_current_speed(): # Arrange car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4) car.start_engine() current_speed = 135 car.accelerate() car.accelerate() car.accelerate() # Act car.stop_engine() # Assert assert car.current_speed == current_speed def test_apply_brakes_when_car_object_is_in_motion_returns_current_speed(car): # Arrange car.start_engine() car.accelerate() car.accelerate() current_speed = 70 # Act car.apply_brakes() # Assert assert car.current_speed == current_speed @pytest.mark.parametrize( "color,max_speed, acceleration, tyre_friction, current_speed", [ ('Red', 200, 50, 20, 30), ('Blue', 150, 25, 25, 0)]) def test_apply_breaks_when_car_object_current_speed_is_more_than_or_equal_to_car_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed): # Arrange car = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) car.start_engine() car.accelerate() # Act car.apply_brakes() # Assert assert car.current_speed == current_speed def test_apply_breaks_when_car_object_current_speed_is_less_than_car_object_tyre_friction_returns_zero(): # Arrange car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=15) car.start_engine() car.accelerate() current_speed_when_less_than_tyre_friction = 0 car.apply_brakes() car.apply_brakes() # Act car.apply_brakes() # Assert assert car.current_speed == current_speed_when_less_than_tyre_friction def test_apply_breaks_when_car_object_current_speed_is_equal_to_car_object_tyre_friction_returns_current_speed(): # Arrange car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=10) car.start_engine() car.accelerate() current_speed = 10 car.apply_brakes() car.apply_brakes() # Act car.apply_brakes() # Assert assert car.current_speed == current_speed
b293cdff81ef8d76c469aa41d74e33b26cbb64d3
zzynggg/python
/Sorting Algorithm.py
25,041
3.953125
4
# Author: Yong Zi Ying # Sorting Algorithm # Grade: 19.6/20 HD #%% Task 1:Radix Sort def best_interval(transactions, t): ''' This function is used to search for the total number of transactions within the best interval by using 2 pointers. :Input: An unsorted list of non-negative integers and a non-negative integer that represent a length of time in seconds (range). :Output: The best interval with minimum start time and the total number of transaction within the best interval. :Time Complexity: Best and worst case will be the same as the best and worst case for radix sort are the same. No matter there's only one element or more in the list, it will be pre-sorted by using radix sort. O (kN) + O (N) = O (kN), where O (kN) is from the radix sort function (explained in radix_sort function) and N is the length of the input list. :Auxiliary Space Complexity: O (N), which is from radix sort function (explained in radix_sort function). In this function, it required extra space for sorting which is O (N) auxiliary space and in comparing state does not required any extra space. :Space Complexity: O (kN), which is from radix sort function (explained in radix_sort function). The input space for comparing state is O (N) and the extra space for comparing state is O (1) so the space complexity will be O (kN) + O (N) + O (1) = O (kN) :Explanation: The input list will loop once only and 2 pointers are moving along the list to get the best time interval and the total number of transactions within the best interval. More details explanation is commented at the code. ''' # === sorting state === new_transactions = radix_sort(transactions) # pre-sort the transactions list # === Comparing state === begin_pointer = 0 exit_pointer = 0 counter = 0 max_counter = 0 best_t = 0 while begin_pointer < len(new_transactions): if len(new_transactions) == 0: # list is empty max_counter = 0 best_t = 0 break if (new_transactions[0]+t) >= new_transactions[-1]: # the first element + t is >= last element max_counter = len(new_transactions) best_t = new_transactions[-1] - t if best_t <= 0: # best_t cannot be -ve best_t = 0 break # exit loop early if (new_transactions[begin_pointer]+t) >= new_transactions[-1] or exit_pointer > len(new_transactions): break if new_transactions[exit_pointer] <= (new_transactions[begin_pointer]+t): # within the current interval exit_pointer += 1 elif new_transactions[exit_pointer] > (new_transactions[begin_pointer]+t): # exceed the current interval counter = exit_pointer - begin_pointer # get the total num of transaction within the interval if counter > max_counter: # get the largest total num of transaction within the list max_counter = counter best_t = new_transactions[exit_pointer-1] - t if best_t <= 0: # best_t cannot be -ve best_t = 0 counter = 0 if (new_transactions[begin_pointer]+t) < new_transactions[exit_pointer]: # duplicated element is found in the list begin_pointer += 1 # extra check to make sure the output is accurate counter = len(new_transactions) - begin_pointer # check the counter again if counter > max_counter: # update the max_counter if new bigger counter is found max_counter = counter best_t = new_transactions[-1] - t # update the best_t if new bigger counter is found if best_t <= 0: # best_t cannot be -ve best_t = 0 return (best_t, max_counter) def radix_sort(transactions): ''' To sort the input list into sorted list by calling multiple times of counting sort function. :Input: An unsorted list. :Output: A sorted list is returned. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(k) * O(N+M) -> O (kN + kM) = O (kN), where k is the biggest length of the element in the list, N is the length of the input list and M which is base constant so ignore M. We will need to call counting sort function for k times. :Auxiliary Space Complexity: each counting sort needs O(N + M + N) = O(N), where first N is the length of the output_array (new list that is same size with original list) that is created in the counting sort function based on the length of the input list and M (base) is the length of buckets. (count_array). A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and M is a constant number (base) so ignore it. :Space Complexity: O(kN+N+M+N) = O(kN), space complexity is input space + extra space. The input space is the length of the input list(N) and k columns (number of digits) which is O (kN) whereas the extra space from counting sort is O (N + M + N). M is base constant. (explained above) ''' # find max number of digits if len(transactions) > 0: max_num = max(transactions) else: max_num = 0 base = 10 columnn = 0 digit = base**columnn # loop the counting sort while max_num//digit > 0: counting_sort(transactions, digit, base) columnn += 1 digit = base**columnn return transactions def counting_sort(transactions, digit, base): ''' To sort the input list column by column into sorted list. :Input: An unsorted list, the column that is used to sort currently and the base value. :Output: The list is sorted until the current column. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(N+M), where N is the length of the input list and M is the biggest length of the element in the list. :Auxiliary Space Complexity: O(N + B + N) = O(N), where first N is the length of the output_array that is created in the functions based on the length of the input list and B (base) is the length of buckets. (count_array) A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and B is a constant number (base) so ignore it. :Space Complexity: O(N+N+B+N) = O(N), space complexity is input space + extra space. The input space is the length of the input list which is O (N) and the extra space is O (N + B + N). (explained above) ''' size = len(transactions) # initialize count array start from index 1 -> max_num count_array = [0] * base # initialize output array output_array = [0] * size # allocate number of elements to count array # base on the digit (column by column) for i in range(0, size): ind = transactions[i] // digit count_array[ind%base] += 1 # reused the count_array for position array for j in range(1, base): count_array[j] += count_array[j-1] # place the elements base on the position(count_array) # loop it in descending order for k in range(size-1, -1, -1): ind = transactions[k] // digit # get the right most digit output_array[count_array[ind%10] - 1] = transactions[k] count_array[ind%10] -= 1 # reuse and update the original list for l in range(0, size): transactions[l] = output_array[l] # %% Task 2: Counting Sort + Radix Sort def words_with_anagrams(list1, list2): ''' Using anagram to compare the words between 2 lists. Output the same anagram word from list1 that appears in list2. List1 will be priorities for output. :Input: Two unsorted string lists. :Output: A list of word from list1 that appear in list2 based on the same anagram of words. :Time Complexity: Best and worst case will be the same, O (L1M1 + L2M2), where L1 is the length of list1 and M1 is the biggest length of the characters of element in list1. L2 is the length of list2 and M2 is the biggest length of the characters of element in list2. if list1 have only 1 item to compare with multiple items in list2 the time complexity will be O (L1M1 + L2M2) vice versa when list2 have 1 item only. (of course the best is when either one of the lists is empty then the best complexity will be O(1)) The sorting state based on characters, the complexity for list1 is O (L1M1) and list2 is O (L2M2). The sorting state based on string elements, the complexity for list1 is O (L1) and list2 is O (L2). The comparing state complexity is based on the length of list1 which is O (L1) The comparing state 2 (refer to in-line comment) is constant. Thus, the overall time complexity is O (L1 + L1+ L2 + L1M1 + L2M2) = O (L1M1 + L2M2) :Auxiliary Space Complexity: O (L1 + L1 + L2) = O (L1 + L2), where L1 is the length of the duplication of list1 (deep copy list1 into new list) and a new list is created (output_list) with the same length as list1 (L1). The worst scenario is if all elements in list1 is appear in list2 so entire list1 is returned (L1 extra space needed). Another new list is created for list2 without duplicate elements, the length will be same as the original list2 if there’s no duplicate element in it (worse scenario). :Space Complexity: O (L1 + L2 + L1 + L2) = O (L1 + L2), space complexity is input space + extra space. The input space is L1 + L2, where L1 is the length of list1 and L2 is the length of list2. The extra space is O (L1 + L2) (explained above). :Explanation: Two lists are given, list1 will be priorities. All string elements from both lists are sorted in alphabetical order based on the characters in each string elements. [cats -> acst] After sorting each characters of string elements, sort both lists again now is sorted based on the entire string elements. [aelpp, acst -> acst, aelpp] Now, remove the duplicated elements in list2 and start comparing both lists. While comparing if the element from both lists has same initial character, it will be compared again based on each characters of the string elements. More details explanation is commented at the code. ''' # handle empty list if len(list1) == 0 or len(list2) == 0: # both list are empty return [] xori_list1 = list1.copy() # deep copy the list to prevent data loss (extra space required) xori_size = len(xori_list1) output_list = [] # extra space required # === Priority list (list1) === for i in range(xori_size): # sort each *characters* in word xori_list1[i] = counting_sort_alphabet(xori_list1[i]) for j in range(xori_size): # pair up each element with an unique key xori_list1[j] = (xori_list1[j], j) for _ in range(xori_size): # sort each *word* in list1 sorted_xori_list1 = radix_sort_string(xori_list1, 1) # === List 2 === list2_size = len(list2) for l in range(list2_size): # sort each *characters* in word list2[l] = counting_sort_alphabet(list2[l]) for _ in range(list2_size): # sort each *word* in list2 sorted_list2 = radix_sort_string(list2, 2) begin = 0 # start pointer exitt = 0 # end pointer while exitt < len(sorted_list2)-1: # remove duplicate anagram word in list2 if sorted_list2[begin] == sorted_list2[exitt+1]: exitt += 1 else: sorted_list2[begin+1] = sorted_list2[exitt+1] begin += 1 exitt += 1 sorted_xdupli_list2 = [] # extra space required for n in range(exitt): # list2 without duplicate elements sorted_xdupli_list2.append(sorted_list2[n]) if (len(sorted_list2) < 2): # restore list2 if only 1 element in list2 sorted_xdupli_list2 = sorted_list2 # === Comparing state === a = 0 # list one pointer b = 0 # list two pointer exit_check = 0 # avoid inf loop while a < xori_size: if sorted_xori_list1[a][0] == sorted_xdupli_list2[b]: # same anagram word found ori_pos = sorted_xori_list1[a][1] # original index of word output_list.append(list1[ori_pos]) a += 1 elif sorted_xori_list1[a][0] != sorted_xdupli_list2[b]: # different anagram word found # handle empty string if sorted_xori_list1[a][0] == '' and sorted_xdupli_list2[b] != '': a += 1 elif sorted_xori_list1[a][0] != '' and sorted_xdupli_list2[b] == '': b += 1 # compare the first character of the anagram word elif (sorted_xori_list1[a][0])[0] > sorted_xdupli_list2[b][0]: # compare first character b += 1 elif (sorted_xori_list1[a][0])[0] == sorted_xdupli_list2[b][0]: # compare first character # first character same pointer1 = 0 pointer2 = 0 meet_condition = True # comparing state 2 for _ in range(len(sorted_xori_list1[a][0])): # length of the word in list1 if (sorted_xori_list1[a][0])[pointer1] == (sorted_xdupli_list2[b])[pointer2]: # same initial is found pointer1 += 1 pointer2 += 1 meet_condition = False elif (sorted_xori_list1[a][0])[pointer1] > (sorted_xdupli_list2[b])[pointer2]: meet_condition = True b += 1 break elif (sorted_xori_list1[a][0])[pointer1] < (sorted_xdupli_list2[b])[pointer2]: meet_condition = True a += 1 break if pointer2 > len(sorted_xdupli_list2[b])-1: # exceed the length of word from list2 meet_condition = True b += 1 break # extra check if meet_condition == False: a += 1 # len(word1) < len(word2) else: # first character different a += 1 # extra check (improve accuracy) if b >= len(sorted_xdupli_list2)-1: # if list1 longer then list2 maintain the last element of list2 exit_check += 1 b = len(sorted_xdupli_list2)-1 # exit loop early if a > len(sorted_xori_list1)-1 and b == len(sorted_xdupli_list2)-1: break elif exit_check > a: break return output_list def radix_sort_string(listt, priority_list): ''' To sort the input list into sorted list by calling multiple times of counting sort function. :Input: An unsorted list and the priority number for the list (explained later). :Output: A sorted list. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(k) * O(N+M) -> O (kN + kM) = O (kN), where k is the biggest length of the element in the list, N is the length of the input list and M which is base constant so ignore M. We will need to call counting sort function for k times. :Auxiliary Space Complexity: each counting sort needs O(N + M + N) = O(N), where first N is the length of the output_array (new list that is same size with original list) that is created in the counting sort function based on the length of input list and M (base) is the length of buckets (count_array). A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and M is a constant number (base) so ignore it. :Space Complexity: O(kN+N+M+N) = O(kN), space complexity is input space + extra space. The input space is the length of the input list, N and k columns (number of digits) which is O (kN) whereas the extra space from counting sort is O (N + M + N). M is base constant. (explained above) :Explanation: The input parameter, priority_list is used to differentiate the list between list1 and list2. List1 will be priorities because we need to output the word from list1 that appear in list2 when comparing the word from both lists by using anagram. In order to get back the original words from list1 after comparing, each elements of list1 are paired up with a unique key so that the output is the original word (e.g cats) but not the sorted word (e.g acst). ''' max_word_size = len(listt[0]) # column if priority_list == 1: # list1 with keys # find the longest string in listt for i in range(len(listt)): word_size = len(listt[i][0]) if word_size > max_word_size: max_word_size = word_size else: # find the longest string in listt for word in listt: word_size = len(word) if word_size > max_word_size: max_word_size = word_size base = 27 # start at index 1 -> 27 column = max_word_size - 1 # word len = 4 (index[0-3]) # loop the string counting sort for column times while column >= 0: listt = counting_sort_word(listt, column, base, max_word_size, priority_list) column -= 1 return listt def counting_sort_word(listt, column, base, max_word_size, priority_list): ''' To sort the input list column by column into sorted list. :Input: An unsorted list, the column that is used to sort currently, the base value, the biggest length of the element in the list and the priority number of the list(explained in radix_sort_string). :Output: The list is sorted until the current column. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(N+M), where N is the length of the input list and M is the biggest length of the element in the list. :Auxiliary Space Complexity: O(N + B + N) = O(N), where first N is the length of the output_array that is created in the functions based on the length of input list and B (base) is the length of buckets (count_array). A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and B is a constant number (base) so ignore it. :Space Complexity: O(N+N+B+N) = O(N), space complexity is input space + extra space. The input space is the length of the input list which is O (N) and the extra space is O (N + B + N). (explained above) ''' size = len(listt) # initialize count array start from index [0-26]-> 27 slots count_array = [0] * base # initialize output array output_array = [0] * size # allocate the char in the correct position ('a' at index 1) # ord('a') = 97 -1 = 96 accurate = ord('a') - 1 if priority_list == 1: # list1 with keys # allocate words to count_array # index 0 act as temporary storage for i in range(size): word = listt[i][0] if column < len(word): index = ord(word[column]) - accurate else: index = 0 count_array[index] += 1 else: # allocate words to count_array # index 0 act as temporary storage for word in listt: if column < len(word): index = ord(word[column]) - accurate else: index = 0 count_array[index] += 1 # reused the count_array for position array for j in range(1, base): count_array[j] += count_array[j-1] if priority_list == 1: # list1 with keys # place the elements base on the position(count_array) # loop it in descending order for k in range(size-1, -1, -1): word = listt[k][0] if column < len(word): # get the right most char index = ord(word[column]) - accurate else: index = 0 output_array[count_array[index] - 1] = listt[k] # store the tuple into output_array count_array[index] -= 1 else: # place the elements base on the position(count_array) # loop it in descending order for k in range(size-1, -1, -1): word = listt[k] if column < len(word): # get the right most char index = ord(word[column]) - accurate else: index = 0 output_array[count_array[index] - 1] = word # store the word into output_array count_array[index] -= 1 return output_array def counting_sort_alphabet(word): ''' To sort the word column by column into sorted word. :Input: A word with random alphabetical order (unsorted word). :Output: Each alphabet in the word is sorted (sorted word). :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(N+M) = O (N), where N is the length of the word and M is the base of the word which is constant. :Auxiliary Space Complexity: O(N + B + N) = O(N), where first N is the length of the output_array that is created in the functions based on the length of input word and B (base) is the length of buckets (count_array). A total of N number of characters (second N) will be placed into buckets (same as the total items in output_array) and B is a constant number (base) so ignore it. :Space Complexity: O(N+N+B+N) = O(N), space complexity is input space + extra space. The input space is the length of the input word which is O (N) and the extra space is O (N + B + N). (explained above) ''' size = len(word) base = 27 # initialize count array start from index [0-26]-> 27 slots count_array = [0] * base # initialize output array output_array = [0] * size # allocate the char in the correct position ('a' at index 1) # ord('a') = 97 -1 = 96 accurate = ord('a') - 1 sorted_word = "" # allocate characters into count_array # index 0 act as temporary storage for alphabet in range(size): index = ord(word[alphabet]) - accurate count_array[index] += 1 # place the elements base on the position(count_array) index = 0 for i in range(len(count_array)): alpha = chr(i + accurate) frequency = count_array[i] for _ in range(frequency): output_array[index] = alpha index += 1 # combine each characters into word for j in output_array: sorted_word += j return sorted_word
dcf7913f53b7ea31ba263c2a26ecd5a52334846e
SaidRem/algorithms
/find_biggest_(recursion).py
404
4.21875
4
# Finds the biggest element using recursion def the_biggest(arr): # Base case if length of array equals 2 . if len(arr) == 2: return arr[0] if arr[0] > arr[1] else arr[1] # Recursion case. sub_max = the_biggest(arr[1:]) return arr[0] if arr[0] > sub_max else sub_max if __name__ == '__main__': arr = list(map(int, input().strip().split())) print(the_biggest(arr))
97789c67c970f11cc90742a11d1bb43e7f94fb01
ekaterina533/lab2.2
/2задание.py
211
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == "__main__": a=input("Введите слово:") b=input("Введите ещё одно слово:") c = set(a).intersection(set(b)) print(c)
c31a7cc8af986a8823b96cc4cc72293040f3b710
richi1325/Markovian_decision_processes
/main.py
3,864
3.5
4
from time import sleep from menu import portada, eleccion from lectura import lecturaPMD, validadorEnteros from algoritmos import * from os import system from examples import base1 def main(): portada() input() tipo = None while True: system("cls") eleccion() seleccion = input("\n Seleccione una opción:") if seleccion == "1": tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() elif seleccion == "2": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() enumeracionExhaustivaPoliticas(estados,estados_decisiones, cij, k, tipo) input() elif seleccion == "3": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() solucionPorProgramacionLineal(estados,estados_decisiones, cij, k, tipo) input() elif seleccion == "4": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() mejoramientoPoliticas(estados,estados_decisiones, cij, k, tipo) input() elif seleccion == "5": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() alpha = validadorFlotantes(' Inserte el factor de descuento:') mejoramientoPoliticasDescuento(estados,estados_decisiones, cij, k, tipo, alpha) input() elif seleccion == "6": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() alpha = validadorFlotantes(' Inserte el factor de descuento:') iteraciones = validadorEnteros(' Inserte el número de iteraciones:') tolerancia = validadorFlotantesPositivos(' Inserte la tolerancia del método:') aproximacionesSucesivas(estados,estados_decisiones, cij, k, tipo,alpha,iteraciones,tolerancia) input() elif seleccion == "7": break else: print("\n¡Por favor ingrese una opción válida!") sleep(2) print(""" _ /.\\ Y \\ / "L // "/ |/ /\_================== / / / / ¡Hasta la próxima! \/ """) sleep(3) def validadorFlotantes(mensaje): while True: try: numero = input(mensaje) numero = float(numero) break except ValueError: print('¡Debes insertar un número!') return numero def validadorFlotantesPositivos(mensaje): while True: try: numero = input(mensaje) numero = float(numero) if numero<=0.0: print('El valor debe ser mayor a 0!') else: break except ValueError: print('¡Debes insertar un número!') return numero if __name__ == "__main__": main()
402632370f075fec73ef83f052aaee9150349108
zoulala/exercise
/leetcode/Sort_quick.py
1,338
3.90625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # # ***************************************************** # # file: Sort_quick.py # author: zoulingwei@zuoshouyisheng.com # date: 2021-12-29 # brief: # # cmd>e.g: # ***************************************************** """快速排序: 说白了就是给基准数据找其正确索引位置的过程,本质就是把基准数大的都放在基准数的右边,把比基准数小的放在基准数的左边,这样就找到了该数据在数组中的正确位置. 然后递归实现左边数组和右边数组的快排。 """ def quick_sort(nums, st, et): if st>=et: return i,j = st, et # 设置基准数 base = nums[i] # 如果列表后边的数比基准数大或相等,则前移一位直到有比基准数小的数 while (i < j) and (nums[j] >= base): j = j - 1 # 如找到,则把第j个元素赋值给第i个元素 nums[i] = nums[j] # 同样的方式比较前半区 while (i < j) and (nums[i] <= base): i = i + 1 nums[j] = nums[i] # 做完第一轮比较之后,列表被分成了两个半区,并且i=j,此时找到基准值 nums[i] = base # 递归前后半区 # print(base, myList) quick_sort(nums, st, i - 1) quick_sort(nums, j + 1, et) nums = [1,3,2,6,4,7,5] quick_sort(nums,0,6) print(nums)
8266e8603f0e2123137e0dadaf27ee36bafc4ac4
zoulala/exercise
/thoth-test/mongodb_test.py
7,399
3.53125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- from pymongo import MongoClient # 连接mongodb # ------------------------------ conn = MongoClient('localhost', 27017) db = conn.mydb #连接mydb数据库,没有则自动创建 my_set = db.test_set # 使用test_set集合,没有则自动创建 # 插入数据(insert插入一个列表多条数据不用遍历,效率高, save需要遍历列表,一个个插入) # ------------------------------ my_set.insert({"name":"zhangsan","age":18}) #或 my_set.save({"name":"zhangsan","age":18}) #添加多条数据到集合中 users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}] my_set.insert(users) #或 for w in users: my_set.save(w) # 查询数据库 # ------------------------------ # 查询全部 for i in my_set.find(): print(i) #查询name=zhangsan的 for i in my_set.find({"name":"zhangsan"}): print(i) print(my_set.find_one({"name":"zhangsan"})) # 更新数据 # ------------------------------ my_set.update({"name":"zhangsan"},{'$set':{"age":20}}, { 'upsert': True, #如果不存在update的记录,是否插入 'multi': False, #可选,mongodb 默认是false,只更新找到的第一条记录 'writeConcern': True #可选,抛出异常的级别。 } ) # 删除数据 # ------------------------------ #删除name=lisi的全部记录 my_set.remove({'name': 'zhangsan'}) #删除name=lisi的某个id的记录 id = my_set.find_one({"name":"zhangsan"})["_id"] my_set.remove(id) #删除集合里的所有记录 db.users.remove() # mongodb的条件操作符 # ------------------------------ # (>) 大于 - $gt # (<) 小于 - $lt # (>=) 大于等于 - $gte # (<= ) 小于等于 - $lte #例:查询集合中age大于25的所有记录 for i in my_set.find({"age":{"$gt":25}}): print(i) # 排序 \在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序,-1为降序。 # ------------------------------ for i in my_set.find().sort([("age",1)]): print(i) # limit和skip # ------------------------------ #limit()方法用来读取指定数量的数据 #skip()方法用来跳过指定数量的数据 #下面表示跳过两条数据后读取6条 for i in my_set.find().skip(2).limit(6): print(i) # in # ------------------------------ #找出age是20、30、35的数据 for i in my_set.find({"age":{"$in":(20,30,35)}}): print(i) # or # ------------------------------ #找出age是20或35的记录 for i in my_set.find({"$or":[{"age":20},{"age":35}]}): print(i) #all # ------------------------------ # 查看是否包含全部条件 dic = {"name":"lisi","age":18,"li":[1,2,3]} dic2 = {"name":"zhangsan","age":18,"li":[1,2,3,4,5,6]} my_set.insert(dic) my_set.insert(dic2) for i in my_set.find({'li':{'$all':[1,2,3,4]}}): print(i) #输出:{'_id': ObjectId('58c503b94fc9d44624f7b108'), 'name': 'zhangsan', 'age': 18, 'li': [1, 2, 3, 4, 5, 6]} #push/pushAll # ------------------------------ my_set.update({'name':"lisi"}, {'$push':{'li':4}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'li': [1, 2, 3, 4], '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi'} my_set.update({'name':"lisi"}, {'$pushAll':{'li':[4,5]}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'li': [1, 2, 3, 4, 4, 5], 'name': 'lisi', 'age': 18, '_id': ObjectId('58c50d784fc9d44ad8f2e803')} # pop/pull/pullAll # ------------------------------ # pop # 移除最后一个元素(-1为移除第一个) my_set.update({'name':"lisi"}, {'$pop':{'li':1}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi', 'li': [1, 2, 3, 4, 4]} # pull (按值移除) # 移除3 my_set.update({'name':"lisi"}, {'$pull':{'li':3}}) #pullAll (移除全部符合条件的) my_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'name': 'lisi', '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'li': [4, 4], 'age': 18} # 多级路径元素操作 # ------------------------------ dic = {"name":"zhangsan", "age":18, "contact" : { "email" : "1234567@qq.com", "iphone" : "11223344"} } my_set.insert(dic) #多级目录用. 连接 for i in my_set.find({"contact.iphone":"11223344"}): print(i) #输出:{'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}} result = my_set.find_one({"contact.iphone":"11223344"}) print(result["contact"]["email"]) #输出:1234567@qq.com #多级路径下修改操作 result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}}) result1 = my_set.find_one({"contact.iphone":"11223344"}) print(result1["contact"]["email"]) #输出:9999999@qq.com # 还可以对数组用索引操作 dic = {"name":"lisi", "age":18, "contact" : [ { "email" : "111111@qq.com", "iphone" : "111"}, { "email" : "222222@qq.com", "iphone" : "222"} ]} my_set.insert(dic) #查询 result1 = my_set.find_one({"contact.1.iphone":"222"}) print(result1) #输出:{'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]} #修改 result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}}) print(result1["contact"][1]["email"]) #输出:222222@qq.com # 索引 #--------------------------------- my_set.ensureIndex({'age':1}) # 在age字段上构建索引(B-tree),,, my_set.find({'age':23}) # 通过age字段查找速度将会大大提高 my_set.getIndexes() # 查看索引 my_set.dropIndex({'age':1}) # 删除索引 # demo #==================================================================================== #!/usr/bin/env python # -*- coding:utf-8 -*- from pymongo import MongoClient settings = { "ip":'192.168.0.113', #ip "port":27017, #端口 "db_name" : "mydb", #数据库名字 "set_name" : "test_set" #集合名字 } class MyMongoDB(object): def __init__(self): try: self.conn = MongoClient(settings["ip"], settings["port"]) except Exception as e: print(e) self.db = self.conn[settings["db_name"]] self.my_set = self.db[settings["set_name"]] def insert(self,dic): print("inser...") self.my_set.insert(dic) def update(self,dic,newdic): print("update...") self.my_set.update(dic,newdic) def delete(self,dic): print("delete...") self.my_set.remove(dic) def dbfind(self,dic): print("find...") data = self.my_set.find(dic) for result in data: print(result["name"],result["age"]) def main(): dic={"name":"zhangsan","age":18} mongo = MyMongoDB() mongo.insert(dic) mongo.dbfind({"name":"zhangsan"}) mongo.update({"name":"zhangsan"},{"$set":{"age":"25"}}) mongo.dbfind({"name":"zhangsan"}) mongo.delete({"name":"zhangsan"}) mongo.dbfind({"name":"zhangsan"}) if __name__ == "__main__": main()
ad820701830b1218dae30ec6f8168979064f2da9
zoulala/exercise
/others/a_stock_simulate.py
2,878
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # # ***************************************************** # # file: a_stock_simulate.py # author: zoulingwei@zuoshouyisheng.com # date: 2020-04-16 # brief: 看了一个操盘策略,用公式进行模拟。https://www.toutiao.com/i6815418938378158606 # # cmd>e.g: # ***************************************************** import random money = 100000. # 总价 p_num = 5. loss_k = 0.1 # 止损率 add_k = 0.2 # 止赢率 prob = 1./3 # 股票上涨概率(止赢概率) 该参数完全体现个人水平,影响最终结果走势 profit = 0. # 每一步利润 inps = 20000. # 初始入金 a_part = money/p_num # 每操作单元 def make_a_deal(inps,money,max_step=10): '''进行一笔交易 inps:入仓额 money:手上总额 max_step:最大交易次数 ''' print(max_step,inps, money) money -= inps # 入仓 outs = 0 # 交易终止条件 if money<0: return outs if max_step<1: return outs # 开始交易 max_step -= 1 # 交易次数减少一次 rd = random.random() # 0~1随机数 if rd < prob: profit = add_k*inps # 止赢 else: profit = -loss_k*inps # 止损 outs = inps+profit # 出仓 money += outs if outs > inps: inps += a_part # 止赢就加大一码入仓 if inps>money: # 入仓额度>总价,则不加码 inps -= a_part outs = make_a_deal(inps, money,max_step) # 继续交易 else: inps -= a_part # 止损就加减一码入仓 if inps<a_part: # 入仓额度最少为一码 inps = a_part outs = make_a_deal(inps, money,max_step) # 继续交易 return outs def make_a_deal2(inps,money,target=200000,step=0): '''进行一笔交易 inps:入仓额 money:手上总额 target:目标额 step:交易次数 ''' print('交易%s次,入仓%s,总额%s'%(step,inps, money)) # 交易终止条件 if money<0 or money>target: return 0 # 开始交易 money -= inps # 入仓 step += 1 # 交易次数减少一次 rd = random.random() # 0~1随机数 if rd < prob: profit = add_k*inps # 止赢 else: profit = -loss_k*inps # 止损 outs = inps+profit # 出仓 money += outs if outs > inps: inps += a_part # 止赢就加大一码入仓 if inps>money: # 入仓额度>总价,则不加码 inps -= a_part outs = make_a_deal2(inps, money,target,step=step) # 继续交易 else: inps -= a_part # 止损就加减一码入仓 if inps<a_part: # 入仓额度最少为一码 inps = a_part outs = make_a_deal2(inps, money,target,step=step) # 继续交易 return outs # make_a_deal(inps,money,max_step=100) make_a_deal2(inps,money,200000,0)
cf7b11055a31306a15a1485840d9c409020cb356
PromasterGuru/Hackerrank-Solutions
/Capitalize!/main.py
171
3.625
4
# Complete the solve function below. def solve(s): return ' '.join([word.capitalize() for word in s.split(' ')]) if __name__ == '__main__': print(solve(input()))
660e41b5a8d6da7ff132d7fd1c91ad29943cd1a0
PromasterGuru/Hackerrank-Solutions
/Alphabet Rangoli/main.py
321
3.53125
4
import string def print_rangoli(size): alphabets = list(string.ascii_lowercase)[:size] for i in range(size-1, -size, -1): res = '-'.join(alphabets[size-1:abs(i):-1] + alphabets[abs(i):size]) print(res.center(4*size-1, '-')) if __name__ == '__main__': n = int(input()) print_rangoli(n)
11649567de31fd5543c30fd786c222bb1438321a
PromasterGuru/Hackerrank-Solutions
/Electronics Shop/main.py
779
3.78125
4
from itertools import product def getMoneySpent(keyboards, drives, b): result = -1 for ar in list(product(*(keyboards, drives))): if sum(ar) <= b and sum(ar) > result: result = sum(ar) return result if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') bnm = input().split() b = int(bnm[0]) n = int(bnm[1]) m = int(bnm[2]) keyboards = list(map(int, input().rstrip().split())) drives = list(map(int, input().rstrip().split())) # # The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items # moneySpent = getMoneySpent(keyboards, drives, b) print(moneySpent) # fptr.write(str(moneySpent) + '\n') # fptr.close()
d16a3efed1b1437a0e4ed382af134e3510b5aac5
iuryferreira/python-data-structures
/data_structures/open_address_hashtable.py
2,174
3.71875
4
from data_structures.hashtable import HashTable from data_structures.utils.data_structures_visualization import DataStructuresVisualization class OpenAddressHashTable(HashTable): """ This class inherits from HashTable, using open address collision treatment. """ def __init__(self, size): super().__init__(size) def hash_func(self, value, sequence): return (super().hash_func(value) + (sequence - 2)) % (self.size) def __repr__(self): return "\nOpen Address HashTable:\n{0}".format(DataStructuresVisualization.open_address_hash_table(self.table)) def insert(self, value): sequence = 0 while sequence != self.size: position = self.hash_func(value, sequence) if self.table[position] is None: self.table[position] = value return position else: sequence += 1 return "All fields have already been filled." def search(self, value): sequence = 0 while sequence != self.size: position = self.hash_func(value, sequence) if self.table[position] == value: return position else: sequence += 1 return None def remove(self, value): position = self.search(value) if position is None: return "All fields are empty." else: self.table[position] = None class OpenAddressHashTableLinearProbing(OpenAddressHashTable): """ This class inherits from OpenAddressHashTable, and implements the linear hash function. """ def __init__(self, size): super().__init__(size) class OpenAddressHashTableQuadraticProbing(OpenAddressHashTable): """ This class inherits from OpenAddressHashTable, and implements the quradratic hash function. """ def __init__(self, size, c1, c2): self.c1 = c1 self.c2 = c2 super().__init__(size) def hash_func(self, value, sequence): return (super().hash_func(value) - 1 + self.c1 * (sequence-1) + (self.c2 * (sequence-1)) ^ 2) % (self.size)
5a1edee22fe63654a519259ee3b4ceaa2f4a345a
NaokiEto/CS171
/hw3/raster.py
4,108
4.3125
4
# Must be called before any drawing occurs. Initializes window variables for # proper integer pixel coordinates. def initDraw(xMin, xMax, yMin, yMax, xr, yr): global windowXMin, windowXMax, windowYMin, windowYMax, xRes, yRes windowXMin = xMin windowXMax = xMax windowYMin = yMin windowYMax = yMax xRes = xr yRes = yr # Helper function to convert a real x position into an integer pixel coord. def getPixelX(x): return int((x - windowXMin) / (windowXMax - windowXMin) * xRes) # Helper function to convert a real y position into an integer pixel coord. def getPixelY(y): return int((y - windowYMin) / (windowYMax - windowYMin) * yRes) # Helper function f as defined in the course text. Not sure exactly what # it means, on a conceptual level. def f(vert0, vert1, x, y): x0 = vert0[0] y0 = vert0[1] x1 = vert1[0] y1 = vert1[1] return float((y0 - y1) * x + (x1 - x0) * y + x0 * y1 - x1 * y0) # The meat of the package. Takes three vertices in arbitrary order, with each # vertex consisting of an x and y value in the first two data positions, and # any arbitrary amount of extra data, and calls the passed in function on # every resulting pixel, with all data values magically interpolated. # The function, drawPixel, should have the form # drawPixel(x, y, data) # where x and y are integer pixel coordinates, and data is the interpolated # data in the form of a tuple. # verts should be a (3-element) list of tuples, the first 2 elements in each # tuple being X and Y, and the remainder whatever other data you want # interpolated such as normal coordinates or rgb values def raster(verts, drawPixel, shadingType, material, lights, campos, matrix): xMin = xRes + 1 yMin = yRes + 1 xMax = yMax = -1 coords = [ (getPixelX(vert[0]), getPixelY(vert[1])) for vert in verts ] coordsX = verts[0] coordsY = verts[1] coordsZ = verts[2] lenX = len(coordsX) # find the bounding box for c in coords: if c[0] < xMin: xMin = c[0] if c[1] < yMin: yMin = c[1] if c[0] > xMax: xMax = c[0] if c[1] > yMax: yMax = c[1] print "the yMin is: ", yMin print "the yMax is: ", yMax print "the xMin is: ", xMin # normalizing values for the barycentric coordinates # not sure exactly what's going on here, so read the textbook fAlpha = f(coords[1], coords[2], coords[0][0], coords[0][1]) fBeta = f(coords[2], coords[0], coords[1][0], coords[1][1]) fGamma = f(coords[0], coords[1], coords[2][0], coords[2][1]) if abs(fAlpha) < .0001 or abs(fBeta) < .0001 or abs(fGamma) < .0001: return print "checkpoint" # go over every pixel in the bounding box for y in range(max(yMin, 0), min(yMax, yRes)): for x in range(max(xMin, 0), min(xMax, xRes)): # calculate the pixel's barycentric coordinates alpha = f(coords[1], coords[2], x, y) / fAlpha beta = f(coords[2], coords[0], x, y) / fBeta gamma = f(coords[0], coords[1], x, y) / fGamma #print "the alpha, beta and gamma are: ", alpha, ", ", beta, ", ", gamma # if the coordinates are positive, do the next check if alpha >= 0 and beta >= 0 and gamma >= 0: # interpolate the data for either gouraud or phong if (shadingType != 0): data = [0]*lenX for i in range(lenX): data[i] = alpha * coordsX[i] + beta * coordsY[i] + gamma * coordsZ[i] # interpolate the data for flat elif (shadingType == 0): data = [0]*6 for i in range(3): data[i] = alpha * coordsX[i] + beta * coordsY[i] + gamma * coordsZ[i] for i in range(3, 6): data[i] = coordsX[i] # and finally, draw the pixel if data[2] >= -1: drawPixel(x, y, data, shadingType, material, lights, campos, windowXMin, windowXMax, windowYMin, windowYMax, matrix)
91cd0209f59bcbdb4c4324ff8bcfaa0cc6b782a4
exload/CS50-2019
/pset6/bleep/bleep.py
889
3.765625
4
from cs50 import get_string from sys import argv, exit def main(): if len(argv) != 2: print("Usage: python bleep.py dictionary") exit(1) # Prompt the user to provide a message print("What message would you like to censor?") text = get_string() # Open file dict_file = open(argv[1], 'r') dictionary = set() for line in dict_file: dictionary.add(line.strip()) dict_file.close() # print("------------") # print(dictionary) # print("------------") # Entered text modification splited_text = text.split(' ') for word in splited_text: # print(word) # print("++++++") if word.lower() in dictionary: x = len(word) print("*" * x, end="") else: print(word, end="") print(" ", end="") print() if __name__ == "__main__": main()
bc49cd0006cb106bfa069970a3e37d84ec093b2f
ubco-mds-2018-labs/data533_lab2_vaghul_jiachen
/xuebadb/dfanalysis/cleanup.py
419
3.5
4
import numpy as np import pandas as pd import missingno import matplotlib.pyplot as plt def show_nulls(input_df): if(not isinstance(input_df, pd.DataFrame)): print("Can't cleanup an object that is not a dataframe") return None input_df.replace("None", np.nan, inplace = True) # Matrix that displays data sparsity to see missing/Null values missingno.matrix(input_df) plt.show()
11cc2c6083d06171c1e2db5e0c2c1b1502e3289a
lucasadelino/Learning-Python
/Automate the Boring Stuff Practice Projects/Chapter 7/regexstrip.py
218
4.0625
4
# A regex version of the strip() method import re def regexstrip(some_string, arg = '\s'): strip = re.compile('^' + arg + '*|' + arg + '*$') return strip.sub('', some_string) print(regexstrip('AAAbruceAAA'))
f3a85aff075359dfbbeedde83d6727735d3b7e29
BSkullll/DSA
/Stacks and Queues/balanced_parenthesis.py
393
3.796875
4
def balanced_parenthesis(data): if len(data) % 2 != 0: return False opening = {'{','(','['} datas = { ('(',')'), ('[',']'), ('{','}') } stack = [] for e in data: if e in opening: stack.append(e) else: if len(stack) == 0: return False ch = stack.pop() if (ch, e) not in datas: return False return len(stack) == 0 print(balanced_parenthesis('[]'))
51eef942ba2281b2f49dc1a8bc7ec8ee8990184f
BSkullll/DSA
/Array Question/anagram_by_sorted_approach.py
341
3.703125
4
def func(a, b): a = a.replace(' ', '').lower() b = b.replace(' ', '').lower() result = None if len(a) != len(b): return False else: a = sorted(a) b = sorted(b) for i in range(len(a)): if a[i] == b[i]: result = True continue else: result = False break return result print(func("abcc","abcd"))
4eb482a93d598a005ef04360363310916c619eeb
PdxCodeGuild/class_mudpuppy
/Assignments/Racheal/python/Lab2.py
713
4.0625
4
# lab2 """ instructions Search the interwebs for an example Mad Lib Create a new file and save it as madlib.py Ask the user for each word you'll put in your Mad Lib Use an fstring to put each word into the Mad Lib """ """ The wheels on the bus go round and round Round and round Round and round The wheels on the bus go round and round All through the town """ adjective = input("Enter an adjective: ") noun = input("Enter a noun: ") verb = input("Enter a verb: ") # There was a farmer who had {noun}, # And Bingo was his name-o. # B-I-N-G-O # And Bingo was his name-o. # There was a farmer who had a dog, # And Bingo was his name-o. print(f"There was a farmer who {verb}, {adjective},And {noun} was his name-o.")
6af4513c000f0bf8ae449e915e146515187fed08
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab07-rock_paper_scissors.py
1,327
4.25
4
#lab07-rockpaperscissors.py import random user_input = 'yes' while user_input == 'yes': print('Let\'s play rock-paper-scissors!') print('The computer will ask the user for their choice of rock, paper or scissors, and then the computer will randomly make a selection.') #computer tell user how the game will work user = input ('rock, paper or scissors:') choices = ('rock', 'paper', 'scissors') #the user will have to choose one of these options computer = random.choice(choices) #the computer will select a random choice if user == computer: print('It\'s a tie') elif user == 'rock': if computer == 'paper': print('Computer wins, the computer chose paper') if computer =='scissors': print('Computer loses, the computer chose scissors' ) elif user == 'paper': if computer =='scissors': print('Computer wins, the computer chose scissors' ) if computer == 'rock': print('Computer loses, the computer chose rock') elif user == 'rock': if computer =='scissors': print('Computer loses, the computer chose scissors' ) if computer == 'rock': print('Computer wins, the computer chose rock') user = input('Would you like to play again?')
f5bac030adc72702c31328a37f3c483b445bd25c
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/repl-example.py
227
3.8125
4
# Running state running = True # While it's running # LOOP while running: # READ value = input("Enter anything or done to exit: ") # EVALUATE if value == "done": running = False break # PRINT print(value)
10ad2eef9da72722ff2354360db06a58c6ff05af
PdxCodeGuild/class_mudpuppy
/3 JavaScript/js_py/rot13/rot13.py
334
3.5
4
import string unencoded = "helloiliketocode" unencoded = "uryybvyvxrgbpbqr" num_list = [] for letter in unencoded: num = string.ascii_lowercase.index(letter) num_list.append(num) encoded = '' for num in num_list: index = (num + 13) % len(string.ascii_lowercase) encoded += string.ascii_lowercase[index] print(encoded)
0ee076081c0c54572abae5c4ab18625918c643f8
PdxCodeGuild/class_mudpuppy
/Assignments/Manny/Python/lab23.py
2,197
3.859375
4
with open('contacts.csv', 'r') as file: lines = file.read().split('\n') list_of_lines = [] for line in lines: line = (line.split(",")) # makes our contact file nice and neat list_of_lines.append(line) # headers = list_of_lines[0] # other_lines = list_of_lines[1:] # 1: starts at the second item on the list not the 0 contacts = [] for line in other_lines: contact_dict = {} for index, item in enumerate(line): contact_dict[headers[index]] = item contacts.append(contact_dict) print(contacts) while True: user_choice = input("Choose (c)reate, (r)etrieve, (u)pdate, (d)elete, (q)uit: ") if 'r' == user_choice: name_choice = input("Enter the name you chose: ") found = False for contact in contacts: if contact["name"] == name_choice: # will show name choice if they are in contacts print(contact) found = True if found == False: print(f"{name_choice} is not in contacts.") elif 'q' == user_choice: break if 'u' == user_choice: name_choice = input("Enter the name you chose: ") for contact in contacts: if contact["name"] == name_choice: # print the contact name if the contact name is the same as the name choice key = input("name? food? hobby? ") value = input("What fo you want to change? ") contact[key] = value # the end updated if 'd' == user_choice: name_choice = input("Which name would you like to delete? ") for contact in contacts: if contact["name"] == name_choice: contacts.remove(contact) print(f"You deleted {name_choice}") if 'c' == user_choice: name_choice = input("Which name would you like to add? ") food_choice = input(f"What is {name_choice} favorite food?? ") hobby_choice = input(f"What is {name choice} favorite hobby? ") contact_dict = { 'name': name_choice, 'food': food_choice, 'hobby': hobby_choice, } contacts.append(contact_dict) print(contacts)
4885b4212545ee9f635fed82f045478503adc865
PdxCodeGuild/class_mudpuppy
/Reviewed/Brea/python/lab17/lab17_version2_checked.py
1,009
4.125
4
#Lab 17, Version 2 Anagram def split(word): return list(word) # good practice, but generally don't make a function # that calls a single function, especially one that's already well-known like list() def remove_spaces(str): new_str = '' for i in range(len(str)): if(str[i] != ' '): new_str += str[i] return new_str # I like that you did this the hard way (you learn more that way) # but you could just do str.replace('', ' ') # Also, don't use the parameter str, that overwrites a builtin function user_input1 = input("What is the first input you'd like to compare? : ") user_input1 = user_input1.lower() list_inp1 = split(remove_spaces(user_input1)) user_input2 = input("What is the second input to compare? : ") user_input2 = user_input2.lower() list_inp2 = split(remove_spaces(user_input2)) list_inp1.sort() list_inp2.sort() if list_inp1 == list_inp2: print("These two inputs are anagrams!") else: print("These two inputs are not anagrams!") # Nice!
37675d15d25aa51006258ff94564fbc04ff6e685
PdxCodeGuild/class_mudpuppy
/1 Python/class_demos/function-lecture/add-number-words-ultimate-solution.py
986
4.125
4
import operator def get_valid_input(): valid_input = False while not valid_input: num1 = input("Spell out a number with letters: ") if num1 in number_dict: return num1 else: print(f"{num1} is not supported. Try entering a different number: ") def reduce_list_to_value(fn, starting_value, values): accumulator = starting_value for val in values: accumulator = fn(accumulator, val) return accumulator def square_and_add(x,y): return x + y**2 number_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} numbers = [] for _ in range(4): inp = get_valid_input() numbers.append(number_dict[inp]) number_sum = reduce_list_to_value(operator.add, 0, numbers) product = reduce_list_to_value(operator.mul, 1, numbers) sum_squares = reduce_list_to_value(square_and_add, 0, numbers) print(f"The sum is {number_sum}, the product is {product}, the sum of squares is {sum_squares}")
096d0dc863ab7739debf8e8000545f4e7f7f3cda
PdxCodeGuild/class_mudpuppy
/Assignments/Devan/1 Python/labs/lab11-simple_calculator.py
1,098
4.21875
4
# Lab 11: Simple Calculator Version 3 def get_operator(op): return operators[op] def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def eval(fn, n1, n2): return fn(n1, n2) operators = {'+': add, '-': subtract, '*': multiply, '/': divide} while True: try: operator = input('Enter your operator (+, -, *, /) or done: ') if operator == 'done': print('\nThanks for using the calculator.') break if operator not in operators: print('Not a vaild operator...') else: # todo: validate user entered number n1 = input('Enter the first number: ') if n1 is not int: print('Enter a vaild number. ') n2 = int(input('Enter the second number: ')) if n2 is not int: print('Enter a valid number. ') print(eval(get_operator(operator), int(n1), int(n2))) except KeyboardInterrupt: print('\nThank You') break
541761c20e5cdc6eb60fb7316866f139754f0841
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/wacky_functions.py
252
3.59375
4
wacky_functions.py def noisey_add(num1, num2): print(f"ADDING {num1} AND {num2}!!!!:D") return num1 + num2 def bad_add (num1, num2): print(num1 + num2) print(noisey_add(1, 3) + (-2 + 5)) # (1 + 3) + (-2 + 5) # 4 + (-2 + 5) # 4 + 3 # 7
50962379cef04f28b24854aeeaccc11e9f673a9b
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/labs06.py
1,170
4.21875
4
# Lab 6: Password Generator """ Let's generate a password of length `n` using a `while` loop and `random.choice`, this will be a string of random characters. """ import random import string # string._file_ = random.choice('string.ascii_letters + string.punctuation + string.digits') # #print((string._file_)) # pass_num = input ("How many characters? ") # pass_num = int(pass_num) # out_num = '' # for piece in range(pass_num): # out_num = out_num + random.choice(string.ascii_letters + string.punctuation + string.digits) # print(out_num) string._file_ = random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation) pass_low = input("How many lowercase? ") pass_low = int(pass_low) pass_high = input("How many uppercase? ") pass_high = int(pass_high) pass_dig = input("How many numbers? ") pass_dig = int(pass_dig) out_num = '' for piece in range(pass_low): out_num = out_num + random.choice(string.ascii_lowercase) for piece in range(pass_high): out_num = out_num + random.choice(string.ascii_uppercase) for piece in range(pass_dig): out_num = out_num + random.choice(string.digits) print(out_num)
b88a20e027f7711bff9a5b8a9d0658d3b8a638cb
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Python Labs/Lab25_version2.py
1,603
3.765625
4
#Lab 25, version 2, April 17th, 2020 class Atm: def __init__(account, balance = 0): account.negative = False account.balance = balance account.interest_rate = .01 account.transactions = [] def check_balance(account): #returns the account balance print(f"Your account currently has ${account.balance}") return account.balance def deposit(account, amount): #deposits the given amount in the account account.balance += amount account.transactions.append(f"User has deposited ${amount}, for a new balance of ${account.balance}") return account.balance def check_withdrawal(account, amount): if (account.balance - amount) >= 0: print("You're good.") return False elif (account.balance - amount) < 0: print("Careful, your withdrawal will put in in the red.") return True def withdraw(account, amount): account.balance -= amount account.transactions.append(f"User has withdrawn ${amount}, for a new balance of ${account.balance}") return account.balance def calc_interest(account): interest_calc = account.balance * account.interest_rate print(f"Your account has earned ${interest_calc} in interest.") return interest_calc def print_transactions(account): for item in account.transactions: print(item, sep='\n') return account.transactions Brea = Atm() Brea.deposit(100) Brea.withdraw(6) Brea.deposit(10000) Brea.print_transactions()
042467884095a0b0e7a52c67df4cae6033eb4f88
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab09-written_addition.py
1,444
3.90625
4
#lab09-written_addition.py units = { "m": 1, "ft": 0.3048, "mi": 1609.34, "km": 1000, "yd": 0.9144, "in": 0.0254 } user_unit = input("What unit are you using?") user_number = input("Enter the number of units.") user_number = int(user_number) if user_unit == "m": solution = units["m"] * user_number print(solution) elif user_unit == "ft": solution = units["ft"] * user_number print(solution) elif user_unit == "mi": solution = units["mi"] * user_number print(solution) elif user_unit == "km": solution = units["km"] * user_number print(solution) elif user_unit == "yd": solution = units["yd"] * user_number print(solution) else: solution = units["in"] * user_number print(solution) ### (user_unit)int = number_dict[user_unit] ### # written_addition.py num1 = input("Spell out a number with letters: ") num2 = input("Spell out a number with letters: ") number_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # num1_int = number_dict[num1] # num2_int = number_dict[num2] num1_int = 0 num2_int = 0 if num1 == 'one': num1_int = number_dict['one'] elif num1 == 'two': num1_int = number_dict['two'] elif ... number_sum = num1_int + num2_int print(f"The sum is {number_sum}") # user_ft = int(input("How many feet do you want to turn into meters? ")) # m = 0.3048 # solution = m * user_ft # print(f"the distance in meters is: {solution}")
9686df41204e02ef1e69ce6eda1c5cc539826484
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab03-grading.py
491
3.984375
4
#lab03-grading.py user_grade = int(input("What is your grade? ")) if user_grade > 100: print("Good job, you got an A+!") elif user_grade <= 100 and user_grade >= 90: print("Good job, you got an A.") elif user_grade <= 90 and user_grade >= 80: print("Not bad, you got an B.") elif user_grade <= 80 and user_grade >= 70: print("That's average, you got an C.") elif user_grade <= 70 and user_grade >= 60: print("Not very good, you got an D.") else: print("You failed!")
efb3cc272635bad1eac58a5a54352b76d8aaf03b
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test3.26.20.py
935
3.953125
4
# import random # eye = random.choice(';:') # nose = random.choice('->') # mouth = random.choice(')]') # output = eye + nose + mouth # print(output) # def make_face(eye, nose, mouth): # return eye + nose + mouth # # def make_eye(): # # return # # def make_nose(): # # return # # def make_mouth(): # # return # #print(make_face(make_eye(), make_nose(), make_mouth())) # #print(make_face(';', '>', ']')) #TRYING TO GET THE COMPUTER TO MAKE AN OPTIMAL GUESS THROUGH AVERAGES AND FEEDBACK def average(x, y): return round((x + y) / 2) def search(lower, upper, target, guess): print(f'You guessed {guess}') if guess == target: print('Correct!') elif guess < target: print('Too low!') search(guess, upper, target, average(guess, upper)) elif guess > target: print('Too high!') search(lower, guess, target, average(lower, guess)) search(1, 100, 1, 2)
29ea796e4e8cf9ed5da93f437c836b23eba80c34
PdxCodeGuild/class_mudpuppy
/1 Python/examples/book_recommender_v2.py
2,420
3.625
4
import requests import random from bs4 import BeautifulSoup # Create your own error called InvalidGenreError class InvalidGenreError(Exception): pass def get_books(genre='horror'): # Get html data from a website response = requests.get(f"https://www.goodreads.com/genres/new_releases/{genre}") # Turn it into something python can work with html = BeautifulSoup(response.text, 'html.parser') # Find all div elements on a page divs = html.find_all('div') # Found books books = [] # Loop over them for div in divs: classes = div.get('class') # If they have a class called 'coverWrapper'... if classes and 'coverWrapper' in classes: # Find the link and title of the book title = div.find('img')['alt'] link = div.find('a')['href'] # Add to our books list book = (title, link) books.append(book) # If we find no books, raise an error if len(books) == 0: raise InvalidGenreError("Invalid genre!") return books def get_suggested_books(books, count=3): # Setup our suggest books list suggested_books = [] # Start our books_found counter at 0 books_found = 0 # Make sure we don't loop forever count = min(len(books), count) # While we haven't found 3 books... while books_found < count: # Randomly pick a book suggested_book = random.choice(books) # If it hasn't already been picked... if suggested_book not in suggested_books: # Add it to our list suggested_books.append(suggested_book) # Increase the amount of books we've found books_found += 1 return suggested_books def print_suggestions(suggested_books): # Print our suggested books in a nice way print(f"We suggest these {len(suggested_books)} book(s):") print("-----------------------\n") for suggested_book in suggested_books: # Tuple unpack our title and link title, link = suggested_book print(title) print(f"https://www.goodreads.com{link}\n") # Default setup! # books = get_books() # suggested_books = get_suggested_books(books) # print_suggestions(suggested_books) # Take user input genre = input("What genre do you want?: ") count = int(input("How many do you want?: ")) # Try and get books, and catch an invalid genre try: books = get_books(genre) suggested_books = get_suggested_books(books, count) print_suggestions(suggested_books) except InvalidGenreError as e: print(e)
ba0752e6e9750a6b832ba939613811df382ee644
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/lab12-v1.py
318
4.0625
4
import random computer_guess = random.randint(1, 10) won = False print(computer_guess) for i in range(10): guess = float(input("Guess a number between 1-10: ")) if guess == computer_guess: won = True break print(f"Guess again, you meat bag! You have {9 - i} tries left...") if won: print("You won!")
361ac4d33c0fd3855b67ebb14103f6a2db052c0f
PdxCodeGuild/class_mudpuppy
/1 Python/hints/lab_23/list_to_dict.py
571
3.609375
4
# list_to_dict.py start_list = [['a', 'b', 'c'], ['d', 'e', 'f']] output = [] for one_list in start_list: # one_list = ['a', 'b', 'c'] print(one_list) one_dict = {} for index in [0, 1, 2]:#range(len(one_list)): #index = 0 #one_list[index] = 'a' one_dict[index] = one_list[index] # one_dict = {0: 'a', 1: 'b', 2: 'c'} output.append(one_dict) print(output) # [{0: 'a', 1: 'b', 2: 'c'}, {0: 'd', 1: 'e', 2: 'f'}] ''' endgoal = [ {0: 'a', 1: 'b', 2: 'c'}, {0: 'd', 1: 'e', 2: 'f'} ] print(endgoal) '''
d67ad475fcc9930444dfc9dba97ea0d380a8ce72
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/function.py
3,960
4.75
5
'''def my_function(fname): #fname is the argument, functions can have as many arguments as possible. just separate with commmas. #When the function is called, we pass along a first name. print(fname + " Refsnes")#used inside the function to print the full name: #shortened to args in Python documents #parameter is a variable listed inside the parentheses in the function definition. #argument is the value that are sent to the function when it is called my_function("Emil") = prints Emil Refsnes my_function("Tobias") = prints Tobias Refsnes my_function("Linus") = prints Linus Refsnes ----------------------------------------------------- if your function expects 2 arguments, you must call the function with 2 arguments, not more and not less. ----------------------------------------------------- ''' '''ARBITRARY ARGUMENTS, *args: if you don't know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly. ''' ''' enter = int(input("What's your favorite numnber? (0-2) : ")) def my_function(*kids): print("Your youngest child will be named" + kids[2]) #Depending on which name I want I can choose from the index my_function(" Emil", " Tobias", " Linus")#if we change 2 to enter, it still produces linus ''' #------------------------------------------------------------------ '''KEYWORD ARGUMENTs: We can also send arguments with the key = value syntax. This way the order of the arguments does not matter. ''' '''def my_function(child3, child2, child1): print("The youngest child is" + child3) my_function(child1 = " Emil", child2 = " Tobias", child3 = " Linus") ''' #---------------------------------------------------------------------- '''ARBITRARY KEYWORD ARGUMENTS (keyword arguments **kwargs): If you dont know how many keyword arguemtns will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of argurments, and can access the items accordingly:''' '''def my_function(**kid): print("His last name is " + kid["lname"]) #If we don't put quotes, python will give us a NameError: 'lname' not defined my_function(fname = "Tobias", lname = "Refsnes")''' #----------------------------------------------------- '''DEFAULT PARAMETER VALUE: if we call the function without argument, it uses the default value: ''' ''' def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") ''' #-------------------------------------------------------------------------------- '''PASSING A LIST AS AN ARGUMENT - you can send any data types of argument to a function (string, number, list, dictionary, etc.) and it will be treated as the same data type inside the function. E.g if you send a LIST as an argument, it will still be alist when it reaches the function: ''' # def my_function(food): # for x in food: # print(x) # fruits = ["apple", "banana", "cherry"] # my_function(fruits) #apple #banana #cherry '''RETURN VALUES''' # def my_function(x): # return 5 * x # print(my_function(3)) = 15 # print(my_function(5)) = 25 # print(my_function(9)) = 45 #------------------------------------------------------------------ '''THE PASS STATEMENT''' # function definitions cannot be empty, # but if you for some reason have a function # definition with no content, put in the pass statement to avoid getting an error. def myfunction(): pass #---------------------------------------------------------------------------- Recursion means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result. BE CAREFUL WITH RECURSION - YOU CAN WRITE A FUNCTION THAT NEVER TERMINATES, OR ONE THAT USES EXCESS AMOUNTS OF MEMORY OR PROCESSOR POWER. tri_c
2874845c72626487f96500a7aac40ba91891870e
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/lab09-v2.5.py
617
4.34375
4
# Supported unit types supported_units = ["ft", "mi", "m", "km"] # Ask the user for the unit they want unit = input("What unit do you want: ") # If an invalid unit is specified, alert the user and exit if unit not in supported_units: print("Please enter a valid unit! Options are ft, mi, m, km...") exit() # Get the amount of units amount = float(input("How many units: ")) # Check to see if the unit matches one we know if unit == "ft": print(amount * 0.3048) elif unit == "mi": print(amount * 1609.34) elif unit == "m": print(amount * 1 * 1 * 1) # Extra spicy elif unit == "km": print(amount * 1000)
94aaa7a1f356fae443a91b748d7ad8f8fe395882
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/lab10.py
330
3.8125
4
list1 = [] i = 0 while True: num1 = (input("Input your first number: ")).lower() # print(num1.isdigit()) if num1.isdigit(): num2 = int(num1) list1.append(num2) elif num1 == "done": total = (sum(list1)//len(list1)) print(f"Your average is: {total}") break
7d22fbd58d09e95c2ab94e8adb567da9c3932b36
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab18.py
439
4.125
4
import string input_string = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] #change variable name #create an empty list for index in range(1,len(input_string)-1): left_side = input_string[index-1] middle = input_string[index] right_side = input_string[index + 1] if left_side < middle and right_side < middle: print(index) elif left_side > middle and right_side > middle: print(index)
adbf42f3752456bea0736e70ac0ac4133ede4db8
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/lab08.py
593
3.703125
4
amount = float(input("Enter a dollar amount (0-99) : ")) ver = amount.is_integer() print(ver) if ver is False: print(amount//.25, "quarters") amount = amount%.25 print(amount//.10, "dimes") amount = amount%.10 print(amount//.05, "nickles") amount = amount%.05 print(amount//.01, "pennies") amount = amount%.01 elif ver is True: print(amount//25, "quarters") amount = amount%25 print(amount//10, "dimes") amount = amount%10 print(amount//5, "nickles") amount = amount%5 print(amount//1, "pennies") amount = amount%1
91c7e627278fe3386b9db69c2bf8636072abbeaf
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab09-unit_converter.py
1,154
4.46875
4
""" Ask the user for the number of feet, and print out the equivalent distance in meters. Hint: 1 ft is 0.3048 m. So we can get the output in meters by multiplying the input distance by 0.3048. Below is some sample input/output. """ # import decimal # print("Enter number of feet ") # number_feet = float(input('')) # meters = 0.3048 # print(f" that equals {number_feet * meters} meters ") """ Allow the user to also enter the units. Then depending on the units, convert the distance into meters. The units we'll allow are feet, miles, meters, and kilometers. """ # import math # distance = 11 # user = input("Choose a unit: ") # unit_dict = { 'feet' : 0.3048, 'miles': 1609.3, 'meter': 1, 'kilometer': 1000 } # user_int = unit_dict[user] # conversion = user_int * distance # print(f"(The conversion is {conversion} ") """ Add support for yards, and inches. """ # import math # distance = 11 # user = input("Choose a unit: ") # unit_dict = { 'feet' : 0.3048, 'miles': 1609.3, 'meter': 1, 'kilometer': 1000, 'yard' : 0.9144, 'inch' : 0.254 } # user_int = unit_dict[user] # conversion = user_int * distance # print(f"(The conversion is {conversion} ")
2deae52c1bab7a98738c027df30c62d50ee50ccc
PdxCodeGuild/class_mudpuppy
/Reviewed/Brea/python/lab14/lab14_v1.py
1,510
3.5625
4
#Lab 14, version 1.py import random winner_card = [] my_card = [] def pick_six(): card = [] for _ in range(6): card.append(random.choice(range(1, 100))) return card def num_matches(winner_card, my_card): matching_counter = 0 for _ in range(len(winner_card)): if winner_card[_] == my_card[_]: matching_counter += 1 return matching_counter def winnings(matching_counter, my_balance): if matching_counter == 0: my_balance += 0 return my_balance elif matching_counter == 1: my_balance += 4 return my_balance elif matching_counter == 2: my_balance += 7 return my_balance elif matching_counter == 3: my_balance += 100 return my_balance elif matching_counter == 4: my_balance += 50000 return my_balance elif matching_counter == 5: my_balance += 1000000 return my_balance elif matching_counter == 6: my_balance += 25000000 return my_balance else: print("Error, more matches than expected!") winner_card = pick_six() plays = 100000 my_balance = 0 for _ in range (plays): my_card = pick_six() my_balance -= 2 matching_counter = num_matches(winner_card, my_card) #my_balance += winnings(matching_counter) my_balance = winnings(matching_counter, my_balance) roi_calc = round((my_balance - (plays * 2)) /(plays * 2)) print(f"I won ${my_balance}! My ROI was ${roi_calc}")
cc27d88befb5c37dbf60154209dd3aaac7b590b9
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Python Labs/Lab25_version3.py
2,614
4.0625
4
#Lab 25, version 3, April 17th, 2020 class Atm: def __init__(account, balance = 0): account.negative = False account.balance = balance account.interest_rate = .01 account.transactions = [] def check_balance(account): #returns the account balance print(f"Your account currently has ${account.balance}") return account.balance def deposit(account, amount): #deposits the given amount in the account account.balance += amount account.transactions.append(f"User has deposited ${amount}, for a new balance of ${account.balance}") return account.balance def check_withdrawal(account, amount): if (account.balance - amount) >= 0: print("You're good.") return False elif (account.balance - amount) < 0: print("Careful, your withdrawal will put in in the red.") return True def withdraw(account, amount): account.balance -= amount account.transactions.append(f"User has withdrawn ${amount}, for a new balance of ${account.balance}") return account.balance def calc_interest(account): interest_calc = account.balance * account.interest_rate print(f"Your account has earned ${interest_calc} in interest.") return interest_calc def print_transactions(account): for item in account.transactions: print(item, sep='\n') return account.transactions if __name__ == "__main__": Brea = Atm() while True: user_input1 = input("Would you like to deposit, withdraw, check balance, check history, or quit? : ") if user_input1 == 'deposit': user_input2 = int(input("How much would you like to deposit? : ")) Brea.deposit(user_input2) elif user_input1 == 'withdraw': user_input3 = int(input("How much would you like to withdraw? : ")) if Brea.balance - user_input3 <= 0: user_input4 = input("This will drain your account. Are you sure? : ") if user_input4 == 'no': break elif user_input4 == 'yes': Brea.withdraw(user_input3) elif user_input1 == 'check balance': Brea.check_balance() elif user_input1 == 'check history': Brea.print_transactions() elif user_input1 == 'quit': print("Thank you for banking with the Piggy Bank!") break else: print("Sorry, I don't understand.")
934737b34c7ffe58f092243fd4036019a57da25c
PdxCodeGuild/class_mudpuppy
/1 Python/class_demos/200323/scratch.py
954
3.6875
4
counter = 0 output = '' while counter < 10: output = 'a' + output + 'bb' #changed counter = counter + 2 print(output) ''' while True: user_input = input("Please type cat: ") if user_input == 'cat': break ''' ''' pieces = '' for piece in ['a', 'b', 'c', 'd', 'e']: pieces = pieces + piece print(f"The letters are {pieces}") ''' ''' while True: # paste code here var1 = input("Please type cat >") if var1 == 'cat': break ''' ''' abc_counter = '' for piece in 'abcde': abc_counter = abc_counter + piece + ', ' print(abc_counter) ''' ''' a_num = input("How many a's do you want? ") a_num = int(a_num) pieces = list(range(a_num)) output = '' for piece in pieces: output = output + 'a' print(output) ''' ''' # scratch.py while True: user_response = input("Should I print a? ") if user_response == 'yes': print('a') if user_response == 'no': break print('done') '''
ad522fcec25bc4b7d7ddf0e89a5473b070aa5a87
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/lab12.py
3,449
4
4
import random # choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # user = int(input(f"pick a number between 1-10 : ")) # num = int(random.randint(0,10)) #random integer between 1 and 10 # print(num) # # user = '' # guess_count = 0 # guess_limit = 10 # out_of_guesses = False # # while guess <= guess_limit: # # if num != user: # # user = int(input("Guess again : ") # # guess = guess + 1 # # elif num == user: # # guess = guess + 1 # # print("correct") # # elif num > user: # # guess = guess + 1 # # print("too low") # # elif num < user: # # guess = guess + 1 # # print("too high")_ # while num != user and not out_of_guesses: # # user = int(input("Guess again : ")) # if guess_count < guess_limit: # user = int(input("Guess again : ")) # num = print(random.randint(0,10)) # guess_count += 1 # elif num == user: # print("correct") # guess += 1 # break # elif num > user: # print("too low!") # guess += 1 # break # elif num < user: # print("too high!") # guess += 1 # break # # print("guesses: ", guess) # else: # out_of_guesses = True # if out_of_guesses: # print("out of guesses, you lose!") # else: # print("You win") ''' break elif num == user: print("correct") guess += 1 break elif num > user: print("too low!") guess += 1 break elif num < user: print("too high!") guess += 1 break # print("guesses: ", guess) ''' '''Building a guessing game''' #input secret word, if they do not guess it continue to ask. secret_word = random.randint(0,10) #created variables guess =int(input("Enter Guess : ")) print(secret_word) guess_count = 0 #everytime the loop goes around add 1 for the guess guess_limit = 10 #how many tries the user has out_of_guesses = False #will tell us whether or not the user is out of guesses # if guess_limit < 10: # out_of_guesses = False # # else: # # out_of_guesses = True while guess != secret_word and not(out_of_guesses): #as long as they haven't guessed the word or are out of guesses if (guess_count) < guess_limit: #if guess count is less than guess limit than they have guesses left. guess = int(input("Enter guess again: ")) #if they have guesses look we ask them to enter another guess # secret_word = print(random.randint(0,10)) guess_count += 1 print(guess_count) if secret_word == guess: guess_count += 1 print("correct") print(guess_count) if secret_word > guess: guess_count += 1 print("too low") print(guess_count) if secret_word < guess: guess_count += 1 print("too high") print(guess_count) break else: out_of_guesses = True #if it is equal to true then they don't get anymore guesses print("Out of guesses, you lose") print(guess_count) # if secret_word in guess: # guess = guess + 1 # print("correct") # elif secret_word > guess: # guess = guess + 1 # print("too low") # elif secret_word < guess: # guess = guess + 1 # print("too high") # else: # print("Try again") # if out_of_guesses: # print("out of guesses, you lose!") # else: # print("You win")
e22e5470c09538653b22d42dfd800bbb11dbba05
PdxCodeGuild/class_mudpuppy
/Assignments/Devan/1 Python/labs/lab03-grading.py
586
4.09375
4
user_grade = int(input('What is your score? ')) second_digit = user_grade % 10 if second_digit < 5: suffix = '-' elif second_digit > 5: suffix = '+' elif second_digit == 5: suffix = '' if user_grade >= 90: print(f"Congrats you got a A{suffix}") elif user_grade >= 80 and user_grade < 90: print(f"Congrats you got a B{suffix}") elif user_grade >= 70 and user_grade < 80: print(f"You\'re just an average C{suffix} student") elif user_grade >= 60 and user_grade < 70: print(f"Try harder, you got a D{suffix}") elif user_grade <= 59: print('You failed....')
c5d508427ca54175b9b640d81d451807aa07ac21
PdxCodeGuild/class_mudpuppy
/Assignments/Racheal/python/test.py
1,247
4.34375
4
import random #Twinkle, twinkle, little star, #How I wonder what you are! #Up above the world so high, #Like a diamond in the sky. # little = input("Enter adjective:") # wonder = input("Enter verb:") # world = input("Enter noun:") # high = input("Enter adjective:") # diamond = input("Enter noun:") # sky =input("Enter noun:") # print(f"twinkle, twinkle,{little} star, how I {wonder} what you are! Up above the {world} so {high} like a {diamond}in the {sky}. Twinkle twinkle little start, how I wonder what you are") # list1 = [] user_input = input('enter a plural noun, an adjective, a verb, a noun, and another adjective:' ) # list1 = user_input.append(user_input) # print(f"twinkle, twinkle,{little} star, how I {wonder} what you are! Up above the {world} so {high} like a {diamond}in the {sky}. Twinkle twinkle little start, how I wonder what you are") user_input_list = user_input.split() print(len(user_input_list)) print(f"twinkle, twinkle,{user_input_list[0]} star, how I {user_input_list[1]} what you are! Up above the {user_input_list[2]} so {user_input_list[3]} like a {user_input_list[4]}in the. Twinkle twinkle little start, how I wonder what you are") word = "" for i in range(): word += random.choice() print(word)
76f115e3224919ec85f85e033a29ea86cbe1307d
PdxCodeGuild/class_mudpuppy
/Assignments/Devan/1 Python/labs/lab05-random_emoticon_generator.py
642
3.671875
4
import random from huepy import * def _main_(): how_many = int(input('How many emoticons do you want? ')) list_of_emoticons = [] seperator = red(' or ') for i in range(how_many): list_of_emoticons.append(make_face()) print(seperator.join(list_of_emoticons)) user_choice = int(input('Which one do you like best? (1,2,3..)')) print(list_of_emoticons[user_choice - 1]) def make_eyes(): return random.choice(':;8X') def make_nose(): return random.choice('->^•') def make_mouth(): return random.choice('D|])(P') def make_face(): return make_eyes() + make_nose() + make_mouth() _main_()
0bb505f1ef1cdaeea4fc60ad3d1091a63e1d29a6
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab02-mad_lib.py
257
3.875
4
lab02-madlib.py ''' You must be the change you wish to see in the world. ''' person = input("Name a person: ") pronoun = input("Name a pronoun: ") place = input("Name a place: ") print(f"{Person} must be the change {pronoun} wish to see in the {place}.")
42996f16ee0b8d80e5cfcb2bc60e20bb875d67e1
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Python Labs/hello32020.py
130
3.875
4
pieces = '' for piece in ['a', 'b', 'c', 'd', 'e']: pieces = pieces + piece print(f"The letter is {pieces}") print('bye')
a8dd0814e6f3294f7c65ed85b0c49311589f6fb8
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab25-atm.py
2,171
4.15625
4
#lab25-atm.py class ATM: def __init__(self, balance=0, interest_rate=.01): self.balance = balance self.interest_rate = interest_rate self.transactions = [] def check_balance(self): '''returns the account balance''' print(f"Your balance is {self.balance}") return self.balance def deposit(self, amount): '''deposits the given amount in the account''' print(f"Your deposit is {amount}") self.balance += amount self.transactions.append(f'User deposited ${amount}') print(f"Your balance is {self.balance}") def check_withdrawal(self, amount): '''returns true if the withdrawn amount won't put the account in the negative''' if self.balance >= amount: return True else: return False def withdrawl(self, amount): '''withdraw(amount) withdraws the amount from the account and returns it''' if self.balance >= amount: self.balance -= amount print(f"Your balance is {self.balance}") self.transactions.append(f'User withdrew ${amount}') else: print("You do not have enough money") def print_transactions(self): print(f"Here is your list of transactions {self.transactions}") '''printing out the list of transactions''' def calc_interest(self): '''returns the amount of interest calculated on the account''' interest = self.balance * self.interest_rate print(f"Your balance is {interest}") my_atm = ATM(balance=100) while True: user_choice = input('Choose (d)eposit, (w)ithdrawl, (cb)alance, (h)istory, (q)uit: ') if 'd' == user_choice: amount = input(f'How much would you like to deposit?') my_atm.deposit(int(amount)) if 'w' == user_choice: amount = input(f'How much would you like to withdrawl?') my_atm.withdrawl(int(amount)) if 'cb' == user_choice: my_atm.check_balance() if 'h' == user_choice: my_atm.print_transactions() elif 'q' == user_choice: break print(f'Thank you, please come again!')
4e17ad1e21e211e490a7e0b4ef34b71052415dc9
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test_042220.py
225
4.1875
4
#Test Examples, April 22nd, 2020 data1 = {'a': 1} data2 = {'a': {'b': 1}} #if we call 'a', it'll return the dictionary data3 = {'a': {'b': 1}, 'z': ['Portland', 'Seattle', 'LA']} #if we call data3['z'][0], returns 'Portland'
d8fca062d064a604256c2e1df1392debd589ece1
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/lab25.py
2,366
3.9375
4
User_Bal = 250 class Bank_Account(): def __init__(self, balance=0, print_transactions=[], interest=.1): self.balance = balance # self.print_transactions = print_transactions self.print_transactions = [] self.interest = interest def ch_bal(self): return f"Your Current Balance : ${self.balance}.00" def deposit(self, amount): self.balance = self.balance + amount '''self.print_transactions''' self.print_transactions.append(f'You Deposited : {amount}.00') # User_Bal += amount return f"You deposited {amount} dollars.\n Your Current Balance is : ${self.balance}.00" def ch_with(self, amount): if amount < self.balance: return True + "Insufficient Funds" def withd(self, amount): self.balance = self.balance - amount '''self.print_transactions = ''' self.print_transactions.append(f"You Withdrew {amount}") # User_Bal -= amount return f'You withdrew {amount}.00 dollars.\n Your New Balance is :$ {self.balance}.00' def get_transactions(self): return self.print_transactions def interest_r(self, interest): return f" Your monthly interest is: {self.balance * self.interest} : Interest Rate: .01" def main(): atm_1 = Bank_Account(250, [], 0.1) User_Bal = 250 while True: user = int(input('What would you like to? 1. Deposit 2. Withdrawal 3. Balance 4. History 5. Exit')) # if 5 != user: if user == 1: user_amount = int(input("How much Shmoneyy would you like to Deposit? : ")) # user_amt1 = "{:.2f}".format(amount) print(atm_1.deposit(user_amount)) if user == 2: user_amount = int(input("How much Would you like to Withdrawal? : ")) if user_amount <= User_Bal: User_Bal -= user_amount # user_amt1 = "{:.2f}".format(amount) print(atm_1.withd(user_amount)) else: print("insuff funds") if user == 3: print(atm_1.balance) if user == 4: print(atm_1.print_transactions) print(f"Your Accumulated Interest : ${atm_1.interest*atm_1.balance}0") if user == 5: print('Thank you, Goodbye!') break main()
710e3aff3001f8d68ba758bf1472992bb021c904
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab25.py
1,803
3.921875
4
class ATM: def __init__(self, balance, interest): self.balance = balance self.interest = interest self.transactions =[] # self.check_withdrawl = True # def __repr__(self): # return f"balance:{self.balance}" def deposit_amount(self, deposit): self.balance += deposit self.transactions.append(f"You deposited {deposit}") # this needs to be copied in a few places def check_withdrawl(self, withdrawl): if self.balance >= withdrawl: print("You can withdraw ") return True else: return False def withdrawl_amount(self, withdrawl): if self.check_withdrawl(withdrawl): self.balance -= withdrawl self.transactions.append(f"You withdrew {withdrawl}") def calc_interest(self): self.balance += 0.1 def print_transaction(self): print(self.transactions) my_atm = ATM(1200, .1) my_atm.withdrawl_amount(1200) ATM.deposit_amount(my_atm, 1200) print(my_atm.balance) my_atm.print_transaction() while True: user_input = input("(D)eposit, (W)ithdrawl, (C)heck_balance, (H)istory? (Q)uit ") if user_input == "D": user_deposit = int(input("How much would you like to deposit?: ")) my_atm.deposit_amount(user_deposit) # print(user_deposit + my_atm.balance) if user_input == "W": user_withdrawl = int(input("How much would you like to withdraw? ")) my_atm.withdrawl_amount(user_withdrawl) # print(user_withdrawl - my_atm.balance) if user_input == "C": print(my_atm.balance) # print(user_balance) if user_input == "H": my_atm.transactions my_atm.print_transaction() # print(user_history) if user_input == "Q": break
3826fbad1118f1c86d3bed7104589caf027a53d4
PdxCodeGuild/class_mudpuppy
/1 Python/hints/lab_17/double_letter_finder.py
488
4.03125
4
# double_letter_finder.py s2 = "I have a book in my bag." s1 = "I have a jacket in my bag." # found_letter = '' found_double_letter = False for index in range(len(s1) - 1): # print(index, s1[index], index + 1, s1[index + 1]) if s1[index] == s1[index + 1]: found_double_letter = True found_letter = s1[index] + s1[index + 1] break if found_double_letter: print(f"It has double letters: {found_letter}") else: print("It doesn't have double letters")
a35cffa0ab2b6c4424709cf8693ef70106688eb9
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test_042120.py
1,464
4.1875
4
#Test Examples April 21st, 2020 #average numbers lab re-do # nums = [5, 0, 8, 3, 4, 1, 6] # running_sum = 0 # for num in nums: # running_sum = running_sum + num # print(running_sum) # aver = running_sum / len(nums) # print(f"The average of your numbers is {aver}.") #--------REPL Version of average numbers lab # nums = [] # running_sum = 0 # while True: # user_input = int(input("Enter a number (or, '0' for done) : ")) # if user_input == 0: # aver = running_sum / len(nums) # print(f"The average of your numbers is {aver}.") # break # nums.append(user_input) # running_sum += user_input # print(nums) #-----------class version of average numbers # class NumList: # def __init__(self): # self.nums = [] # def append(self, in_num): # self.nums.append(int(in_num)) # def average(self): # return sum(self.nums) / len(self.nums) # me = NumList() # while True: # user_input = input("Enter a number or 'done': ") # if user_input == 'done': # break # me.append(user_input) # print(me.nums) # print(me.average()) #--------------------- #Tic Tac Toe Tests board = [[' ', '|', ' ', '|', ' '], [' ', '|', ' ', '|', ' '], [' ', '|', ' ', '|', ' ']] board2 = [] # for inner_list in board: # board2.append(''.join(inner_list)) board2 = '\n'.join([''.join(inner_list) for inner_list in board]) print(board2)
850e221c13bbdc7bb9f70adb622070a42ccdfcea
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Python Labs/Lab12_v1_3.26.20.py
477
3.890625
4
#Lab 12 Version 1, March 26th, 2020 import random num1 = random.randint(1,10) guess_num = 0 while True: user_guess = int(input("What number do you guess? : ")) if user_guess == num1: guess_num = guess_num + 1 print(f"You're correct! You guessed {guess_num} of times.") break if user_guess != num1: guess_num = guess_num + 1 print("Guess again!") if guess_num == 10: print("Sorry, game over!") break
a402906c2b218262ba0afbafa8a1a600dd58b028
PdxCodeGuild/class_mudpuppy
/Assignments/Manny/Python/scantron_checker.py
462
3.5625
4
import random scantron_choices = ['a', 'b', 'c', 'd', 'e' ] nephews_answers = [] for piece in range (0,5): nephews_answers = nephews_answers.append(random.choice(scantron_choices)) answer_sheet = [] counter = 0 for piece in range(0,5): answer_sheet.append(random.choice(scantron_choices)) for i in range(5): if answer_sheet[i] == nephews_answers[i]: print("correct") counter += 1 else: print("incorrect")
74bbe23731059f641662d2d577b36f2ecdd4db66
bob1b/blakes7
/server/FuncServer.py
8,479
3.515625
4
""" This code handles basic client/server transactions in he blake's 7 game """ # from https://github.com/Pithikos/python-websocket-server from websocket_server import WebsocketServer import pprint import json import requests pp = pprint.PrettyPrinter(indent=4) class FuncServer(object): """ handles all server-related duties - mainly communication stuff """ server = {'PORT':9001, 'stagedDataMessages':[]} # model data messages to be sent later # to each player by ID blakes7 = None clients = None def __init__(self, blakes7): """ initialize whatnot """ self.blakes7 = blakes7 self.clients = [] def get_ip_location_string(self, ip_address): """ use remote api to get region and country for a given IP addr """ freegeopip_url = 'http://freegeoip.net/json/' url = '{}{}'.format(freegeopip_url, ip_address) print "funcServer().getIPlocString(): url = " + str(url) response = requests.get(url) response.raise_for_status() the_json = response.json() try: ret_string = "%s, %s, %s" % (the_json['city'], \ the_json['region_name'], \ the_json['country_name']) except Exception: print """functServer().getIPlocString(): unable to get IP location string from json: """ + str(the_json) ret_string = "unknown location" return ret_string def client_joined(self, client, server): """ Called for every client connecting (after handshake) A client joined the game. Add to list of clients """ print "New client connected and was given id %d" % client['id'] self.clients.append({'id':client['id'], 'data':client}) self.blakes7.server.send_client(client['id'], {'type':'CONNECTED'}) def client_requesting_name(self, client_id, name, password, iploc): """ client has connected and is requesting a player name """ ## TODO - ensure client is not already in the players list player_id = self.blakes7.players.assign_player_id_to_client( client_id, name, password ) values = {'client_id':client_id, 'player_id':player_id, 'name':name, 'password':password, 'iploc':iploc} self.blakes7.players.player_joined(values) def client_left(self, client, server): """ Called when a client disconnects """ print "Client (id = %d) disconnected" % client['id'] client_id = client['id'] # remove player or set to inactive self.blakes7.players.player_left(client_id) # remove from clients list for i in range(0, len(self.clients)): if self.clients[i] and self.clients[i]['id'] == client_id: print "removing client, ID = " + str(client_id) del self.clients[i] break def get_client_data(self, client_id): """ for a given client_id, return the client data from the internal list. This will be mainly used for sending messages to clients """ for i in range(0, len(self.clients)): if self.clients[i] and self.clients[i]['id'] == client_id: return self.clients[i]['data'] print """FuncServer.get_client_data(): unable to get client data for clientID = %d""" % (client_id) return None def message_received(self, client, server, message): """ message was received from a client, decide what to do """ if len(message) > 200: message = message[:200]+'..' print "message from client (%d) is over 200 bytes long" % \ (client['id']) client_id = client['id'] print "from client %d: %s" % (client_id, message) # attempt to serialize json try: message_dict = json.loads(message) except Exception: print """could not convert json to dict, message from client (%d), message = %s""" % (client_id, message) return None # handle received messages if message_dict: if message_dict['type'] == 'REQUESTING_PLAYER_NAME': name = message_dict['data']['name'], password = message_dict['data']['password'] iploc = self.blakes7.server.get_ip_location_string( client['address'][0] ) self.client_requesting_name( \ client['id'], name, password, iploc) # check for messages to do with different model updates player = self.blakes7.players.client_id_to_player(client_id) player_id = None if player and 'player_id' in player: player_id = player['player_id'] self.blakes7.ships.process_message(client['id'], player_id, message_dict) return message_dict def send(self, player_id, message_dict): """ converts the message dict to JSON and sends to a player given by player id """ try: json_message = json.dumps(message_dict) # , ensure_ascii=False) except Exception: print """funcServer.send(): could not dump message_dict to json. Message dict:""" pp.pprint(message_dict) return # send to all players if player_id < 0: # TODO - perhaps should get list of clients and check if each has # an active player associated? instead doing the reverse player_ids = self.blakes7.players.get_player_ids() for player_id in player_ids: client_data = self.blakes7.players.player_id_to_client(player_id) print "funcServer.send(): sending to client %d, json = %s" % \ (player_id, json_message) if client_data is not None: self.server['ws'].send_message(client_data, json_message) else: print "FuncServer.send(): could not send to every player, missing " + \ "client data for player #%d" % player_id # send to single player else: client_data = self.blakes7.players.player_id_to_client(player_id) if client_data is not None: print "funcServer.send(): sending to client %d, json = %s" % \ (player_id, json_message) self.server['ws'].send_message(client_data, json_message) else: print """funcServer.send(): No client info! Could not send message: %s""" % json_message # TODO - merge code with send()? def send_client(self, client_id, message_dict): """ sends to a given client (based on port) rather than to a particular player """ try: json_message = json.dumps(message_dict) # , ensure_ascii=False) except Exception: print """funcServer.send_client(): could not dump message_dict to json. Message dict:""" pp.pprint(message_dict) client_data = self.get_client_data(client_id) if client_data is not None: self.server['ws'].send_message(client_data, json_message) else: print "funcServer.send_client(): could not send message: %s" % \ json_message def start_server(self): """ entry-point for the websocket part of the server """ # not adding 0.0.0.0 listens only for local connections self.server['ws'] = WebsocketServer(self.server['PORT'], '0.0.0.0') self.server['ws'].set_fn_new_client(self.client_joined) self.server['ws'].set_fn_client_left(self.client_left) self.server['ws'].set_fn_message_received(self.message_received) print "starting websocket listener" self.server['ws'].run_forever() def stage_data_message(self, player_id, model): """ receive models as a parameter, which will later be sent all at once """ # TODO return def send_staged_data_messages(self): """ send aggregated data model to players """ # TODO return
750437c3c078315b3a3ee1981aa1173e2dfaeefe
charlotteviner/project
/land.py
1,632
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 28 17:37:12 2017 @author: charlotteviner Credit: Code written by Andrew Evans. Create elevation data for use in the project. Provided for background on how the artificial environment 'land' was created. Returns: land (list) -- List containing land elevation data. land (.txt) -- File containing data for the land elevation. """ import matplotlib import csv w = 100 # Set width to 100. h = 100 # Set height to 100. land = [] # Create empty list called 'land'. # Plot a 100 x 100 square. for y in range(0, h): # Cycle through coordinates (0, h) until h = 100. row = [] # Create empty list called 'row'. for x in range(0, w): row.append(0) # Append 0 to 'row' at (0, w) until w = 100. land.append(row) # Append each row created to the 'land' list. # Add relief to the 100 x 100 square. for y in range(0, h): # Cycle through coordinates (0, h) until h = 100. for x in range(0, w): # Cycle through (0, w) until w = 100. if (x + y) < w: # If (x + y) < w, then the coordinate will = x + y. land[y][x] = x + y else : # If not, the coordinate will = (w - x) + (h - y). land[y][x] = (w - x) + (h - y) # Plot 'land' on a graph. matplotlib.pyplot.ylim(0, h) # Limit of y axis. matplotlib.pyplot.xlim(0, w) # Limit of x axis. matplotlib.pyplot.imshow(land) print(land) # Create a new file 'land.txt' which contains the coordinate data. f = open('land.txt', 'w', newline='') writer = csv.writer(f, delimiter=',') for row in land: writer.writerow(row) f.close()