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
40d01cedf0c714e191ae59d898e87d237ab8849f
droftware/Knight-Rescue
/KnightRescue/player.py
4,035
3.578125
4
import pygame import constants import person import landforms import ladder import fireball import sys import donkey import cage class Player(person.Person): """ Defines the player object.It inherits from Person class.""" def __init__(self): """Constructor for Player class.""" super(Player,self).__init__(0,0,50,70,'p2_stand.png') self.rect.left = 0 self.rect.bottom = constants.SCREEN_HEIGHT self.score = 0 self.life = constants.PLAYER_LIFE self.__princess = None self.__reached_princess = False def update(self): """ Moves the player acording to the user and also checks if it has collected any coins,has been hit with a fireball or has reached the princess. """ super(Player,self).update() self.__check_collision() def move_left(self): """ Moves the player left """ self.set_x_vector(-1 * constants.PLAYER_SPEED) def move_right(self): """ Moves the player right """ self.set_x_vector(constants.PLAYER_SPEED) def move_up(self): """ Checks if there is a ladder and only then allowes the player to move up """ collided_ladders = pygame.sprite.spritecollide(self,ladder.Ladder.all_ladders,False) if len(collided_ladders) > 0: self.set_y_vector(-20) def move_down(self): """ Checks if there is a ladder and only then allows the player to move down """ self.rect.y += 80 collided_ladders = pygame.sprite.spritecollide(self,ladder.Ladder.all_ladders,False) self.rect.y -= 80 if len(collided_ladders) > 0: self.rect.y = self.rect.y + 130 print 'move down' def jump(self): """ Makes the player jump only after checking if the player is on the ground or standing on a platform """ self.rect.y += 2 collided_blocks = pygame.sprite.spritecollide(self,landforms.Platform.all_blocks,False) self.rect.y -= 2 if len(collided_blocks) > 0 or self.rect.bottom == constants.SCREEN_HEIGHT: self.set_y_vector(-10) def __check_collision(self): """ Checks if the player has collided with any of the game elements such as coin,fireball,princess and donkey.If a player has collided takes appropriate action. """ self.__collect_coin() self.__check_fireball() self.__check_princess() self.__check_donkey() self.__check_cage() def __collect_coin(self): """ Checks if there is a coin at players current position.If it is so then increment the players score and make the coin disappear. """ collided_coins = pygame.sprite.spritecollide(self,landforms.Platform.all_coins,True) for gold_coin in collided_coins: self.score += 5 def __check_fireball(self): """ Checks if the player is hit with a fireball. """ collided_fireballs = pygame.sprite.spritecollide(self,fireball.Fireball.all_fireballs,True) if len(collided_fireballs) > 0: self.life -= 1 self.score -= 25 self.rect.left = 0 self.rect.bottom = constants.SCREEN_HEIGHT def set_princess(self,princess): """ Assigns princess to the player """ self.__princess = princess def __check_princess(self): """ Checks whether the player has reached the princess or not """ flag = pygame.sprite.collide_rect(self,self.__princess) if flag == True: self.__check_princess = True def check_reached_princess(self): """ Returns true if the player has reached the princess """ return self.__check_princess def __check_donkey(self): """ Checks if the player has collided with a donkey.If it has ,reduces the life and points of the player and sends him back to the starting position. """ collided_donkeys = pygame.sprite.spritecollide(self,donkey.Donkey.all_donkeys,False) if len(collided_donkeys) > 0: print 'Collided with donkey' self.life -= 1 self.score -= 25 self.rect.left = 0 self.rect.bottom = constants.SCREEN_HEIGHT def __check_cage(self): """ Restricts the player to move through the cage """ collided_cages = pygame.sprite.spritecollide(self,cage.CageOne.all_cages,False) for cage_block in collided_cages: self.rect.left = cage_block.rect.right
8a1bab3272fd58fe4999fe571fa7eb58f1cac9e4
Souravvk18/Python-Project
/dice_roll.py
1,204
5
5
''' The Dice Roll Simulation can be done by choosing a random integer between 1 and 6 for which we can use the random module in the Python programming language. The smallest value of a dice roll is 1 and the largest is 6, this logic can be used to simulate a dice roll. This gives us the start and end values to use in our random.randint() function. Now let’s see how to simulate a dice roll with Python: ''' #importing module for random number generation import random #range of the values of a dice min_val = 1 max_val = 6 #to loop the rolling through user input roll_again = "yes" #loop while roll_again == "yes" or roll_again == "y": print("Rolling The Dices...") print("The Values are :") #generating and printing 1st random integer from 1 to 6 print(random.randint(min_val, max_val)) #generating and printing 2nd random integer from 1 to 6 print(random.randint(min_val, max_val)) #asking user to roll the dice again. Any input other than yes or y will terminate the loop roll_again = input("Roll the Dices Again?") ''' Rolling The Dices... The Values are : 2 3 Roll the Dices Again?yes Rolling The Dices... The Values are : 1 5 '''
b836b5f8ee930033348291d83be460e57ef5fd0d
Souravvk18/Python-Project
/text_based.py
861
4.34375
4
''' you will learn how to create a very basic text-based game with Python. Here I will show you the basic idea of how you can create this game and then you can modify or increase the size of this game with more situations and user inputs to suit you. ''' name = str(input("Enter Your Name: ")) print(f"{name} you are stuck at work") print(" You are still working and suddenly you you saw a ghost, Now you have two options") print("1.Run. 2.Jump from the window") user = int(input("Choose 1 or 2: ")) if user == 1: print("You did it") elif user == 2: print("You are not that smart") else: print("Please Check your input") ''' output- Enter Your Name: sourav sourav you are stuck at work You are still working and suddenly you you saw a ghost, Now you have two options 1.Run. 2.Jump from the window Choose 1 or 2: 2 You are not that smart '''
8817f472e24034a7157bd400da6f7ee26eb5cc69
HoNedAy/lemon_erp
/qcd/lession.py
5,813
4.1875
4
# 名字命名规则 # (1)只能包含数字、字母、下划线 # (2)不能以数字开头 # (3)不能使用关键字 # 可以通过import keyword # print(keyword.kwlist)打印关键字 # ctrl+/也可以多行注释 # import keyword # print("打印到控制台") # print(type(12)) # print(type(3.14)) # print(isinstance(12,int)) # print("刚刚'你好呀'下雨啦") # print("刚刚\"人名\"下雨啦") # print(""" # 今天下雨了没 # 今天没下雨 # 今天学python # """) #切片取多个值===字符串取值,索引从0开始 0.1.2.3 #步长:隔几步取值 # str="今天1天气真好!" # print(str[0:3:2])#隔2步取值,取索引值为0,2的字符串 # print(str[1:6:2])#隔2步取值,取索引为1,3,5的字符串 # print(str[-1])#-1代表最后一个元素 # print(str[::-1])#从右向左取值 # # print(str1[0:len(str1):1])#从0开始取值,len()是str1字符串的长度 # # str1="12今天你学习了吗?" # # str2=str1.replace("12","新的值") # # # print(str2) # # print(str1.index('学习'))#获取元素开始的位置--索引--字符串不存在的时候会报错 # # print(str1.find('学习'))#获取元素开始的位置--索引--字符串不存在的时候不会报错,会返回-1 # # name='皮卡丘' #--0--索引 # age=18 #--1--索引 # gender='Female' #--2--索引 # print(''' # ---{1}同学的信息---- # name:{1} # age:{2} # gender:{3}'''.format(name,name,age,gender) # ) # print(10+80) # print('按时'+'交作业') # print(str(123)+'向前走呀') #123要转化为字符串:str()--内置函数:int(),float(),bool() # a=10 # a += 5 #a=a+5 a=15 # print(a) # a-=10 #a=a-10 # print(10>8 and 5>6) #--True and Flase ==False # print(10>8 or 5>6) #--True or Flase ==True # print( not 10>8 ) #--True--> Flase # str="hello word" # print('ee' in str) # print('ee' not in str) # # list=[12,'你好呀',True,3.14,['皮卡丘','天天','妍妍']] #定义一个空列表---往列表里添加元素 # # print(list[0:3]) #切片取值 # # print(list[4][0]) #列表的嵌套取值,取索引为0的字符串 # #增加 # list.append('小雪') #追加到元素的末尾---最常用的 # list.insert(2,'伊呀呀呀') #在指定的位置添加元素 # list.extend(['aaa','鲍鱼','卡罗尔']) #一次添加多个元素,不是以整体添加的 # list.append(['aaa','鲍鱼','卡罗尔']) #一次添加多个元素,是以整体添加的--列表的形式添加 # print(list) # # #修改 # list[0]='卡卡' #添加索引为0的元素 # list[1]='123456' #添加索引为1的元素 # list.insert(1,'卡卡') # list.remove('卡卡') #重复元素,只删除第一个遇见的元素 # list.insert(0,['卡卡','卡卡']) #指定位置天机多个元素 # list.remove('卡卡') #删除了不是整体的卡卡 # print(list.count('伊呀呀呀')) #统计某个元素出现的次数 # print(len(list)) # tuple_1=('皮卡丘','南瓜','涵涵') #取变量名如果用了内置函数的名字的话--调用这个内置函数时就会报错。 # # tuple1[0]='麦克' #指定修改会报错 # #转换---要想修改元素,可以转换成列表添加元素 # list1=list(tuple_1) #元组-->列表 # list1.append('杰克') #添加元素,在最末尾添加 # tuple_1=tuple(list1) #列表-->元组 # print(tuple_1) # dict1={'name':'皮卡丘','age':18,'weight':'80','height':160} # print(dict1) # #取值 --- # print(dict1['name'],dict1['weight']) #key取value # print(dict1.get('weight')) #get方法里面放的也是key # #增加+修改 # dict1['gender']='Female' #key不存在的话,则增加一个键值对 ---增加元素 # dict1['name']='卡卡' #key存在的话,则改变value值 # #删除 # dict1.pop('gender') #必须指定一个key来删除key:value # #修改 # dict1.update({'city':'广州','hobby':'写代码'}) #增加 多个元素的时候---用update # print(dict1) # #集合 :set --{} --无序 # list1=[11,22,33,44,55,88,99] #含有重复数据的 # set1=set(list1) #列表--->集合 =====去重操作 # print(set1) #控制流 # money=int(input('输入金额:')) #----input() #输入的变量是字符串类型的----要转换为整型int # if money>=600: # print('买大房子') # elif money>=100: # print('买小房子') # elif money==50: # print('买小车子') # else: # print('继续搬砖') #For循环 # str='今天学习了思维课程' #定义了一个字符串变量 # count=0 #定义了一个计时器,用来计算循环次数的 # for item in str: # if(item=='天'): # # break # continue #--中断,后面的还会执行,只跳出了本次循环 # elif(item=='思'): # break # ---中断,后面的不会再执行的,跳出了整个循环 # print(item) # # print('*'*10) # count+=1 #每次循环,值自加1 # print(count) #打印循环次数 # print(len(str)) # #range--开始(默认0),结束,步长(默认1) # # for num in range(0,60,2): # # print(num) # # # name=input('请输入姓名:') # age=input('请输入年龄:') # sex=input('请输入性别:') # print( # ''' # ********************* # 姓名:{1} # 年龄:{2} # 性别:{3} # ******************** '''.format(name,age,sex,name) # ) # # # str1 = 'python hello aaa 123123aabb' # # 1)请取出并打印字符串中的'python'。 # print(str1[0:7:1]) # # 2)请分别判断 'o a' 'he' 'ab' 是否是该字符串中的成员? # print( 'o a' in str1) # print( 'he' in str1) # print( 'ab'in str1) # # 3)替换python为 “lemon”. # str1 =str1.replace('python','lemon') # print(str1) # # 4) 找到aaa的起始位置 # print(str1.index('aaa')) # print("kjhjk") #单元格里面的内容
df58a62863d9eede2e9dba8466d4530364b60ffc
0x000552/python
/coursera/diving_in_python/study_process.py
3,100
3.59375
4
""" os.fork """ """ import os pid = os.fork() if pid == 0: print(f"MAIN pid: {pid}") else: print(f"CHILD pid: {pid}") """ """ multiprocessing """ from multiprocessing import Process def f(_str): print(f"amazing process! _str = {_str}") prcs1 = Process(target=f, kwargs={"_str": "WOW"}) prcs1.start() # creating process and start it prcs1.join() # waiting for our child... print("\n\nAnd now let's try Process class inheritance (from Process class):") class MyProcess(Process): def __init__(self, **kwargs): # kwargs only for practice... super().__init__() self._str = kwargs["_str"] def run(self): print() print(f"amazing process! _str = {self._str}") prcs2 = MyProcess(_str="DOUBLE WOW") prcs2.start() prcs2.join() print("\n\nNow let's try multiprocessing.Pool:") from multiprocessing import Pool import os def func_for_pool(x): print(f"{os.getpid()}: {x} ") return x**9 with Pool(5) as p: print(p.map(func_for_pool, [*range(5)])) print("\n\nNow let's try thread with concurrent module:") from concurrent.futures import ThreadPoolExecutor, as_completed from random import randint from time import sleep def f(id_): slp_time = randint(0, 2) print(f"BEGIN: {id_:2}; slp_time: {slp_time}") sleep(slp_time) print(f"END {id_:2};") return id_ with ThreadPoolExecutor(max_workers=2) as pool: thrds = [pool.submit(f, i) for i in range(1, 2)] sleep(1) for future in as_completed(thrds): print(f"id: {future.result():2} completed") print("\n\nRLock and Conditions...") from concurrent.futures import ThreadPoolExecutor, as_completed from random import randint from time import sleep import threading class Queue(object): def __init__(self, size=5): self._size = size self._queue = [] self._mutex = threading.RLock() self._empty = threading.Condition(self._mutex) self._full = threading.Condition(self._mutex) def put(self, val): with self._full: while len(self._queue) >= self._size: self._full.wait() self._queue.append(val) self._empty.notify() def get(self): with self._empty: while len(self._queue) == 0: self._empty.wait() ret = self._queue.pop(0) self._full.notify() return ret def f_queue_put(queue, thread_id): print(f"Th {thread_id} put") queue.put(thread_id) print(f"Th {thread_id} end") def f_queue_get(queue, thread_id): print(f"Th {thread_id} get") print(f"Th {thread_id} gotten: {queue.get()}") print(f"Th {thread_id} end") queue = Queue() print("\n\nThreadPoolExecutor...") with ThreadPoolExecutor(max_workers=6) as pool: thrds_get = [pool.submit(f_queue_get, queue, i) for i in range(3)] sleep(3) thrds_put = [pool.submit(f_queue_put, queue, i+3) for i in range(3)] for thrd in as_completed(thrds_get): thrd.result() for thrd in as_completed(thrds_put): thrd.result() print("That's all")
d8a388914e511f6697eeb9cbb91f6099d086a025
mrgold92/Python_Complete
/01-Conceptos-Básicos/01.04-Trabajando-con-Fechas.py
1,445
3.96875
4
##################################################################### # Trabajando con fechas # ##################################################################### # # # Sintaxis: datetime.now() # # datetime.now().date() # # datetime.now().today() # # # # datetime.strptime("11-03-1998", "%d-%m-%Y").date() # # print(datetime.now().strftime("%A, %d %m, %Y") # # # ##################################################################### from datetime import datetime # Almacenamos en la variable dt1 la fecha actual del sistema dt1 = datetime.now().date() print("Fecha1: ", dt1) # Almacenamos en la variable dt2 la fecha y hora actual del sistema dt2 = datetime.now() print("Fecha2: ", dt2) # Convertimos un valor alfanúmerico en fecha utilizando STRPTIME fecha = input("Escribe tu fecha de nacimiento: ") dt3 = datetime.strptime(fecha, "%d-%m-%Y").date() # Mostramos por pantalla una fecha formateada print("Fecha3: ", dt3.strftime("%A, %d %B, %Y")) # Calculos entre fechas años = dt1.year - dt3.year print(f"Tienes {años} años.")
52a46f8b6b37582af42e5b4eaad702e4022c849b
mrgold92/Python_Complete
/01-Conceptos-Básicos/Ejercicios/01_Calcular-la-Edad.py
355
3.84375
4
from datetime import datetime fecha = input("Escribe tu fecha de nacimiento: ") fnDt = datetime.strptime(fecha, "%d-%m-%Y").date() hoyDt = datetime.now().date() edad = hoyDt.year - fnDt.year if(edad >= 18): print(f"Tienes {edad} años, eres mayor de edad.") else: años = 18 - edad print(f"Te faltan {años} años para ser mayor de edad.")
c4f321d41afb37bc7f0e97c71426e67ab9a7a76b
mrgold92/Python_Complete
/99-Base-de-Datos/99.05-SQLite.py
1,773
3.625
4
import sqlite3 import sys from typing import Sized #Establecemos conexión con la base de datos, indicando la ruta del fichero #Si el fichero no exite, se crea connection = sqlite3.connect('.\\Ficheros\\demo.db') #Creamos un cursor que nos permite ejecutar comandos en la base de datos cursor = connection.cursor() #En una base de datos nueva, necesitamos inicialmente crear las tablas #Estas sentencias se ejecutan una sola vez command = "SELECT count() FROM sqlite_master WHERE type = 'table' AND name = 'Alumnos'" cursor.execute(command) tablas = cursor.fetchone()[0] if (tablas == 0): command = "CREATE TABLE Alumnos (id, nombre, apellidos, curso, notas)" cursor.execute(command) #Consultar datos command = "SELECT * FROM Alumnos" cursor.execute(command) r = cursor.fetchone() while (r): print(r) r = cursor.fetchone() print("") cursor.execute(command) data = cursor.fetchall() for r in data: print(r) print("") for r in cursor.execute(command): print(r) #Insertar un registro en la base de datos command = "INSERT INTO Alumnos (id, nombre) VALUES ('A00', 'Borja')" command = "INSERT INTO Alumnos VALUES ('A00', 'Borja', 'Cabeza', '2B', Null)" cursor.execute(command) connection.commit() #Insertar varios registros en la base de datos listaAlumnos = [('H32', 'Ana', 'Trujillo', '2B', None), ('5H2', 'Adrian', 'Sánchez', '2C', None), ('A9C', 'José', 'Sanz', '2A', None)] command = "INSERT INTO Alumnos VALUES (?, ?, ?, ?, ?)" cursor.executemany(command, listaAlumnos) connection.commit() #Actualiza registros command = "UPDATE Alumnos SET apellidos = 'Sanz' WHERE id = '5H2'" cursor.execute(command) connection.commit() #Eliminar registros command = "DELETE Alumnos WHERE id = '5H2'" cursor.execute(command) connection.commit()
21c438ce49cd3cb187e43b05a74daae410d7db9d
lutingying/lutingying
/HW4.py
5,613
3.921875
4
#HW #4 #Due Date: 07/27/2018, 11:59PM EST #Name: class Node: def __init__(self, value): self.value = value self.next = None def __str__(self): return "Node({})".format(self.value) __repr__ = __str__ class Stack: # ------- Copy and paste your Stack code here -------- def __init__(self): self.top = None def __str__(self): temp=self.top out='' while temp: out+=str(temp.value)+ '\n' temp=temp.next return ('Top:{}\nStack:\n{}'.format(self.top,out)) __repr__=__str__ def isEmpty(self): #write your code here return self.top==None def size(self): #write your code here count, curr=0, self.top while curr!=None: count+=1 curr=curr.next return count def peek(self): #write your code here return self.top def push(self,value): #write your code here tmp=None if isinstance(value, Node):tmp=value else:tmp=Node(value) if not self.top:self.top=tmp else: # node=self.top # while node.next:node=node.next # node.next=tmp tmp=Node(value) tmp.next = self.top self.top = tmp def pop(self): #write your code here if self.top==None: return 'Stack is empty' tmp=self.top self.top=self.top.next return tmp # ------- Stack code ends here -------- class Vertex: def __init__(self,value): self.value = value self.connectedTo = {} def addNeighbor(self,node,weight=1): self.connectedTo[node] = weight def __str__(self): return str(self.value) + ': ' + str([x.value for x in self.connectedTo]) class Graph: def __init__(self): self.vertList = {} def __iter__(self): return iter(self.vertList.values()) def getVertex(self,key): if key in self.vertList: return self.vertList[key] else: return None def addVertex(self,key): new_node = Vertex(key) self.vertList[key] = new_node return new_node def addEdge(self,frm,to,weight=1): if frm not in self.vertList: new_node = self.addVertex(frm) if to not in self.vertList: new_node = self.addVertex(to) self.vertList[frm].addNeighbor(self.vertList[to], weight) def dfs(self, start): # ---- Write your code here #print(self.vertList[start]) #return if start is None: return ls=[] ls.append(start) visited=[] s=Stack() s.push(start) visited.append(start) char='ABCDEFGHIJKLMNOPQRSTUVWXYZ' ######################################### while s.size()!=0: v=s.pop() ######################################### if v not in visited: visited.append(v) convert_str=str(self.vertList[v.value]) ################################ for k in range(100): for j in char: if j not in visited and j in convert_str: ################### """ cls=[] for u in convert_str: if u>='A' and u<='Z': if u!=convert_str[0]: cls.append(ord(u)) min_ls_value=min(cls) #print(min_ls_value) i=chr(min_ls_value) """ ################### for i in convert_str: if i>='A' and i<='Z': if i!=convert_str[0] and i not in visited: ls.append(i) v=i visited.append(v) convert_str=str(self.vertList[v]) s.push(i) break else: continue ##################################### if start=='F': ls.append('C') return ls """ print(str(self.vertList[start])) convert_str=str(self.vertList[start]) for i in convert_str: if i>='A' and i<='Z': if i!=convert_str[0]: print(i) else: continue #print(convert_str) """ """ for i in str(self.vertList[start]): print("lo ", i) """ #print(s.pop()) #return """ while s.size()>0: cur=visited.pop() for i in cur: if i not in visited: visited.append(cur) visited.append(i) self.vertList[cur].addNeighbor(self.vertList[i], 1) print(self.vertList[i]) break """
6d9e4b5517e4777ccbca6cb1df0f83b7aae20377
lian88jian/py_everything_exercise
/src/pack_2016_10_17_hundred_example/10/14.py
328
3.828125
4
#分解质因数 num = 90; primeArr = []; i = 2; while i <= num: if num % i == 0: primeArr.append(i); num /= i; else: i += 1; for i in range(len(primeArr)): if i == 0: print('%d' % primeArr[i],end=""); else: print(' * %d' % primeArr[i],end="");
00223ca3e0e0c4c268f44aa23bc58416a8e3ef1e
lian88jian/py_everything_exercise
/src/pack_2016_10_17_hundred_example/10/13.py
185
3.59375
4
def tripe(n): n = int(n); return n ** 3; for i in range(100,1000): str = '%d' % i; if i == tripe(str[0]) + tripe(str[1]) + tripe(str[2]): print(i);
3658371393c2ccd2ba58a3f6a15ac3a310f17520
saurify/A2OJ-Ladder-13
/54_cosmic_tables.py
1,289
3.5
4
'''def colchanger(l,x,y,n): for i in range(n): l[i][x-1],l[i][y-1]=l[i][y-1], l[i][x-1] def rowchanger(l,x,y,m): for i in range(m): l[x-1][i],l[y-1][i]=l[y-1][i], l[x-1][i]''' def main(): '''n, m, k = map(int, input().split()) R = {str(i): i - 1 for i in range(n+1)} C = {str(i): i - 1 for i in range(m+1)} ans = [] l = [input().split() for i in range(n)] for i in range(k): q, x, y = input().split() if q == 'c': C[x], C[y] = C[y], C[x] elif q == 'r': R[x], R[y] = R[y], R[x] else: ans.append(l[R[x]][C[y]]) print('\n'.join(ans))''' n,m,k = map(int, input().split()) l=[] for i in range(n): l.append(list(map(int, input().split()))) #q=[] r=dict() c=dict() #for zzz in range(k): # s,x,y= [i for i in input().split()] # q.append([s, int(x),int(y)]) for j in range(k): s,a,b= input().split() if s=='g': print(l[int(r.get(a,a))-1][int(c.get(b,b))-1]) elif s=='r': r[a],r[b]=r.get(b,int(b)),r.get(a,int(a)) #for i in range(n): #l[i][j[1]-1],l[i][j[2]-1]=l[i][j[2]-1], l[i][j[1]-1] #colchanger(l,i[1],i[2],n) else: c[a],c[b]=c.get(b,int(b)),c.get(a,int(a)) #for i in range(m): #l[j[1]-1][i],l[j[2]-1][i]=l[j[2]-1][i], l[j[1]-1][i] #rowchanger(l,i[1],i[2],m) return 0 if __name__ == '__main__': main()
8fba0b74dc2c82cc0adcd0d6f81cc0031131f65c
saurify/A2OJ-Ladder-13
/37_bank.py
198
3.5
4
def main(): n=input() if int(n)<0: if int(n[:-1])>int(n[:-2]+n[-1]): print(int(n[:-1])) else: print(int(n[:-2]+n[-1])) return 0 print(n) return 0 if __name__ == '__main__': main()
28ea536957a9ee992179ac18b326edd81309d4bb
chengweilin114/direct_capstone2020
/codes/summarize.py
5,467
3.5625
4
import pandas as pd import datetime from dataloader import dataloader def get_actual_peaks(load_df): """ Arguments: load_df: The entire actual demand datasets. Return: peaks_df: Keep the highest demand for each day. This function keeps the highest demand (the peak hour) for each day. """ # Create a new column to hold rankings in a day rankings = load_df.groupby(['season', load_df.ts.dt.date] ).adjusted_demand_MW.rank(ascending=False) load_df['rankings_per_day'] = rankings mask = load_df['rankings_per_day'] == 1.0 peaks_df = load_df[mask] # Reset index peaks_df.reset_index(drop=True, inplace=True) return peaks_df def get_top_n_peaks(peaks_df, n_peaks_to_use): """ Arguments: peaks_df: A dataframe. The peak hours for each day. n_peaks_to_use: An int. Number of top peaks to use in each season. Return: A dataframe. The top n_peaks_to_use peaks in each season. This function keeps the top n_peaks_to_use peak hours in each season. """ # Create a new column to hold rankings in a year rankings = peaks_df.groupby(['season'] ).adjusted_demand_MW.rank(ascending=False) peaks_df['rankings_per_season'] = rankings mask = peaks_df['rankings_per_season'] <= float(n_peaks_to_use) top_n_peaks = peaks_df[mask] return top_n_peaks def summarize_top_n(peaks_df, forecasts, n_peaks_to_use): """ Arguments: peaks_df: A dataframe. The peak hours for each day. forecasts: A dataframe. The entire forecasting results. n_peaks_to_use: An int. Number of top peaks to use in each season Return: Two DataFrames. The first one is the merged results of the actual demand data and forecasting data for the top n_peaks_to_use peaks. The second one is the summary of success rates for the forecasts. This function merges the actual demand data and forecasting data for the top n_peaks_to_use peaks, and calculate the success rates for the forecasts. """ columns_to_keep = ['adjusted_demand_MW', 'demand_MW', 'season', 'ts', 'rankings_per_day', 'rankings_per_season'] top_n_peaks = get_top_n_peaks(peaks_df, n_peaks_to_use) top_n_peaks = top_n_peaks[columns_to_keep] top_n_results = pd.merge(top_n_peaks, forecasts, on='ts') df = top_n_results.groupby(['season']) top_n_sum = df.forecast.apply(lambda x: (x > 0).sum()) return top_n_results, top_n_sum def summarize(peaks_df, forecasts, save_path): """ Arguments: peaks_df: A dataframe. The peak hours for each day. forecasts: A dataframe. The entire forecasting results. save_path: A string. The path to save the summary of forecasts. Return: A DataFrame. The summary of success rates for the forecasts. This function calls the function summarize_top_n and calculate success rates for the forecasts for top 1, top 5, top 10, and top 20 peaks in each season. """ mapper = {} keys_list1 = ['Season', 'Success(%)', 'Top_n'] keys_list2 = ['12', '16', '17', '18', '19', '20'] keys = keys_list1 + keys_list2 for key in keys: mapper[key] = [] for n in [1, 5, 10, 20]: top_n_results, top_n_sum = summarize_top_n(peaks_df, forecasts, n) seasons = top_n_sum.index.values for s in seasons: mapper['Season'].append(s) succ_rate = int(top_n_sum.loc[s]/n*100) mapper['Success(%)'].append(succ_rate) mapper['Top_n'].append(n) mask = top_n_results.season == s season_df = top_n_results[mask] for key in keys_list2: mask = season_df.ts.dt.time == datetime.time(int(key), 0) hour_df = season_df[mask] total_num = hour_df.shape[0] num_hit = hour_df.forecast.gt(0).sum() mapper[key].append(str(num_hit)+'/'+str(total_num)) summary = pd.DataFrame(data=mapper) summary.to_csv(save_path+'Summary.csv') return summary if __name__ == '__main__': actual_load_fname = 'ieso_ga_master_dataset_allWeather_updated2020.csv' forecasts_fname = 'ga_forecasts_top_2.csv' actual_load, forecasts = dataloader(actual_load_fname, forecasts_fname) # Test get_actual_peaks actual_peaks = get_actual_peaks(actual_load) print('Actual peaks:') print(actual_peaks.head(3)) # Test get_top_n_peaks top_n_actual_peaks = get_top_n_peaks(actual_peaks, top_n_to_use=1) print('Top n actual peaks:') print(top_n_actual_peaks.head(3)) # Summarize actual peaks and forecasts # forecasts = forecasts[['ts_future', 'forecast']] # forecasts = forecasts.rename(columns={'ts_future': 'ts'}) mapper = {} top_n_results, top_n_sum = summarize_top_n(actual_peaks, forecasts, 1) print('Top n results:') print(top_n_results.head(3)) print('Top n summary:') print(top_n_sum.head(3)) summary = summarize(actual_peaks, forecasts, save_path='') print('Summary:') print(summary.head(5))
a2c2794cf054e57d43a3f3c4da884f39921d07c1
idkrepp12/python-projects
/jeff.py
221
3.921875
4
import random print("Hi") while True: print("ask me your question...") question = input("> ") answers = ['yes','no','maybe','i dont know','most likley'] answer = random.choice(answers) print(answer)
9257e8280dbb4adba146cdd25edf6cb71cd40ff2
liorys/new-520
/objeto.py
1,818
3.734375
4
#!/usr/bin/python3 import time class Car(): def __init__(self,marca,modelo,ano,cor): self.marca = marca self.modelo = modelo self.ano = ano self.cor = cor self.velocidade = 0 self.combustivel = 'gasolina' def acelerar(self): self.velocidade += 10 print('Acelerando...Velocidade:[{}]'.format(self.velocidade)) def freiar(self): self.velocidade -= 10 print('Freiando...Velocidade:[{}]'.format(self.velocidade)) def parar(self): print('parado...') class Car_eletric(Car): def __init__(self): self.combustivel = 'energia' carro1 = Car('ford','ka',91,'verde') car1 = Car_eletric() car1.ano = 2002 car1.modelo ='BMW' # print(carro1.anda()) while True: time.sleep(0.1) carro1.acelerar() if carro1.velocidade == 200: for x in range(carro1.velocidade): carro1.freiar() time.sleep(0.2) if carro1.velocidade == 0: carro1.parar() break exit() ######## OOP ####### class Dog(): def __init__(self, nome, idade):# definir atributos da classe self.nome = nome self.idade = idade self.energia = 10 def latir(self):# comportamentos print('Au au!') def andar(self): self.energia -= 1 # if self.energia == 0: # print('Estou cansado') print('andando...{}'.format(self.energia)) def dormir(self): self.energia = 10 print('dormindo....{}\n'.format(self.energia)) dog1 = Dog('haush',2) dog2 = Dog('Pele',4) print(dog2.nome) print(dog1.nome) dog1.latir() while True: dog1.andar() time.sleep(0.2) if dog1.energia == 0: print('\nEstou cansado\n') dog1.dormir()
abbf9c92a6558f4cce385ce98b1de1d8a54e31da
liorys/new-520
/frutas-list-def.py
1,347
4.03125
4
#!/usr/bin/python3 from pprint import pprint frutas = [ {'nome':'pera','preco':1.0,'qtd':10}, {'nome':'uva','preco':2.0,'qtd':20}, {'nome':'abacaxi','preco':3.0,'qtd':30}, {'nome': 'morango', 'preco':4.0, 'qtd': 40}, {'nome': 'kiwi', 'preco': 5.0, 'qtd':50}, ] def buscafruta(frutasearch): for fruta in frutas: fruta['nome'] if fruta['nome'] == frutasearch: return ('A fruta existe na lista.') break elif fruta['nome'] != frutasearch: print ('A fruta não existe na lista') resp = input('Caso deseje adicionar na lista digite S: ') if resp.lower() == 's': frutanova = input('Qual o nome da nova fruta ?') preconova = float(input('Qual o valor da nova fruta ?')) qtdnova = int(input('Qual a quantidade deseja inserir? ')) frutas.append({'nome':frutanova,'preco':preconova,'qtd':qtdnova}) print('Nova lista de frutas \n\n',frutas) print('Adicionado com sucesso') while True: select = input('Digite o nome da fruta para pesquisar ou x para sair ') if select.lower() == 'x': print('Saindo do programa . . .') break print(buscafruta(select))
3b9c5b1aa16c865e84fc039d280fa85b0cf2a55a
csrm/python_basics
/temporary_list_sort.py
349
4.03125
4
#List of no.s numbers = [156, 23, 1, 97, 100, 45, 7, 90 ] #Print the list print('Original List:',numbers) #Print the list print('Temporarily sorted the list in Ascending Order:',sorted(numbers)) #Print the list print('Temporarily Sorted List in Descending Order:',sorted(numbers, reverse = True)) #Print the list print(f'The list now is: {numbers}')
b6b0f2782322be0e0945ea3febb734f3b03d7eaa
csrm/python_basics
/pop_from_list.py
297
3.796875
4
my_cars = ["Maruti 800", "Maruti Zen", "Zen Estilo", "WagonR", "Ertiga"] print(f"Original List: {my_cars}") # A pop operation returns the element popped unlike the deletion operation on a list latest_car = my_cars.pop() print(f"Element Popped: {latest_car}") print(f"List after 1st pop operation: {my_cars}")
8b1370186269880ea804974642cc8f7df23a74e8
csrm/python_basics
/element_at_last_index.py
214
4.1875
4
fruits = ['Apple', 'Banana', 'Orange', 'Sapota'] print(f'Original List: {fruits}') print(f'Element at index -1: {fruits[-1]}') print(f'Element at index -2: {fruits[-2]}') print(f'Element at index -5: {fruits[-5]}')
f5ca18d328871f5c41309175725414389239376d
csrm/python_basics
/copy_list.py
664
4.15625
4
#Define a list of food items regular_food = ['Annam', 'Pappu', 'Kura', 'Pacchadi', 'Charu', 'Curd'] #Assign the list regular_food to my_fav_food my_fav_food = regular_food #Copy list regular food to mom_fav_food mom_fav_food = regular_food[:] print(f'Regular Food : {regular_food}\nMy Favourite Food: {my_fav_food}\nMom Favourite Food {mom_fav_food}') print() #Append ice-cream to mom_fav_food mom_fav_food.append('ice-cream') print(f'Mom Favourite Food : {mom_fav_food}\nRegular Food : {regular_food}') print() #Append milk-mysorepak to my_fav_food my_fav_food.append('Milk MysorePak') print(f'My Favourite Food : {my_fav_food}"\nRegular Food : {regular_food}')
fa4ae23af436a4a6ef8a1b06cbcde8e79d9f608d
csrm/python_basics
/keyword_args.py
390
3.609375
4
def pet_details(animalType, animalName): """Prints the name of the animal & its type""" print(f"I have a {animalType}") print(f"My {animalType.lower()}'s name is {animalName}") animalType = 'Dog' animalName = 'Jimmy' pet_details(animalType = animalType, animalName = animalName) animalType = 'Tiger' animalName = 'Timoti' pet_details(animalName = animalName, animalType = animalType)
7593d1d720dcdc84cfa8c07c6b97f341b96cb87e
HollyMccoy/InCollege
/Profile.py
1,401
3.796875
4
class Profile: def __init__(self, username, firstName, lastName, title, major, schoolName, bio, experience, education): self.experience = [] self.username = username self.firstName = firstName self.lastName = lastName self.title = title self.major = major self.schoolName = schoolName self.bio = bio self.experience = experience #This will be a list of up to 3 Employment objects self.education = education def Print(self): history = "Employment History\n" for h in self.experience: history += ("----------------------------------------\n" + h.Print() + "----------------------------------------\n") return("----------------------------------------\n" + self.firstName + " " + self.lastName + "\n" + self.title + "\n----------------------------------------\n" + "School: " + self.schoolName + "\n" + "About: " + self.bio + "\n\n" + history + "\n" + self.education.Print()) def Write(self): return(self.username + ' ' + self.firstName + ' ' + self.lastName + ' ' + self.title.replace(" ", "_") + ' ' + self.major + ' ' + self.schoolName + ' ' + self.bio.replace(" ", "_") + "\n")
4eb506aafc70283bb2e38cd8fc96dda63600e330
HollyMccoy/InCollege
/menus/Languages.py
1,025
3.921875
4
# Menu commands for the "Languages" submenu # Path: Main menu / important links / privacy policy / guest controls / languages import globals def ShowMenu(): """Present the user with a menu of guest control settings.""" while True: selection = input( "\n" + "-- Languages --: " + '\n\n' \ + f"Current language: {globals.currentAccount.language}" + '\n\n' \ + "[1] English" + '\n' \ + "[2] Spanish" + '\n' \ + f"[{globals.goBack.upper()}] Return to the previous menu" + '\n\n') selection = selection.lower() if (selection == "1"): # Set the language to English globals.currentAccount.language = "English" globals.updateAccounts() elif (selection == "2"): # Set the language to Spanish globals.currentAccount.language = "Spanish" globals.updateAccounts() elif (selection == globals.goBack): # Return to the previous menu return
d0a4ff6900081e99e3ddfa9a9d36c90722460409
Barbara-Diaz/Calculator
/proyecto.py
2,769
3.78125
4
import tkinter as tk from tkinter import messagebox import sys ################################################# def convertir(dato): try: dato=int (dato) return dato except ValueError: try: dato=float(dato) return dato except ValueError: dato="error" return dato def sumar(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error": c=a+b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Error de datos") cTres.insert(0,"error") def restar(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error": c=a-b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Error de datos") cTres.insert(0,"error") def multiplicar(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error": c=a*b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Error de datos") cTres.insert(0,"error") def dividir(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error" and b!=0 and a!=0: c=a/b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Data error") cTres.insert(0,"error") def pedir_info(): messagebox.showerror(title="Information",message="myCalculadora: 01/04/2021") def salir(): respuesta=messagebox.askyesno(title="Question",message="Do you want to exit?") if respuesta: sys.exit() ################################################## ventana=tk.Tk() ventana.config(width=300,height=300) ventana.title("myCalculadora") cUno=tk.Entry() cUno.place(x=20,y=60) cDos=tk.Entry() cDos.place(x=160,y=60) bSuma=tk.Button(text=" + ",command=sumar) bSuma.place(x=20,y=120) bResta=tk.Button(text=" - ",command=restar) bResta.place(x=100,y=120) bMultiplicacion=tk.Button(text=" x ",command=multiplicar) bMultiplicacion.place(x=170,y=120) bDivision=tk.Button(text=" % ",command=dividir) bDivision.place(x=240,y=120) cTres=tk.Entry() cTres.place(x=90,y=200) bSalir=tk.Button(text="Salir",command=salir) bSalir.place(x=200,y=250,width=80,height=40) bInfo=tk.Button(text="Info",command=pedir_info) bInfo.place(x=30,y=250,width=80,height=40) eUno=tk.Label(text="Dato uno") eUno.place(x=20,y=30) eDos=tk.Label(text="Dato dos") eDos.place(x=160,y=30) resultado=tk.Label(text="Resultado") resultado.place(x=90,y=170) ventana.mainloop()
79af9fa8c11bac176eb28de0674851027336dbad
Iernst95/myProjects
/Python-Projects/PetstoreFinalProject/python4401FinalProject.py
4,471
3.84375
4
from Petstore import Cat,Dog,Turtle,Frog,Parrot from Customer import Person import pickle import random def main(): todays_animals = [] create_inventory(todays_animals) print("Welcome to our Pet Store!") print("Every day we have new and exciting animals to buy!\n") name = input("what is your name?: " ) try: infile = open(name,"rb") customer = pickle.load(infile) infile.close() print("\n") print("Hello, ", customer.get_name()) print("\n") customer.new_day() input_check(customer, todays_animals) except FileNotFoundError: print("\nLooks like you're a new customer! \n") customer = Person(name) print("\n") print("Hello, ", customer.get_name()) print("\n") input_check(customer,todays_animals) def input_check(customer, todays_animals): num_check = True while(num_check == True): try: print("What brings you in today?") print("1. I want to show you my pets! ") print("2. I want to buy a pet!" ) print("3. Leave") choice = int(input("What would you like to do?: ")) if int(choice) == 1: animals = len(customer.get_animals()) if(animals==0): print("\nIt looks like you dont have any animals yet! \n") else: show_animals(customer.get_animals()) print("\nIt Looks like you have" , animals, "animals!") print("Very Nice!\n") continue if int(choice) == 2: print("Here is our current inventory: ") show_animals(todays_animals) print("\n") print("Your current balance is: ", customer.get_money(), "$") print("\n") shop_animals(customer, todays_animals) continue if int(choice) == 3: outfile = open(customer.get_name(), "wb") pickle.dump(customer, outfile) outfile.close() num_check = False break except ValueError: print("oops! that wasn't an option!") print("Please enter 1, 2, or 3") def create_inventory(todays_animals): amount = random.randint(5,10) for i in range(amount): animal_num = random.randint(0,4) if(animal_num ==0 ): animal = Cat() todays_animals.append(animal) elif(animal_num == 1): animal = Dog() todays_animals.append(animal) elif(animal_num == 2): animal = Frog() todays_animals.append(animal) elif(animal_num == 3): animal = Turtle() todays_animals.append(animal) elif(animal_num == 4): animal = Parrot() todays_animals.append(animal) def show_animals(animal_list): for i in range(len(animal_list)): animal = animal_list[i] print("Animal #", i) print("Name: ", animal.get_name()) print("Type: ", animal.get_type()) print("Age: ", animal.get_size()) print("Color: ", animal.get_color()) print("Price: ", animal.get_cost(), "$") print("\n") def shop_animals(customer, animal_list): animal_amount = len(animal_list) print("What animal would you like to buy? " ) repeat = True while(repeat): try: selection = int(input("Select an animal #: ")) repeat = False except TypeError: print("please enter a number! ") except ValueError: print("please enter a number! ") if(int(selection) < 0 or int(selection) > animal_amount): print("Sorry, we don't have that animal number! ") else: animal = animal_list[selection] if(animal.get_cost()>customer.get_money()): print("you don't have enough money for this animal!") else: name = input("What would you like to name your new pet?: ") animal.set_name(name) customer.add_animal(animal) customer.bought_animal(animal.get_type(), animal.get_cost()) del animal_list[selection] main()
a4626ca589be214fc375c7c0fe005807cf4f9291
rosekay/data_structures
/lists.py
1,232
4.34375
4
#list methods applied list_a = [15, 13.56, 200.0, -34,-1] list_b = ['a', 'b', 'g',"henry", 7] def list_max_min(price): #list comprehension return [num for num in price if num == min(price) or num == max(price)] def list_reverse(price): #reverse the list price.reverse() return price def list_count(price, num): #checks whether an element occurs in a list return price.count(num) def list_odd_position(price ): #returns the elements on odd positions in a list return [num for num in price if price.index(num) % 2 != 0] def list_total(price): #computes the running total of a list #simple version # return sum(price) #for loop total = 0 for num in price: total += num return total def list_concat(price, new_price): #concatenates two lists together if type(new_price) == list: price.append(new_price) return price else: return "Not a list" def list_merge_sort(price, new_price): #merges two sorted lists into a sorted list price.append(new_price) return sorted(price) print list_max_min(list_a) print list_reverse(list_a) print list_count(list_a, -34) print list_odd_position(list_a) print list_total(list_a ) print list_concat(list_a, list_b) print list_merge_sort(list_a, list_b)
6983b9b8ad8737a418c59ed38256630d3ed7b598
SbSharK/PYTHON
/PYTHON/whileelse.py
246
4.1875
4
num = int(input("Enter a no.: ")) if num<0: print("Enter a positive number!") else: while num>0: if num==6: break print(num) num-=1 else: print("Loop is not terminated with break")
58692a5a7da1097be3d19ba1edc3faf13458e1e7
SbSharK/PYTHON
/PYTHON/lec2.py
589
4.09375
4
#! a=int(input("Enter number 1 ")) b=int(input("Enter number 2 ")) c=int(input("Enter number 3 ")) if a>b and a>c: print("a is largest, value is ",a) elif b>c and b>a: print("b is largest, value is ",b) elif c>a and c>b: print("c is largest, value is ",c) else: if a==b and a==c: print("all are equal, values are ",a) elif a==c: print("a and c are equal, values are ",a) elif a==b: print("a and b are equal, values are ",a) elif b==c: print("b and c are equal, values are ",b) else: print("error")
b05f477cbc8438335692cc426d545cf624035b49
SbSharK/PYTHON
/PYTHON/fileOpen.py
412
3.8125
4
def fileOpen(filename): fd = open(filename) data=fd.readline() count = 0 while data!='': if(count%2!=0): print(data) data=fd.readline() count+=1 else: continue print("\n Number of Lines",count) fd.close() if __name__ == "__main__": filename = input("Enter the Filename/PATH : ") fileOpen(filename)
d6e485bfd4f23e04505e36d53397e39f81832a53
Morgan-Sell/connect-four-oop
/play.py
2,375
3.5
4
import numpy as np from connectfour import Board, Player import pygame import sys game_over = False no_token = 0 p1_token = 1 p2_token = 2 blue = (0, 0, 255) column_count = 7 row_count = 6 square_size = 100 #board_width = column_count * square_size #board_height = row_count * square_size p1_name = input('Player 1 Name: ') p2_name = input('Player 2 Name: ') player1 = Player(p1_name, p1_token) player2 = Player(p2_name, p2_token) board = Board(column_count, row_count, square_size) board.draw_board(blue) ''' while game_over == False: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: # PLAYER ONE'S TURN p1_col = int(input(f'{p1_name}, select a column to drop a token. Options are 0 to {board_width-1}. ' ' )) available_space = board.is_valid_loc(p1_col) # Ask to select another column if space is not available. while available_space == False: print('Ooops! The column that you selected is full.') p1_col = int(input(f'Select a different column. Options are 0 to {board_width-1}.' )) available_space = board.is_valid_loc(p1_col) avail_row = board.find_first_available_row(p1_col) board.update_board(avail_row, p1_col, p1_token) print(board.board) # Check if Player 1 won game_over = board.check_for_winner(player1.token, player1.name) if game_over: break # PLAYER TWO'S TURN p2_col = int(input(f'{p2_name}, select a column to drop a token. Options are 0 to {board_width-1}. ' )) available_space = board.is_valid_loc(p2_col) # Ask to select another column if space is not available. while available_space == False: print('Ooops! The column that you selected is full.') p2_col = int(input(f'Select a different column. Options are 0 to {board_width-1}.' )) available_space = board.is_valid_loc(p2_col) avail_row = board.find_first_available_row(p2_col) board.update_board(avail_row, p2_col, p2_token) print(board.board) game_over = board.check_for_winner(player2.token, player2.name) '''
0ecddbc90aaf35f0fb28351b096deb152ebd0e44
tuhiniris/Python-ShortCodes-Applications
/patterns1/hollow inverted right triangle star pattern.py
374
4.1875
4
''' Pattern Hollow inverted right triangle star pattern Enter number of rows: 5 ***** * * * * ** * ''' print('Hollow inverted right triangle star pattern: ') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(i,rows+1): if i==1 or i==j or j==rows: print('*',end=' ') else: print(' ',end=' ') print('\n',end='')
122de28469b09f5f0050d9e6c5001fedeb90b94e
tuhiniris/Python-ShortCodes-Applications
/patterns2/number pattern_triangle_15.py
348
3.953125
4
''' Pattern Enter number of rows: 5 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 ''' print('Number pattern: ') counter=1 k=1 number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,counter+1): if k==10: k=1 print(k,end=' ') k+=1 print() counter*=2
0215399d8173998139d327bfd73917982e9a4e7a
tuhiniris/Python-ShortCodes-Applications
/array/right rotate an array.py
797
4.3125
4
from array import * arr=array("i",[]) n=int(input("Enter the length of the array: ")) for i in range(n): x=int(input(f"Enter the elements into array at position {i}: ")) arr.append(x) print("Origianl elements of the array: ",end=" ") for i in range(n): print(arr[i],end=" ") print() #Rotate the given array by n times towards left t=int(input("Enter the number of times an array should be rotated: ")) for i in range(0,t): #stores the last element of the array last = arr[n-1] for j in range(n-1,-1,-1): #Shift element of array by one arr[j]=arr[j-1] #last element of array will be added to the end arr[0]=last print() #Display resulting array after rotation print("Array after left rotation: ",end=" ") for i in range(0,n): print(arr[i],end=" ") print()
a38424508206bc52de7afef6400f0a031773a349
tuhiniris/Python-ShortCodes-Applications
/class and objects/Use of self parameter and to maintain state of an object.py
1,198
3.90625
4
''' Description: ------------ When objects are instantiated, the object itself is passed into the self parameter. The Object is passed into the self parameter so that the object can keep hold of its own data. ''' print(__doc__) print('-'*25) class State(object): def __init__(self): global x x=self.field = 5.0 def add(self, x): self.field += x def mul(self, x): self.field *= x def div(self, x): self.field /= x def sub(self, x): self.field -= x n=int(input('Enter a valued: ')) s = State() print(f"\nAfter intializing the varaiable, the value of variable is: {s.field}") s.add(n) # Self is implicitly passed. print(f"\nAddition of the initalized variable {x} with {n} is: {s.field}") s.mul(n) # Self is implicitly passed. print(f"\nMultiplication of the initalized variable {x} with {n} is: {s.field}") s.div(n) # Self is implicitly passed. print(f"\nSubtraction of the initalized variable {x} with {n} is: {s.field}") s.sub(n) # Self is implicitly passed. print(f"\nDivision of the initalized variable {x} with {n} is: {s.field}")
88c8659d9a348812fa58d4e47ef7c7d801f744c7
tuhiniris/Python-ShortCodes-Applications
/basic program/print all possible combinations from the digits.py
570
3.78125
4
##Problem Description ##The program takes three distinct numbers and prints all possible combinations from the digits. while True: a=int(input("Enter the first number: ")) b=int(input("Enter the second number: ")) c=int(input("Enter the third number: ")) d=[] d.append(a) d.append(b) d.append(c) for i in range(0,3): for j in range(0,3): for k in range(0,3): if(i!=j and j!=k and k!=i): print(d[i],d[j],d[k]) print("-----------------------------") continue
6a157dd21d9cdff8fbd373649f1a5dead92151ac
tuhiniris/Python-ShortCodes-Applications
/basic program/print the sum of negative numbers, positive even numbers and positive odd numbers in a given list.py
779
4.125
4
n= int(input("Enter the number of elements to be in the list: ")) even=[] odd=[] negative=[] b=[] for i in range(0,n): a=int(input("Enter the element: ")) b.append(a) print("Element in the list are: {}".format(b)) sum_negative = 0 sum_positive_even = 0 sum_positive_odd = 0 for j in b: if j > 0: if j%2 == 0: even.append(j) sum_positive_even += j else: odd.append(j) sum_positive_odd += j else: negative.append(j) sum_negative += j print("Sum of all positive even numbersin the list, i.e {1} are: {0}".format(sum_positive_even,even)) print("Sum of all positive odd numbers in the list, i.e {1} are: {0}".format(sum_positive_odd,odd)) print("Sum of all negative numbers in the list, i.e {1} are: {0}".format(sum_negative,negative))
987fdb176bd3aba61e03f288233d20db427e47df
tuhiniris/Python-ShortCodes-Applications
/array/print the number of elements of an array.py
611
4.40625
4
""" In this program, we need to count and print the number of elements present in the array. Some elements present in the array can be found by calculating the length of the array. """ from array import * arr=array("i",[]) n=int(input("Enter the length of the array: ")) for i in range(n): x=int(input(f"Enter the elements of the array at position {i}: ")) arr.append(x) print("elements in the array: ",end=" ") for i in range(n): print(arr[i],end=" ") print() #Number of elements present in the array can be found by using len() print(f"Number of elements present in given array: {len(arr)}")
d282b4996d72d792df13ba6d25f541a0411a286f
tuhiniris/Python-ShortCodes-Applications
/file handling/Count the Number of Blank Spaces in a Text File.py
433
4.03125
4
''' Problem Description: -------------------- The program reads a file and counts the number of blank spaces in a text file. ''' print(__doc__) print('-'*25) fileName=input('Enter file name: ') k=0 with open(fileName,'r')as f: for line in f: words=line.split() for i in words: for letter in i: if letter.isspace: k+=1 print('Occurance of blank space in text file \'{%s}\' is %d times'%(fileName,k))
4ff69ac15644ff508436eac964f4e3f8be11ea2e
tuhiniris/Python-ShortCodes-Applications
/tuples/convert tuple to string.py
160
3.59375
4
''' You can use join() method to convert tuple into string. ''' test = ("America", "Canada", "Japan", "Italy") strtest = ' '.join(test) print(strtest)
7139cde7a49d54db3883ae161d1acecf942489ed
tuhiniris/Python-ShortCodes-Applications
/list/Reversing a List.py
1,808
5.03125
5
print("-------------METHOD 1------------------") """ Using the reversed() built-in function. In this method, we neither reverse a list in-place (modify the original list), nor we create any copy of the list. Instead, we get a reverse iterator which we use to cycle through the list. """ def reverse(list): return [ele for ele in reversed(list)] list=[] n=int(input("Enter size of the list: ")) for i in range(n): data=int(input("Enter elements of list: ")) list.append(data) print(f"elements of the list: {list}") print(f"Reverse of the list is: {reverse(list)}") print("-------------METHOD 2--------------------") """ Using the reverse() built-in function. Using the reverse() method we can reverse the contents of the list object in-place i.e., we don’t need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list. """ def reverse(list): list.reverse() return list list=[] n=int(input("Enter size of the list: ")) for i in range(n): data=int(input("Enter elements of list: ")) list.append(data) print(f"elements of the list: {list}") print(f"Reverse of the list is: {reverse(list)}") print("---------------METHOD 3-------------------") """ Using the slicing technique. In this technique, a copy of the list is made and the list is not sorted in-place. Creating a copy requires more space to hold all of the existing elements. This exhausts more memory. """ def reverse(list): new_List=list[::-1] return new_List list=[] n=int(input("Enter size of the list: ")) for i in range(n): data=int(input("Enter elements of list: ")) list.append(data) print(f"elements of the list: {list}") print(f"Reverse of the list is: {reverse(list)}")
584171438444fc7001b68698651b725933f58b26
tuhiniris/Python-ShortCodes-Applications
/patterns2/program to print 0 or 1 square number pattern.py
390
4.1875
4
''' Pattern Square number pattern: Enter number of rows: 5 Enter number of column: 5 11111 11111 11111 11111 11111 ''' print('Square number pattern: ') number_rows=int(input('Enter number of rows: ')) number_columns=int(input('Enter number of columns:')) for row in range(1,number_rows+1): for column in range(1,number_columns+1): print('1',end='') print('\n',end='')
e06defb7a919a2a12e11189c112c5bb885455813
tuhiniris/Python-ShortCodes-Applications
/class and objects/Iteration overloading Methods.py
802
4.09375
4
''' Discription: ----------- The __iter__ returns the iterator object and is implicitly called at the start of loops. The __next__ method returns the next value and is implicitly called at each loop increment. __next__ raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. ''' print(__doc__,end='') print('-'*50) class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 for num in Counter(5, 15): print(num)
7166cac047616cf383f96c4584f7cf8a756ede9e
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_29.py
327
4.25
4
""" Example: Enter number: 5 A B C D E A B C D A B C A B A """ print('Alphabet Pattern: ') number_rows = int(input("Enter number of rows: ")) for row in range(1,number_rows+1): print(" "*(row-1),end="") for column in range(1,number_rows+2-row): print(chr(64+column),end=" ") print()
fec7edf8eb0203ce4f31868dbea9811946200e53
tuhiniris/Python-ShortCodes-Applications
/patterns2/rhombus or parallelogram star pattern.py
824
4.0625
4
''' Pattern 4 Enter rows: 5 Rhombus star pattern ***** ***** ***** ***** ***** ''' print('rhombus star pattern:') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(0,rows-i): print(' ',end=" ") for j in range(1,rows+1): print('*',end=" ") print('\n',end=' ') print('------------------------------------') ''' Pattern 4 Parallelogram star pattern Enter rows: 5 Enter column: 10 ************ ************ ************ ************ ************ ''' print('Parallelogram star pattern') rows=int(input('enter number of rows: ')) columns=int(input('Enter number of columns: ')) for i in range(1,rows+1): for j in range(0,rows-i): print(' ',end=" ") for j in range(1,columns+1): print('*',end=' ') print('\n',end=" ")
f8327e9e9ed9601eb9570777acb835a08f5a9fed
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_18.py
450
4.0625
4
''' Pattern: Enter number of rows: 5 E E E E E E E E E D D D D D D D C C C C C B B B A ''' print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): print(' '*(row-1),end=' ') for column in range(1,number_rows+2-row): print(chr(65+number_rows-row),end=' ') for column in range(2,number_rows+2-row): print(chr(65+number_rows-row),end=' ') print()
3f868bcc92790acb85e72e8033d29bde05db17a1
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_12.py
302
4.15625
4
''' Alphabet Pattern: Enter number of rows: 5 A A A A A B B B B B C C C C C D D D D D E E E E E ''' print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+1): print(chr(64+row),end=' ') print()
05245453d39856168dbc249ebf5de56d659b338c
tuhiniris/Python-ShortCodes-Applications
/number programs/determine whether a given number is a happy number.py
1,573
4.25
4
""" Happy number: The happy number can be defined as a number which will yield 1 when it is replaced by the sum of the square of its digits repeatedly. If this process results in an endless cycle of numbers containing 4,then the number is called an unhappy number. For example, 32 is a happy number as the process yields 1 as follows 3**2 + 2**2 = 13 1**2 + 3**2 = 10 1**2 + 0**2 = 1 Some of the other examples of happy numbers are 7, 28, 100, 320 and so on. The unhappy number will result in a cycle of 4, 16, 37, 58, 89, 145, 42, 20, 4, .... To find whether a given number is happy or not, calculate the square of each digit present in number and add it to a variable sum. If resulting sum is equal to 1 then, given number is a happy number. If the sum is equal to 4 then, the number is an unhappy number. Else, replace the number with the sum of the square of digits. """ #isHappyNumber() will determine whether a number is happy or not num=int(input("Enter a number: ")) def isHappyNumber(num): rem = sum = 0 #Calculates the sum of squares of digits while(num > 0): rem = num%10 sum = sum + (rem*rem) num = num//10 return sum result = num while(result != 1 and result != 4): result = isHappyNumber(result) #Happy number always ends with 1 if(result == 1): print(str(num) + " is a happy number") #Unhappy number ends in a cycle of repeating numbers which contain 4 elif(result == 4): print(str(num) + " is not a happy number")
091a210b5cc80d42ce28a35b80b7186e808ae101
tuhiniris/Python-ShortCodes-Applications
/strings/find the frequency of characters.py
1,095
4.3125
4
""" To accomplish this task, we will maintain an array called freq with same size of the length of the string. Freq will be used to maintain the count of each character present in the string. Now, iterate through the string to compare each character with rest of the string. Increment the count of corresponding element in freq. Finally, iterate through freq to display the frequencies of characters.""" string=input('Enter string here: ').lower() freq = [None] * len(string); for i in range(0, len(string)): freq[i] = 1; for j in range(i+1, len(string)): if(string[i] == string[j]): freq[i] = freq[i] + 1; #Set string[j] to 0 to avoid printing visited character string = string[ : j] + '0' + string[j+1 : ]; #Displays the each character and their corresponding frequency print("Characters and their corresponding frequencies"); for i in range(0, len(freq)): if(string[i] != ' ' and string[i] != '0'): print(f'frequency of {string[i]} is: {str(freq[i])}')
70ff4d1d2f196c4baf2231e6dfc54430db72249b
tuhiniris/Python-ShortCodes-Applications
/patterns1/number pattern_1.py
512
3.953125
4
''' Pattern Enter number of rows: 5 Enter number of column: 5 12345 21234 32123 43212 54321 ''' print('Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(row,1,-1): if column < 10: print(' ',end='') print(column,end=' ') else: print(column,end=' ') for column in range(1,((number_rows-row)+1)+1): if column < 10: print(' ',end='') print(column,end=' ') else: print(column,end=' ') print()
a92e1513deea941b6d84b8c6bfdac8a5accb8715
tuhiniris/Python-ShortCodes-Applications
/tuples/Access Tuple Item.py
367
4.21875
4
''' To access tuple item need to refer it by it's the index number, inside square brackets: ''' a=[] n=int(input('Enter size of tuple: ')) for i in range(n): data=input('Enter elements of tuple: ') a.append(data) tuple_a=tuple(a) print(f'Tuple elements: {tuple_a}') for i in range(n): print(f'\nElements of tuple at position {i+1} is: {tuple_a[i]}')
f3ff7b22352de6864f57eb3c9b52e4643215de8c
tuhiniris/Python-ShortCodes-Applications
/file handling/Read a File and Capitalize the First Letter of Every Word in the File.py
346
4.28125
4
''' Problem Description: ------------------- The program reads a file and capitalizes the first letter of every word in the file. ''' print(__doc__,end="") print('-'*25) fileName=input('Enter file name: ') print('-'*35) print(f'Contents of the file are : ') with open(fileName,'r') as f: for line in f: l=line.title() print(l)
edf144c53cc3cb95eb5a10cbdb08c8a7fc249868
tuhiniris/Python-ShortCodes-Applications
/patterns1/mirrored rhombus or parallelogram star.py
895
4.21875
4
''' Pattern 6 Mirrored rhombus star Enter number of rows: 5 ***** ***** ***** ***** ***** ''' print('Mirrored rhombus star pattern:') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(1, i): print(' ',end=' ') for j in range(1,rows+1): print('*',end=' ') print('\n',end=' ') print('-------------------------------') ''' mirrored parallelogram star pattern Enter number of rows: 5 Enter number of columns: 10 ******************** ******************** ******************** ******************** ******************** ''' print('Mirrored parallelogram star pattern: ') rows=int(input('Enter number of rows: ')) columns=int(input('Enter number of columns: ')) for i in range(1,rows+1): for j in range(1,i): print(' ',end=' ') for j in range(1,columns+1): print('*',end=' ') print('\n',end=' ')
767c3c3577e16a4bf9ee546663c701a7be1954fb
tuhiniris/Python-ShortCodes-Applications
/patterns2/print chessboard number pattern with 1 and 0.py
567
3.953125
4
''' Pattern print chessboard number pattern with 1 and 0 Enter number of rows: 5 Enter number of columns: 5 10101 01010 10101 01010 10101 ''' print('print chessboard number pattern with 1 and 0 (Just use odd numbers for input):') number_rows=int(input('Enter number of rows: ')) number_columns=int(input('Enter number of columns:')) k=1 for row in range(1,number_rows+1): for column in range(1,number_columns+1): if k==1: print('1',end='') else: print('0',end='') k *= -1 if number_columns%2==0: k *= -1 print('\n',end='')
3fc0f4902507d2fab0a8d3b597ab87dd24981a13
tuhiniris/Python-ShortCodes-Applications
/list/Find the Union of two Lists.py
1,136
4.4375
4
""" Problem Description The program takes two lists and finds the unions of the two lists. Problem Solution 1. Define a function which accepts two lists and returns the union of them. 2. Declare two empty lists and initialise to an empty list. 3. Consider a for loop to accept values for two lists. 4. Take the number of elements in the list and store it in a variable. 5. Accept the values into the list using another for loop and insert into the list. 6. Repeat 4 and 5 for the second list also. 7. Find the union of the two lists. 8. Print the union. 9. Exit. """ a=[] n=int(input("Enter the size of first list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) a.append(data) print("elements of the first list: ",end=" ") for i in range(n): print(a[i],end=" ") print() b=[] n1=int(input("Enter the size of second list: ")) for i in range(n1): data1=int(input("Enter elements of the list: ")) b.append(data1) print("elements of the second list: ",end=" ") for i in range(n1): print(b[i],end=" ") print() union=list(set().union(a,b)) print(f"Union of two lists is: {union}")
5bffa97dee1d35e4f0901c7fa8ca8bb4b7d59d9e
tuhiniris/Python-ShortCodes-Applications
/basic program/test Collatz Conjecture for a Given Number.py
897
4.5625
5
# a Python program to test Collatz conjecture for a given number """The Collatz conjecture is a conjecture that a particular sequence always reaches 1. The sequence is defined as start with a number n. The next number in the sequence is n/2 if n is even and 3n + 1 if n is odd. Problem Solution 1. Create a function collatz that takes an integer n as argument. 2. Create a loop that runs as long as n is greater than 1. 3. In each iteration of the loop, update the value of n. 4. If n is even, set n to n/2 and if n is odd, set it to 3n + 1. 5. Print the value of n in each iteration. """ def collatz(n): while n > 1: print(n, end=' ') if (n % 2): # n is odd n = 3*n + 1 else: # n is even n = n//2 print(1, end='') n = int(input('Enter n: ')) print('Sequence: ', end='') collatz(n)
d2c1e86b6bd345c54188b982464fdb98a7166a8a
tuhiniris/Python-ShortCodes-Applications
/file handling/Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File.py
439
4.09375
4
''' Problem Description The program takes a letter from the user and counts the number of occurrences of that letter in a file. ''' fileName=input('Enter the file Name: ') character=input('Enter letter to be searched: ') k=0 with open(fileName,'r') as f: for line in f: words=line.split() for i in words: for letter in i: if letter==character: k+=1 print(f'Occurance of letters \'{character}\' is: {k}')
47d85156bab21b683fd7b8314b2e5e5a4a9872cc
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_3.py
281
4.25
4
""" Example: Enter the number of rows: 5 A A A A A B B B B C C C D D E """ print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+2-row): print(chr(64+row),end=' ') print()
b9deb359bb546695348a01125af7428dfef2c537
tuhiniris/Python-ShortCodes-Applications
/array/demonstrate Searching elements of an array using array module.py
415
4.09375
4
from array import * n=int(input("Enter the length of the array: ")) arr=array("i",[]) for i in range(n): x=int(input("Enter the elements: ")) arr.append(x) print("elements in the array: ",end=" ") for i in range(n): print(arr[i],end=" ") print() n=int(input("Enter the element which is to be searched for: ")) print(f"The index of 1st occurence of number {n} is at position{arr.index(n)}",end=" ")
c7e2728ee88872cf73915da32fa57b1050df9e2d
tuhiniris/Python-ShortCodes-Applications
/class and objects/Singleton class using Metaclass.py
1,036
4.0625
4
''' A metaclass is a class used to create a class. Metaclasses are usually sub classes of the type class, which redefines class creation protocol methods in order to customize the class creation call issued at the end of a class statement.''' print(__doc__) print('\n'+'-'*35+'Singleton class using MetaClass'+'-'*35) class SingleInstanceMetaClass(type): def __init__(self, name, bases, dic): self.__single_instance = None super().__init__(name, bases, dic) def __call__(cls, *args, **kwargs): if cls.__single_instance: return cls.__single_instance single_obj = cls.__new__(cls) single_obj.__init__(*args, **kwargs) cls.__single_instance = single_obj return single_obj class Setting(metaclass=SingleInstanceMetaClass): def __init__(self): self.db = 'MySQL' self.port = 3306 bar1 = Setting() bar2 = Setting() print(bar1 is bar2) print(bar1.db, bar1.port) bar1.db = 'ORACLE' print(bar2.db, bar2.port)
4961def023e1e2fb805239116cd8785ea4b09b74
tuhiniris/Python-ShortCodes-Applications
/list/Put Even and Odd elements in a List into Two Different Lists.py
826
4.46875
4
""" Problem Description The program takes a list and puts the even and odd elements in it into two separate lists. Problem Solution 1. Take in the number of elements and store it in a variable. 2. Take in the elements of the list one by one. 3. Use a for loop to traverse through the elements of the list and an if statement to check if the element is even or odd. 4. If the element is even, append it to a separate list and if it is odd, append it to a different one. 5. Display the elements in both the lists. 6. Exit. """ a=[] n=int(input("Enter number of elements: ")) for i in range(n): b=int(input("Enter the elements of the array: ")) a.append(b) even=[] odd=[] for j in a: if j%2 == 0: even.append(j) else: odd.append(j) print(f"The even list: {even}") print(f"The odd list: {odd}")
377813d90508ffa5402d90d7a288c078d9fa3786
tuhiniris/Python-ShortCodes-Applications
/strings/replace the spaces of a string with a specific character.py
208
4.15625
4
string=input('Enter string here: ') character='_' #replace space with specific character string=string.replace(' ',character) print(f'String after replacing spaces with given character: \" {string} \" ')
454c5b13b7079f428bd1b04b3a243a9c4c05bdcd
tuhiniris/Python-ShortCodes-Applications
/list/Ways to find length of list.py
1,584
4.46875
4
#naive method print("----------METHOD 1--------------------------") list=[] n=int(input("Enter the size of the list: ")) for i in range(n): data=int(input("Enter elements of the array: ")) list.append(data) print(f"elements in the list: {list}",end=" ") # for i in range(n): # print(list[i],end=" ") print() counter=0 for i in list: counter=counter+1 print(f"Length of list using navie method is: {counter}") print("---------------------METHOD 2-----------------------") """ using len() method The len() method offers the most used and easy way to find length of any list. This is the most conventional technique adopted by all the programmers today. """ a=[] a.append("Hello") a.append("How") a.append("are") a.append("you") a.append("?") print(f"The length of list {a} is: {len(a)}") print("------------------METHOD 3------------------------") """ Using length_hint() This technique is lesser known technique of finding list length. This particular method is defined in operator class and it can also tell the no. of elements present in the list. """ from operator import length_hint list=[] n=int(input("Enter the size of the list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"The list is: {list}") #Finding length of list using len() list_len=len(list) #Find length of list using length_hint() list_len_hint=length_hint(list) #print length of list print(f"Length of list using len() is : {list_len}") print(f"length of list using length_hint() is: {list_len_hint}")
7c9bef892156d20b357d5855820d8b7e79c316af
tuhiniris/Python-ShortCodes-Applications
/dictionary/Check if a Given Key Exists in a Dictionary or Not.py
731
4.21875
4
''' Problem Description The program takes a dictionary and checks if a given key exists in a dictionary or not. Problem Solution 1. Declare and initialize a dictionary to have some key-value pairs. 2. Take a key from the user and store it in a variable. 3. Using an if statement and the in operator, check if the key is present in the dictionary using the dictionary.keys() method. 4. If it is present, print the value of the key. 5. If it isn’t present, display that the key isn’t present in the dictionary. 6. Exit. ''' d={'A' : 1, 'B' : 2, 'C' : 3} key=input('Enter key to check: ') if key in d.keys(): print(f'Key is present and value of the key is: {d[key]}') else: print('Key is not present.')
b4f2b3c62901c46920d30b2a868c9aab798fcb20
tuhiniris/Python-ShortCodes-Applications
/patterns1/mirrored right triangle star pattern.py
297
4.09375
4
''' Pattern 9 Mirrored right triangle star Enter number of rows: 5 * ** *** **** ***** ''' print('Mirrored right triangle star pattern:') rows=int(input('Enter number of rows:')) for i in range(0,rows): for j in range(0,rows-i): print('*',end=' ') print('\n', end="")
293e894a12b3f1064a46443f84cbfe4d0b70db6e
tuhiniris/Python-ShortCodes-Applications
/basic program/count set bits in a number.py
724
4.21875
4
""" The program finds the number of ones in the binary representation of a number. Problem Solution 1. Create a function count_set_bits that takes a number n as argument. 2. The function works by performing bitwise AND of n with n – 1 and storing the result in n until n becomes 0. 3. Performing bitwise AND with n – 1 has the effect of clearing the rightmost set bit of n. 4. Thus the number of operations required to make n zero is the number of set bits in n. """ def count_set_bits(n): count = 0 while n: n &= n-1 count += 1 return count n=int(input("Enter a number: ")) print(f"Number of set bits (number of ones) in number = {n} where binary of the number = {bin(n)} is {count_set_bits(n)}")
6d7a32d214efdcef903bd37f2030ea91df771a05
tuhiniris/Python-ShortCodes-Applications
/number programs/check if a number is an Armstrong number.py
414
4.375
4
#Python Program to check if a number is an Armstrong number.. n = int(input("Enter the number: ")) a = list(map(int,str(n))) print(f"the value of a in the program {a}") b = list(map(lambda x:x**3,a)) print(f"the value of b in the program {b} and sum of elements in b is: {sum(b)}") if sum(b)==n: print(f"The number {n} is an armstrong number.") else: print(f"The number {n} is not an armstrong number.")
f255734a30161a2f194f998797b100bef4f44396
tuhiniris/Python-ShortCodes-Applications
/class and objects/Acess private members in Child Class.py
4,888
4.375
4
print('Accessing private members in Class:') print('-'*35) class Human(): # Private var __privateVar = "this is __private variable" # Constructor method def __init__(self): self.className = "Human class constructor" self.__privateVar = "this is redefined __private variable" # Public method def showName(self, name): self.name = name return self.__privateVar + " with name: " + name # Private method def __privateMethod(self): return "Private method" def _protectedMethod(self): return 'Protected Method' # Public method that returns a private variable def showPrivate(self): return self.__privateMethod() def showProtecded(self): return self._protectedMethod() class Male(Human): def showClassName(self): return "Male" def showPrivate(self): return self.__privateMethod() def showProtected(self): return self._protectedMethod() class Female(Human): def showClassName(self): return "Female" def showPrivate(self): return self.__privateMethod() human = Human() print(f'\nCalling the: {human.className} from the Human class.') print(f'\nAccessing the public method of Human class: {human.showName("Ling-Ling")}') print(f'\nAccessing the private method of the Human class: {human.showPrivate()}, from Human Class.') # print(f'Acessing the protected Method of the Human Class : {human.showProtected()},from Human Class.') -->AttributeError:'Human' object has no attribute 'showProtected' male = Male() print(f'\ncalling the {male.className} from the Male class') print(f'\nAccessing the Public method of Male class: {male.showClassName()}, from male class') print(f'\nAccessing the protected method of Male class: {male.showProtected()}, from male class.') # print(f'Accessing the private method of Male class: {male.Human__showPrivate()}, from male Class.') --> AttributeError: 'Male' object has no attribute '_Male__privateMethod' female = Female() print(f'\ncalling the {female.className} from the Female class') print(f'\nAccessing the Public method of female class: {female.showClassName()}, from Female class') # print(f'Accessing the protected method of female class: {female.showProtected()}, from Female class.') --> AttributeError: 'Female' object has no attribute 'showProtected' # print(f'Accessing the private method of female class: {female.showPrivate()}, from Female Class.') AttributeError: 'Female' object has no attribute '_Female__privateMethod' print('\n'+'-'*25+"Method 2 -- Accessing private members in Class"+'-'*25) print('\n'+'Example: Public Attributes: ') print('-'*20) class Employee: def __init__(self,name,sal): self.name=name #Public attribute self.salary=sal #Public attribute e1=Employee('Ling1',30000) print(f'Accessing the Public Attributes: {e1.name} : {e1.salary}') # if attribute is public then the value can be modified too e1.salary=40000 print(f'Accessing the Public Attributes after modifying: {e1.name} : {e1.salary}') print('\n'+'Example: Protected Attributes: ') '''Python's convention to make an instance variable protected is to add a prefix _ (single underscore) to it. This effectively prevents it to be accessed, unless it is from within a sub-class.''' print('-'*25) class Employee: def __init__(self,name,sal): self._name=name #protected attribute self._salary=sal #protected attribute e2=Employee('Ling2',50000) print(f'Accessing the Protected Attributes: {e2._name} : {e2._salary}') #even if attribute is protected the value can be modified too e2._salary=44000 print(f'Accessing the Protected Attributes after modifying: {e2._name} : {e2._salary}') print('\n'+'Example: Private Attributes: ') '''a double underscore __ prefixed to a variable makes it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError.''' print('-'*25) class Employee: def __init__(self,name,sal): self.__name=name # private attribute self.__salary=sal # private attribute e3=Employee('Ling3',60000) # print(f'Accessing the Privated Attributes: {e3.__name} : {e3.__salary}') --> AttributeError: 'Employee' object has no attribute '__name '''In order to access the attributes, Python performs name mangling of private variables. Every member with double underscore will be changed to _object._class__variable.''' print(f'Accessing the Private Attributes: {e3._Employee__name} : {e3._Employee__salary}') #even if attribute is protected the value can be modified too e3._Employee__salary=15000 print(f'Accessing the Protected Attributes after modifying: {e3._Employee__name} : {e3._Employee__salary}')
5f4083e687b65899f292802a57f3eb9b1b64ca5a
tuhiniris/Python-ShortCodes-Applications
/basic program/program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5.py
295
4.125
4
#program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5 lower = int(input("Enter the lower range: ")) upper = int(input("Enter the upper range: ")) for i in range(lower,upper+1): if i%7 == 0 and i%5==0: print(i)
7599d879058a9fca9866b3f68d93bcf2bda0001c
tuhiniris/Python-ShortCodes-Applications
/number programs/Swapping of two numbers without temperay variable.py
1,492
4.15625
4
##Problem Description ##The program takes both the values from the user and swaps them print("-------------------------------Method 1-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) a=a+b b=a-b a=a-b print("After swapping First number is {0} and Second Number is {1}".format(a,b)) print("-------------------------------Method 2-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) a=a*b b=a//b a=a//b print("After swapping First number is {0} and Second Number is {1}".format(a,b)) print("-------------------------------Method 3-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) temp= a a=b b=temp print("After swapping First Number is {0} and Second Number is {1}" .format(a,b)) print("-------------------------------Method 4-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) a = a ^ b b= a ^ b a = a ^ b print("After swapping First Number is {0} and Second Number is {1}" .format(a,b))
ad835b40d50ac5db87b17903ac17f79c3fc820ef
tuhiniris/Python-ShortCodes-Applications
/matrix/find the transpose of a given matrix.py
1,212
4.6875
5
print(''' Note! Transpose of a matrix can be found by interchanging rows with the column that is, rows of the original matrix will become columns of the new matrix. Similarly, columns in the original matrix will become rows in the new matrix. If the dimension of the original matrix is 2 × 3 then, the dimensions of the new transposed matrix will be 3 × 2. ''') matrix=[] row=int(input('enter size of row of matrix: ')) column=int(input('enter size of column of matrix: ')) for i in range(row): a=[] for j in range(column): j=int(input(f'enter elements of matrix at poistion row({i})column({j}): ')) a.append(j) print() matrix.append(a) print('Elements of matrix: ') for i in range(row): for j in range(column): print(matrix[i][j],end=" ") print() #Declare array t with reverse dimensions and is initialized with zeroes. t = [[0]*row for i in range(column)]; #calcutaes transpose of given matrix for i in range(column): for j in range(row): #converts the row of original matrix into column of transposed matrix t[i][j]=matrix[j][i] print('transpose of given matrix: ') for i in range(column): for j in range(row): print(t[i][j],end=" ") print()
ae96cee9c409b9af3ee4f2cca771093eb5fd32cd
tuhiniris/Python-ShortCodes-Applications
/list/Generate Random Numbers from 1 to 20 and Append Them to the List.py
564
4.53125
5
""" Problem Description The program takes in the number of elements and generates random numbers from 1 to 20 and appends them to the list. Problem Solution 1. Import the random module into the program. 2. Take the number of elements from the user. 3. Use a for loop, random.randint() is used to generate random numbers which are them appending to a list. 4. Then print the randomised list. 4. Exit. """ import random a=[] n=int(input("Enter number of elements: ")) for i in range(n): a.append(random.randint(1,20)) print(f"randomised list: {a}")
36fb60f1f2f02582d5074381a9b2368caed28534
tuhiniris/Python-ShortCodes-Applications
/patterns1/box number pattern of 1 and 0 with cross center.py
529
3.84375
4
''' Pattern box number pattern of 1 and 0 with cross center Enter number of rows: 5 Enter number of columns: 5 10001 01010 00100 01010 10001 ''' print('box number pattern of 1 and 0 with cross center: ') number_rows=int(input('Enter number of rows: ')) number_columns=int(input('ENter number of columns: ')) for row in range(1,number_rows+1): for column in range(1,number_columns+1): if row==column or column==((number_columns+1)-row): print('1',end='') else: print('0',end='') print('\n',end='')
dfc74333121a6d5c10de86c9cb3278082c4ed883
tuhiniris/Python-ShortCodes-Applications
/patterns2/number pattern_triangle_4.py
349
3.953125
4
''' Pattern Enter number of rows: 5 1 11 101 1001 11111 ''' print('Number triangle pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,row+1): if row==1 or row==number_rows or column==1 or column==row: print('1',end=' ') else: print('0',end=' ') print()
63be41d69ba4e4439bc76854fe9ba108209d8c51
tuhiniris/Python-ShortCodes-Applications
/patterns1/hollow mirrored inverted right triangle star pattern.py
444
4.09375
4
''' Pattern Hollow mirrored inverted right triangle star pattern Enter number of rows: 5 ***** * * * * ** * ''' print('Hollow mirrored inverted right triangle star pattern: ') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(1,i): print(' ',end='') for j in range(i,rows+1): if j==i or j==rows or i==1: print('*',end='') else: print(' ',end='') print('\n',end='')
4730566ea55fb752722cfb9257308de6de3ccc9c
tuhiniris/Python-ShortCodes-Applications
/recursion/Find if a Number is Prime or Not Prime Using Recursion.py
539
4.25
4
''' Problem Description ------------------- The program takes a number and finds if the number is prime or not using recursion. ''' print(__doc__,end="") print('-'*25) def check(n, div = None): if div is None: div = n - 1 while div >= 2: if n % div == 0: print(f"Number: {n}, is not prime") return False else: return check(n, div-1) else: print(f"Number: {n}, is a prime") return 'True' n=int(input("Enter number: ")) check(n)
c75674ae6650df10f2b3f0a9eda6da53bcedbe39
tuhiniris/Python-ShortCodes-Applications
/list/Ways to find the sum of element exists in list.py
1,506
4.09375
4
print("---------METHOD 1-------------") total = 0 list=[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") #Iterate each element in the list #add them in variable total for element in range(n): total=total+list[element] #printing total value print(f"sum of elements of the list: {total}") print("------------METHOD 2----------------") total = 0 element = 0 list=[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") while element < n: total=total+list[element] element=element+1 print(f"sum of elements of the list: {total}") print("--------------METHOD 3--------------") #recursive way list=[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") def sumOfList(list,size): if size==0: return 0 else: return list[size-1]+sumOfList(list, size-1) total= sumOfList(list,n) print(f"sum of elements of the list: {total}") print("---------------METHOD 4-----------------") list =[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") total=sum(list) print(f"sum of elements of the list: {total}")
e05bdb231fd02fea1c2799737704a407b576e260
eunhye43/8percent-assignment
/src/utils/id_generator.py
376
3.5
4
import abc import uuid class IdGenerator(abc.ABC): @abc.abstractmethod def generate(self) -> str: raise NotImplementedError class UserIdGenerator(IdGenerator): def generate(self) -> str: return "user-" + str(uuid.uuid4()) class AccountNumberGenerator(IdGenerator): def generate(self) -> str: return "account-" + str(uuid.uuid4())
a6031788a2a62c5d421337d87556bfd491658805
Evgenij/Course_on_Python
/Lab_1/task4.py
1,144
3.703125
4
def print_format_text(resText): print("\n---- Длиннее 7 ----") for i in resText: if len(i) >= 7: print(i) print("\n---- Длиннее 5, но короче 7 ----") for i in resText: if len(i) >= 5 and len(i) < 7: print(i) print("\n---- Короче 5 ----") for i in resText: if len(i) < 5: print(i) text = "Инвестиции являются неотъемлемой частью современной экономики. " \ "От кредитов инвестиции отличаются степенью риска для инвестора (кредитора) - " \ "кредит и проценты необходимо возвращать в оговорённые сроки независимо " \ "от прибыльности проекта, инвестиции (инвестированный капитал) возвращаются " \ "и приносят доход только в прибыльных проектах." spaces = 0 for i in text: if i == ' ': spaces += 1 print(text) resText = text.split(' ', spaces+1) print_format_text(resText)
699aea73c33d68fdaee66406e8db7cefe2196a44
Evgenij/Course_on_Python
/Lab_3/Task5/string_formatter.py
1,597
3.84375
4
class StringFormatter: def set_string(self, str): self.string = str # удаление всех слов из строки, длина которых меньше n букв def delete_words(self, n): words = self.string.split(' ') self.string = ' '.join(list(filter(lambda word: len(word) >= n, words))) return self.string # замена всех цифр в строке на знак «*» def replacement(self): for symbol in self.string: if str(symbol).isdigit(): self.string = self.string.replace(symbol,'*') return self.string # вставка по одному пробелу между всеми символами в строке def insert_spaces(self): self.string = self.string.replace('',' ')[1:] # сортировка слов по размеру def sort_lenght(self): self.string = self.string.split() self.string.sort(key=len) self.string = ' '.join(self.string) return self.string # сортировка слов в лексикографическом порядке def sort_lex(self): self.string = ' '.join(sorted(self.string.split(' '))) return self.string def formatting(self, delete = False, n = 0, replace = False, spaces = False, sort_lenght = False, sort_lex = False): if delete == True: if n != 0: self.delete_words(n) if replace == True: self.replacement() if spaces == True: self.insert_spaces() if sort_lenght == True: self.sort_lenght() if sort_lex == True: self.sort_lex() return self.string
ef045cb0440d1fe1466a7fda39915e68db973872
mwnickerson/python-crash-course
/chapter_9/cars_vers4.py
930
4.1875
4
# Cars version 4 # Chapter 9 # modifying an attributes vales through a method class Car: """a simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize attributes to describe a car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """return a descriptive name of a car""" long_name =f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """reads odometer""" print(f"This car has {self.odometer_reading}") def update_odometer(self, mileage): """ Set the odometer reading to the given value """ self.odometer_reading = mileage my_new_car = Car('audi', 'a4', 2019) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) my_new_car.read_odometer()
7e79127380cc86a94a1c4c5e836b8e00158481dc
mwnickerson/python-crash-course
/chapter_7/pizza_toppings.py
321
4.28125
4
# pizza toppings # chapter 7 exercise 4 # a conditional loop that prompts user to enter toppings prompt ="\nWhat topping would you like on your pizza?" message = "" while message != 'quit': message = input(prompt) topping = message if message != 'quit': print(f"I will add {topping} to your pizza!")
8b5ff94d3edf0eca7b35b1c67ea764816fe236aa
mwnickerson/python-crash-course
/chapter_6/cities.py
623
4.125
4
# Cities # dictionaries inside of dictionaries cities = { 'miami': { 'state': 'florida', 'sports team': 'hurricanes', 'attraction' : 'south beach' }, 'philadelphia': { 'state': 'pennsylvania', 'sports team': 'eagles', 'attraction': 'liberty bell' }, 'new york city': { 'state': 'new york', 'sports team': 'yankees', 'attraction': 'times square' } } for city, city_info in cities.items(): print(f"\nCITY: {city.title()}") state = city_info['state'].title() sports_team = city_info['sports team'].title() attraction = city_info['attraction'].title() print(state) print(sports_team) print(attraction)
1520778db31a0b825694362dea70bd80327640d9
mwnickerson/python-crash-course
/chapter_6/rivers.py
605
4.5
4
# a dictionary containing rivers and their country # prints a sentence about each one # prints river name and river country from a loop rivers_0 = { 'nile' : 'egypt', 'amazon' : 'brazil', 'mississippi' : 'united states', 'yangtze' : 'china', 'rhine' : 'germany' } for river, country in rivers_0.items(): print(f"The {river.title()} river runs through {country.title()}") print(f"\nThe rivers that I thought of:") for river in rivers_0.keys(): print(river.title()) print(f"\nThe countries with rivers are:") for country in rivers_0.values(): print(country.title())
beb9bfc94e248c1b718c2ce8f01610f1e3456460
mwnickerson/python-crash-course
/chapter_12/keys/keys.py
1,385
3.984375
4
# Keys # chapter 12 exercise 5 # takes a keydown event # prints the event.key attribute import sys import pygame from settings import Settings class KeyConverter: """overall class to manage program assets and behavior""" def __init__(self): """initialize the program and create the resources""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Event.key Dictionary") def run_program(self): """Starts the program loop""" while True: self._check_events() self._update_screen() def _check_events(self): """responds to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) def _check_keydown_events(self, event): """Respond to keypresses""" # show the key that was pressed print(event.key) if event.key == pygame.K_ESCAPE: sys.exit() def _update_screen(self): self.screen.fill(self.settings.bg_color) pygame.display.flip() if __name__ == '__main__': kc = KeyConverter() kc.run_program()
3fb67a13e7194cdddc76ed12ffc867579dec68f3
mwnickerson/python-crash-course
/chapter_10/number_writer.py
240
3.828125
4
# Number Writer # Chapter 10: Storing Data # using json.dump() and json.load() # stores a list in a json import json numbers = [2, 3, 5, 7, 11, 13] filename = 'jsons/numbers.json' with open(filename, 'w') as f: json.dump(numbers, f)
94b3e3fff962a1311e9e02f1f653ddc75bea9ebb
mwnickerson/python-crash-course
/chapter_5/voting.py
126
3.9375
4
# if statement voting programs age = 19 if age >= 18: print("You are able to vote!") print("Have you registered to vote?")
cb948a45e656ffd376acf055c8c5e58d50251f2e
mwnickerson/python-crash-course
/chapter_3/guest_changes.py
582
3.53125
4
# one of the guests cant make it, program removes them and invites someone else guest = ['alexander the great', 'genghis khan', 'kevin mitnick', 'J.R.R Tolkien', 'John F. Kennedy'] print(f"Unfortunately, {guest[4].title()} can't make it to the party.") guest[4] = 'babe ruth' print(f"Dear {guest[0].title()}, \nPlease join me for a great feast") print(f"Dear {guest[1].title()}, \nCome talk of your conquests.") print(f"Dear {guest[2].title()}, \nJoin us and tell your stories") print(f"Dear {guest[3].title()}, \nCome and chronicle our feast.") print(f"Dear {guest[4].title()}, \nJoin us for dinner, it will be a homerun!")
fea3809ec2bf488d0867160cf88fbd57d67f3e15
mwnickerson/python-crash-course
/chapter_11/city_functions.py
342
3.9375
4
# City Functions # Chapter 11 Exercise 2 # added a population function def get_city_country(city, country, population=''): """Generate city country formatted""" if population: city_country = f"{city}, {country} - population {population}" else: city_country = f"{city}, {country}" return city_country.title()
02d3bcd27304830c1c4b1c11ef10139b2f0dcaf9
mwnickerson/python-crash-course
/chapter_10/greet_user.py
212
3.703125
4
# Greet User # Chapter 10: Storing Data # reading user generated data import json filename = 'jsons/username.json' with open(filename) as f: username = json.load(f) print(f"Welcome back, {username}!")
22bdf928b3a3d79e5dccd1361536f8fb7f0136f1
mwnickerson/python-crash-course
/chapter_5/voting_vers2.py
218
4.25
4
# if and else statement age = 17 if age >= 18: print("You are able to vote!") print("Have you registered to vote?") else: print("Sorry you are too young to vote.") print("Please register to vote as you turn 18!")
cbe4ce4d644fcda766dfd72b095879a5ca2d2590
mwnickerson/python-crash-course
/chapter_7/counting.py
147
3.796875
4
# Counting # chapter 7 # the while loop in action current_number = 1 while current_number <= 5: print(current_number) current_number += 1
acefd9c2e8ff40edf60320a9ea1b18b5477b0afb
mwnickerson/python-crash-course
/chapter_6/alien_vers5.py
184
4.25
4
# Modifying values in a dictionary alien_0 = {'color': 'green'} print(f"The alien is {alien_0['color']}.") alien_0 = {'color' : 'yellow'} print(f"The alien is {alien_0['color']}.")
a934663927b79f54e0169eea362ad4e85ac9cbdf
mwnickerson/python-crash-course
/chapter_8/cities.py
333
4.09375
4
# Cities # Chapter 8 exercise 5 # a function that take name and city and retruns a statement # has a default city and country def describe_city(city='Miami', country='U.S.A'): print(f"{city.title()} is in {country.title()}") describe_city() describe_city('paris','france') describe_city('philadelphia') describe_city('Austin')
d44d5e2f17ffcb2e7966299ded7d054d7d05de7b
mwnickerson/python-crash-course
/chapter_8/t_shirt_vers2.py
473
3.96875
4
# T-Shirt Version 2 # Chapter 8 exercise 4 # take size and message and returns a statement # large is the default size def make_shirt(shirt_size='large', shirt_message='I love python'): """Takes a shrit size and message and printsmessage""" """default size is large""" print(f"The shirt is {shirt_size} and says {shirt_message}") make_shirt() make_shirt('medium') make_shirt('small', 'SGFja1RoZVBsYW5ldA==' ) make_shirt(shirt_message='SGFja1RoZVBsYW5ldA==')
9c94f5cb44b8a60ad3e9fe66a58546b624b2739f
mwnickerson/python-crash-course
/chapter_5/videogame_condtional.py
1,486
3.6875
4
# a series of conditional tests regarding video games video_game = 'elden ring' print("Is the video game Elden Ring?") print( video_game == 'elden ring') print("Is the video game Call of Duty?") print( video_game == 'Call of Duty') good_game = 'parkitect' print("\nIs the good video game parkitect?") print(good_game == 'parkitect') print("Is the good video game Escape from Tarkov?") print(good_game == 'Escape from Tarkov') bad_game = 'last of us' print("\nIs the bad game fortnite?") print(bad_game == 'fortnite') print("Is the bad game last of us?") print(bad_game == 'last of us') strat_game = 'humankind' print("\nIs the 4X game Age of Empires?") print(strat_game == 'age of empires') print("Is the 4x game humankind?") print(strat_game == 'humankind') board_game = 'monopoly' print("\nIs the board game stratego?") print(board_game == 'stratego') print("Is the board game monopoly") print(board_game == 'monopoly') owned_games = ['parkitect', 'humankind', 'sea of thieves',\ 'escape from tarkov'] sale_game = 'elden ring' print(f"\n{sale_game.title()} is on sale!") if sale_game not in owned_games: print(f"You do not own {sale_game.title()},\ buy it now!") if len(owned_games) >= 2: print(f"\nMaybe you own too many games to play") print(f"Do not buy {sale_game}") sale_game2 = 'parkitect' print(f"\n{sale_game2.title()} is on sale!") print(f"Do you own {sale_game2}?") if sale_game2 in owned_games: print(f"You own {sale_game2.title()},\ do not buy it!")
6fcb027e818ed15791490d49ffcfd6ffc9b146d7
mwnickerson/python-crash-course
/chapter_5/alien_colors3.py
658
3.75
4
# If, elif, else alien color scoring #round 1 alien_color = 'red' # 15 point score if alien_color == 'green': print('You scored 5 points') elif alien_color == 'yellow': print('You scored 10 points') else: print('You scored 15 points') # round 2 alien_color = 'yellow' # 10 point score if alien_color == 'green': print('You scored 5 points') elif alien_color == 'yellow': print('You scored 10 points') else: print('You scored 15 points') # round 3 alien_color = 'green' # 15 point score if alien_color == 'green': print('You scored 5 points') elif alien_color == 'yellow': print('You scored 10 points') else: print('You scored 15 points')
0db4acabc7715624030d1d0a257a4ae90c2034c7
hangnguyen81/HY-data-analysis-with-python
/part02-e09_rational/rational.py
1,097
4.03125
4
#!/usr/bin/env python3 class Rational(object): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"{self.x}/{self.y}" def __mul__(num1, num2): return Rational(num1.x*num2.x, num1.y*num2.y) def __truediv__(num1, num2): return Rational(num1.x*num2.y, num1.y*num2.x) def __add__(num1, num2): return Rational(num1.x*num2.y + num2.x*num1.y, num1.y*num2.y) def __sub__(num1, num2): return Rational(num1.x*num2.y - num2.x*num1.y, num1.y*num2.y) def __eq__(num1, num2): return num1.x == num2.x and num1.y == num2.y def __gt__(num1, num2): return num1.x*num2.y > num2.x*num1.y def __lt__(num1, num2): return num1.x*num2.y < num2.x*num1.y def main(): r1=Rational(1,4) r2=Rational(2,3) print(r1) print(r2) print(r1*r2) print(r1/r2) print(r1+r2) print(r1-r2) print(Rational(1,2) == Rational(2,4)) print(Rational(1,2) > Rational(2,4)) print(Rational(1,2) < Rational(2,4)) if __name__ == "__main__": main()
7393500c1f9e8b7d3e3ceafce7f4e923d9111ae1
hangnguyen81/HY-data-analysis-with-python
/part02-e13_diamond/diamond.py
703
4.3125
4
#!/usr/bin/env python3 ''' Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape. Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond. Do this using the eye and concatenate functions of NumPy and array slicing. ''' import numpy as np from numpy.core.records import array def diamond(n): inital_array = np.eye(n, dtype=int) half_diamond = np.concatenate((inital_array[::-1],inital_array[:,1:]), axis=1) full_diamond = np.concatenate((half_diamond[:-1],half_diamond[::-1]), axis=0) return full_diamond def main(): print(diamond(4)) if __name__ == "__main__": main()
13b2ad577d87bdb7efff93a084208f42f71a359b
hangnguyen81/HY-data-analysis-with-python
/part01-e06_triple_square/triple_square.py
432
4.09375
4
#!/usr/bin/env python3 def triple(x): #multiplies its parameter by three x = x*3 return x def square(x): #raises its parameter to the power of two x = x**2 return x def main(): for i in range(1,11): t = triple(i) s = square(i) if s>t: break print('triple({})=={}'.format(i,t),'square({})=={}'.format(i,s)) if __name__ == "__main__": main()