blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
fcedb2e85cb1283c77421a2f9aed8fd1b77af591
nnicexplsz/python
/Work/4_2.py
2,336
3.8125
4
t = 5 vocadulary = { "rose apple":" n.คำนาม ชมพู่ ", "keyboard":" n.คำนาม คีย์บอร์ด", "drink":" v.คำกริยา ดื่ม ", "speak":" v.คำกริยา พูด", "These":" adj.ขยายคำนาม พวกนี้", } while(True): print("พจนานุกรม\n 1)เพิ่มคำศัพท์\n 2)แสดงคำศัพท์\n 3)ลบคำศัพท์\n 4)ออกจากโปรแกรม\n") data = int(input("Input Choice :")) if data == 1 : t += 1 terminology = input("เพิ่มคำศัพท์\t:") work_type = input("ชนิดของคำ (ชนิดของคำ(n.,v.,adj.,adv.) :") if work_type == "n.": work_type = "n.คำนาม" elif work_type == "v." : work_type = "v.คำกริยา" elif work_type == "adj." : work_type = "adj.ขยายคำนาม" elif work_type == "adv." : work_type = "adv.กริยาวิเศษณ์" meaning = input("ความหมาย\t :") vocadulary[terminology] = " "+work_type+" "+meaning print("เพิ่มคำศัพท์เรียบร้อยแล้ว") elif data == 2 : print(15*"-"+"\n คำศัพท์มีทั้งหมด ",t," คำ\n",15*"-") print("คำศัพท์ ประเภท ความหมาย") for i in vocadulary : print (i+vocadulary[i]) elif data == 3: delete = input("พิมพ์คำศัพท์ที่ต้องการลบ :") x = input("ต้องการลบ"+delete+"ใช่หรือไม่ (yes / no):") if x == "yes": vocadulary.pop(delete) t -= 1 print("ลบ"+delete+"เรียบร้อยแล้ว") else: yes = input("ต้องการออกจากโปรแกรมใช่หรือไม่ (yes / no):") if yes == "yes": print("ออกจากโปรแกรมเรียบร้อยแล้ว") break
f46ef7a473eaa019a376c7312864168d63e06ef5
nnicexplsz/python
/week3/week3_2.py
896
3.703125
4
value = int(input("กรุณากรอกจำนวนครั้งการรับค่า")) # แบบฝึกหัด 3.2 i = 1 a = 0 while(i <= value) : number = int(input("กรอกตัวเลข :")) i=i+1 a=a+number print("ผลรวมที่รับค่ามาทั้งหมด = %d"%a) print("ป้อนชื่ออาหารโปรดของคุณ หรือ exit เพื่อออกจากโปรแกรม") foodlist[] i = 0 while(True): i = i +1 print("อาหารโปรดลำดับที่",i,end="") choose = input("คือ\t") foodlost.append(choose) if choose == "exit" : break print("รายการอาหารสุพดโปรดของคุณ มีดังนี้",end="") for z in range(1,i) : print(i,".",foodlist[z-1],end=" ")
b3f0da91062c2cef4b18f75077bacb5b9b555d02
JFincher42/RandomStuff
/sairam-test.py
493
3.53125
4
import pygame pygame.init() window = pygame.display.set_mode([500,500]) x_speed = 7 y_speed = 3 b_x = 15 b_y = 15 frames = 0 while frames < 750: frames += 1 b_x += x_speed b_y += y_speed if b_x >= 485: b_x = 15 elif b_x <= 15: b_x = 485 if b_y >= 485: b_y = 15 elif b_y <= 15: b_y = 485 window.fill((255,255,255)) pygame.draw.circle(window, (255,0,0), (b_x, b_y), 15) pygame.display.flip() pygame.time.wait(10)
e66d6267baedca2ed407055dec553fc524811e0c
abhinavgairola/PowerSimData
/powersimdata/utility/helpers.py
3,071
3.59375
4
import copy import importlib import os import sys class MemoryCache: """Wrapper around a dict object that exposes a cache interface. Users should create a separate instance for each distinct use case. """ def __init__(self): """Constructor""" self._cache = {} def put(self, key, obj): """Add or set the value for the given key. :param tuple key: a tuple used to lookup the cached value :param Any obj: the object to cache """ self._cache[key] = copy.deepcopy(obj) def get(self, key): """Retrieve the value associated with key if it exists. :param tuple key: the cache key :return: (*Any* or *NoneType*) -- the cached value if found, or None """ if key in self._cache.keys(): return copy.deepcopy(self._cache[key]) def list_keys(self): """Return and print the current cache keys. :return: (*list*) -- the list of cache keys """ keys = list(self._cache.keys()) print(keys) return keys def cache_key(*args): """Creates a cache key from the given args. The user should ensure that the range of inputs will not result in key collisions. :param args: variable length argument list :return: (*tuple*) -- a tuple containing the input in heirarchical structure """ kb = CacheKeyBuilder(*args) return kb.build() class CacheKeyBuilder: """Helper class to generate cache keys :param args: variable length arguments from which to build a key """ def __init__(self, *args): """Constructor""" self.args = args def build(self): """Combine args into a tuple, preserving the structure of each element. :return: (*tuple*) -- container which can be used as a cache key """ return self._build(self.args) def _build(self, arg): if arg is None: return "null" if isinstance(arg, (str, int, bool)): return arg if isinstance(arg, (list, set, tuple)): return tuple(self._build(a) for a in arg) raise ValueError(f"unsupported type for cache key = {type(arg)}") class PrintManager: """Manages print messages.""" def __init__(self): """Constructor""" self.stdout = sys.stdout def __enter__(self): self.block_print() def __exit__(self, exc_type, exc_value, traceback): self.enable_print() @staticmethod def block_print(): """Suppresses print""" sys.stdout = open(os.devnull, "w") def enable_print(self): """Enables print""" sys.stdout = self.stdout def _check_import(package_name): """Import a package, or give a useful error message if it's not there.""" try: return importlib.import_module(package_name) except ImportError: err_msg = ( f"{package_name} is not installed. " "It may be an optional powersimdata requirement." ) raise ImportError(err_msg)
68f964fde72113fea68ff42de7cb33db2e7f4e86
abhinavgairola/PowerSimData
/powersimdata/utility/distance.py
2,790
3.703125
4
from math import acos, asin, cos, degrees, radians, sin, sqrt def haversine(point1, point2): """Given two lat/long pairs, return distance in miles. :param tuple point1: first point, (lat, long) in degrees. :param tuple point2: second point, (lat, long) in degrees. :return: (*float*) -- distance in miles. """ _AVG_EARTH_RADIUS_MILES = 3958.7613 # noqa: N806 # unpack latitude/longitude lat1, lng1 = point1 lat2, lng2 = point2 # convert all latitudes/longitudes from decimal degrees to radians lat1, lng1, lat2, lng2 = map(radians, (lat1, lng1, lat2, lng2)) # calculate haversine lat = lat2 - lat1 lng = lng2 - lng1 d = ( 2 * _AVG_EARTH_RADIUS_MILES * asin(sqrt(sin(lat * 0.5) ** 2 + cos(lat1) * cos(lat2) * sin(lng * 0.5) ** 2)) ) return d def great_circle_distance(x): """Calculates distance between two sites. :param pandas.dataFrame x: start and end point coordinates of branches. :return: (*float*) -- length of branch (in km.). """ mi_to_km = 1.60934 return haversine((x.from_lat, x.from_lon), (x.to_lat, x.to_lon)) * mi_to_km def ll2uv(lon, lat): """Convert (longitude, latitude) to unit vector. :param float lon: longitude of the site (in deg.) measured eastward from Greenwich, UK. :param float lat: latitude of the site (in deg.). Equator is the zero point. :return: (*list*) -- 3-components (x,y,z) unit vector. """ cos_lat = cos(radians(lat)) sin_lat = sin(radians(lat)) cos_lon = cos(radians(lon)) sin_lon = sin(radians(lon)) uv = [cos_lat * cos_lon, cos_lat * sin_lon, sin_lat] return uv def angular_distance(uv1, uv2): """Calculate the angular distance between two vectors. :param list uv1: 3-components vector as returned by :func:`ll2uv`. :param list uv2: 3-components vector as returned by :func:`ll2uv`. :return: (*float*) -- angle (in degrees). """ cos_angle = uv1[0] * uv2[0] + uv1[1] * uv2[1] + uv1[2] * uv2[2] if cos_angle >= 1: cos_angle = 1 if cos_angle <= -1: cos_angle = -1 angle = degrees(acos(cos_angle)) return angle def find_closest_neighbor(point, neighbors): """Locates the closest neighbor. :param tuple point: (lon, lat) in degrees. :param list neighbors: each element of the list are the (lon, lat) of potential neighbor. :return: (*int*) -- id of the closest neighbor """ uv_point = ll2uv(point[0], point[1]) id_neighbor = None angle_min = float("inf") for i, n in enumerate(neighbors): angle = angular_distance(uv_point, ll2uv(n[0], n[1])) if angle < angle_min: id_neighbor = i angle_min = angle return id_neighbor
c210c723687f3b80583ad336bcdbc0b9f737af0d
mytbk/xgboost-learning
/convert_data.py
895
3.5625
4
#!/usr/bin/env python2 import pandas import sys from types import * def getDataFromCSV(csv): table = pandas.read_csv(csv) column_names = table.columns working = pandas.DataFrame() for col in column_names: print(col) if type(table[col][0]) is not StringType: working = pandas.concat([working, table[col]], axis=1) else: dummy = pandas.get_dummies(table[col], prefix=col) working = pandas.concat([working, dummy], axis=1) return working if __name__ == '__main__': working = getDataFromCSV(sys.argv[1]) fo = open(sys.argv[2], 'w') for row in working.values: fo.write('%d' % row[1]) data = row[2:] for i in range(0,len(data)): if data[i] != 0: fo.write(' %d:%d' % (i+1, data[i])) fo.write('\n') fo.close()
308f36d76762dfc539ff391c11c3464963ac7e4c
mattbaumann1/contractors
/main.py
1,173
3.96875
4
#!/usr/bin/python3 # main.py authored by Matt Baumann for COMP 412 Loyola University #The following video was very helpful for this assignment: https://www.youtube.com/watch?v=mlt7MrwU4hY import csv #Creation of list objects. contractorList = [] lobbyistList = [] #Reading in the contractorList with contracts for the city cr = open('contractors.csv') csvCR = csv.reader(cr) #contractorList name is element 1 or the second element for i in csvCR: contractorList.append(i[1]) cr.close() #Reading in the lobbbyist's clients lr = open('lobbyist.csv') csvLR = csv.reader(lr) #lobbyist's client's names are element 0 for i in csvLR: lobbyistList.append(i[0]) lr.close() #Comparison of the two sets #print(len(contractorList)) #print command to check how many contractors were appended to the list. #print(len(lobbyistList)) #print command to check how many lobbyists were appended to the list. contractorSet = set(contractorList) lobbyistSet = set(lobbyistList) print('The following names are contractors that have contracts with the city and are clients of registered lobbyists.') for i in contractorSet.intersection(lobbyistSet): print(i)
f7269f85dbc1ec9a43880f49efa09b193e080aee
bopopescu/PycharmProjects
/shashi/7) Mebership & indentity operators.py
1,117
4.0625
4
# Membership Operators 15/05/2018 #a = '1' #if (a === 1): # print(a) #if(a == '1'): # print(a) '''l1 = [1,2,3,4] if 1 in l1: print(1 in l1) d1 = {'a': 1 , 'b': 2} print('a' in d1) print('aa' in d1) print('a' not in d1) print('aa' not in d1)''' # Indentity operators '''a = 1 print(a is 1) print(a is not 1) print(a is not 1) print(a is not 11)''' # reverse a string '''a = 'abc' print(a[::-1]) print(a[ :-1]) b = 'def' print(b[ ::2])''' '''a = 101 # Decision making # if loop if a == 10: print("a: {0}".format(a)) # if else loop if a == 10: print("a: {0}".format(a)) else: print("else block")''' # nested if '''a = 12 if a == 10: print("a: {0}".format(a)) elif a == 11: print("a: {0}".format(a)) elif a == 12: print("a: {0}".format(a)) else: print("else block")''' # Nested if statement '''a = 10 b = 11 c = 12 if a == 10: if b == 11: if c == 12: print("done") else: print("failed at C check point") else: print("failed at B check point") else: print("failed at A check point")'''
347460f3edf3af4e5601a45b287d1a086e1a3bc3
bopopescu/PycharmProjects
/Class_topic/7) single_inheritance_ex2.py
1,601
4.53125
5
# Using Super in Child class we can alter Parent class attributes like Pincode # super is like update version of parent class in child class '''class UserProfile(Profile): # Child Class def __init__(self,name,email,address,pincode): # constructor of child Class super(UserProfile, self).__init__(name,email,address) # parent containing three attributes self.pincode = pincode''' class Profile: # Parent Class def __init__(self, name, email, address): # constructor of parent class self.name = name self.email = email self.address = address def displayProfile(self): # display method in parent class return "Name:{0}\nEmail:{1}\nAddress:{2}".format( self.name, self.email, self.address ) class UserProfile(Profile): # Child Class def __init__(self,name,email,address,pincode): # constructor of child class super(UserProfile, self).__init__(name,email,address) # parent containing three attributes self.pincode = pincode def setCity(self, city): # setCity method of child lass self.city = city def displayProfile(self): # display method in child class return "Name:{0}\nEmail:{1}\nAddress:{2}\nCity:{3}\nPincode:{4}".format( self.name, self.email, self.address, self.city, self.pincode ) user = UserProfile("Raju","raju@gmail.com","BTM","580045") # object of child class user.setCity("Bangalore") # adding attribute value to child class temp = user.displayProfile() print(temp)
55f9eb36b8d77e7adfa28e1d27a5922dfddf1206
bopopescu/PycharmProjects
/shashi/17) ExceptionHandling_try& _except.py
840
4
4
'''try: int("sds") print(name) name = "aaaa" open('dddddd') import asdfg print("went good...") except (NameError, ValueError, ImportError): print("something went Wrong") except NameError: print("NameError") #except: except ValueError: print("exception") except ImportError: print("Importerror") finally: print("i am always here.....")''' # try example '''try: num = input("number?") num = int(num) if num < 0: raise ValueError except (NameError, ImportError): print("something went wrong") except ValueError: print("Number can't be negative") finally: print("i am always here")''' # to enter a no ''' while True: try: i = int(input("please enter a no")) break except ValueError: print("please enter a correct no ") '''
2329f20248f4ab62b23828caae234b23dad10ab8
bopopescu/PycharmProjects
/shashi/14) import_3_methods & packages .py
552
3.515625
4
# import 3 methods # 1) import PackageName '''import test print(test.email) test.name()''' # 2) from PackageName import VarName ,functions ,Classes '''from test import name,email name() print((email))''' # 3) from PackageName import * '''from test import * name() print(email)''' # 4) from PackageName import VarName as NewVarNme, ClassName as NewClassName, functionName as NewfunctionName '''from test import name as newName,email as newEmail email = "rahul@gmail.com" def name(): print("rahul") newName() name() print(email) print(newEmail)'''
6a6b1394a960ba09ff2c97fa71e61b78a1c45858
bopopescu/PycharmProjects
/shashi/10) functions_1( lambda) .py
1,902
4.25
4
#Nested function '''def func1(): def func2(): return "hello" return func2 data = func1() print(data())''' #global function '''a = 100 def test(): global a # ti use a value in function a = a + 1 print(a) #print(a) test()''' '''a = 100 def test(): global a # ti use a value in function b = 100 a = a + 1 print(a) #print(a) test() print(b)''' # doc string / documentation function '''def add(a,b): # """ enter then the it will execute :param a: # :par b: # :return:am """ :param a: :par b: :return:am """ return a + b print(add.__doc__) add(1,2)''' # default parameter intialization '''def add(a,b = 100): return a + b temp = add(1) print(temp)''' # closure function '''def func1(a): def func2(b): return "iam function2" def func3(c): return "i am from func3" return [func2,func3] data = func1(11) #print(data[0]) #print(data[1]) print(data[0](11)) print(data[1](11))''' '''def test(a,b): if a > b: return" ai s largest" else: return "b is largest" large = test(10,20) print(large) print("============")''' #lamda - terinary expression : True if condition False #lambda p1,p2,pn:expression #exp ? value1 : value2 # to find largest to two no's using lambda function '''data = lambda a,b: 'a is largest' if a > b else "b is largest" #print(data) #print(data()) # error statement print(data(200,300))''' # to find largest to three no's using lambda function '''data = lambda a,b,c: a if a > b and a > c else b if b > c else c #print(data) #print(data()) # error statement print(data(2000,3000,500))''' # to find largest to four no's using lambda function data = lambda a,b,c,d: a if a > b and a > c and a > d else b if b > c and b > d else c if c > d else d #print(data) #print(data()) # error statement print(data(200,700,9000,6))
ee3776a9a10899adb7ca4e6979145114c979dabf
bopopescu/PycharmProjects
/Class_topic/class_assigment.py
351
3.75
4
'''class A: def __init__(self,file): self.file = open("Demo") data = self.file.read() print(data) def f1(self,f): m = input("enter a string") self.f = open("demo")as w: self.f = m.writeable() def __del__(self): print("i am here") a = A("file2") temp = a.f1("h") print(temp)'''
2001b07997daf96893b9885f14bff85c97f59d2d
danniekot/programming
/Practice/21/Python/21.py
281
3.875
4
def BMI(weight: float, height: float): return weight/(height*height/10000) def printBMI(bmi: float): if BMI < 18.5 print('Underweight') elif BMI < 25 print('Normal') elif BMI < 30 print('Overweight') else print('Obesity') w,h=map(float,input().split()) printBMI(BMI(w,h))
1f6a9e033c3a3b8c5c278cb4a96d5900ef8a994e
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/roadtrip/roadtrip-v1.py
1,130
4.15625
4
city_dict = { 'Boston': {'New York', 'Albany', 'Portland'}, 'New York': {'Boston', 'Albany', 'Philadelphia'}, 'Albany': {'Boston', 'New York', 'Portland'}, 'Portland': {'Boston', 'Albany'}, 'Philadelphia': {'New York'} } city_dict2 = { 'Boston': {'New York': 4, 'Albany': 6, 'Portland': 3}, 'New York': {'Boston': 4, 'Albany': 5, 'Philadelphia': 9}, 'Albany': {'Boston': 6, 'New York': 5, 'Portland': 7}, 'Portland': {'Boston': 3, 'Albany': 7}, 'Philadelphia': {'New York': 9}, } class Trip(): def __init__(self, starting_city, hops=1, city_dict=city_dict, city_dict2=city_dict2): self.starting_city = starting_city self.hops = hops self.city_dict = city_dict self.city_dict2 = city_dict2 def show_cities(self): one_hop_set = self.city_dict[self.starting_city] one_hop_list = [city for city in one_hop_set] two_hops = [self.city_dict[city] for city in one_hop_list] print(f"one hop: {one_hop_set}") print(f"two hops: {two_hops}") start_city = input("Starting city: ") this_trip = Trip(start_city) this_trip.show_cities()
0f6a5f4930f4a7ef9ce28e4fe790d79b1e77561b
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab15/lab15-number-to-phrase-v2.py
1,819
3.984375
4
''' lab15-number-to-phrase-v2 Version2: Handle numbers from 100-999 ''' print("Welcome to Number to Phrase v2.0. We'll convert your number between 0-999 to easily readable letters.") while True: n = int(input("Please enter an integer between 0 and 999: ")) if n not in range(0, 1000): print("Please enter an acceptable number.") continue else: break x = n // 100 #hundreds_digit y = n % 100 // 10 #tens_digit z = n % 10 #ones_digit tn = n % 100 #teen exception finder x2a = {# this is the dictionary to convert 100s to hundreds 9: 'nine-hundred', 8: 'eight-hundred', 7: 'seven-hundred', 6: 'six-hundred', 5: 'five-hundred', 4: 'four-hundred', 3: 'three-hundred', 2: 'two-hundred', 1: 'one-hundred', 0: '', } y2b = {# this is the dictionary to convert 10s to tens 9: 'ninety-', 8: 'eighty-', 7: 'seventy-', 6: 'sixty-', 5: 'fifty-', 4: 'forty-', 3: 'thirty-', 2: 'twenty-', 1: 'ten', 0: '', } z2c = {# this is the dictionary to convert 1s to ones 9: 'nine', 8: 'eight', 7: 'seven', 6: 'six', 5: 'five', 4: 'four', 3: 'three', 2: 'two', 1: 'one', 0: '', } a = x2a[x] b = y2b[y] if n % 10 == 0:#this if statement gets rid of unecessary hyphens b = b.strip('-') c = z2c[z] l = a + ' ' + b + c if 20 > tn > 10:#this addresses the teen exceptions if tn == 19: bc = 'nineteen' if tn == 18: bc = 'eighteen' if tn == 17: bc = 'seventeen' if tn == 16: bc = 'sixteen' if tn == 15: bc = 'fifteen' if tn == 14: bc = 'fourteen' if tn == 13: bc = 'thirteen' if tn == 12: bc = 'twelve' if tn == 11: bc = 'eleven' l = a + ' ' + bc print(f"{n} is {l}.")
7c693a0fe73b2fe3cbeeddf1551bf3d2f0250ab2
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab12/lab12-guess_the_number-v3.py
694
4.34375
4
''' lab12-guess_the_number-v3.py Guess a random number between 1 and 10. V3 Tell the user whether their guess is above ('too high!') or below ('too low!') the target value.''' import random x = random.randint(1, 10) guess = int(input("Welcome to Guess the Number v3. The computer is thinking of a number between 1 and 10.\nEnter your guess: ")) count = 0 while True: count = count + 1 if guess == x: print(f"Congrats. You guessed the computer's number and it only took you {count} times!") break else: if guess > x: guess = int(input("Too high... Try again: ")) if guess < x: guess = int(input("Too low... Try again: "))
ffa71514a68193fcebd2c4939dfeaa28529d5f75
pjz987/2019-10-28-fullstack-night
/Assignments/dj/lab10-v1.py
390
4.09375
4
""" Name: DJ Thomas Lab: 11 version 1 Filename: lab10-v1.py Date: 10-31-2019 Lab covers the following: - input() - float() - for/in loop - fstring - range """ num = int(input("how many numbers?: ")) total_sum = 0 for i in range(num): numbers = float(input('Enter number: ')) total_sum += numbers avg = total_sum/num print(f"Average of {num} numbers is {avg}")
f4da5503cbbf47772f9bcccdbfc7487c6efdc13f
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab14-gambling_pick6v2.py
2,237
4.09375
4
''' lab14-pick6-v1.py v2 The ROI (return on investment) is defined as (earnings - expenses)/expenses. Calculate your ROI, print it out along with your earnings and expenses. ''' #1.Generate a list of 6 random numbers representing the winning tickets...so define a pick6() function here. import random def pick6(): ticket = [] count = 0 while count != 6: ticket.append(random.randint(0, 100)) count = count + 1 return ticket #I HAD to do this to make ANYTHING work winning_ticket = pick6() print(f"Welcome to pick6. The winning ticket is:{winning_ticket}.") #2. Start your balance at 0. balance = 0 earnings = 0 expenses = 0 #3. Loop 100,000 times, for each loop: count = 0 while count != 100000: #4. Generate a list of 6 random numbers representing the ticket ticket = pick6() #5. Subtract 2 from your balance (you bought a ticket) balance = balance - 2 expenses = expenses + 2 #6. Find how many numbers match match = 0 if ticket[0] == winning_ticket[0]: match = match + 1 if ticket[1] == winning_ticket[1]: match = match + 1 if ticket[2] == winning_ticket[2]: match = match + 1 if ticket[3] == winning_ticket[3]: match = match + 1 if ticket[4] == winning_ticket[4]: match = match + 1 if ticket[5] == winning_ticket[5]: match = match + 1 #7. Add to your balance the winnings from your matches if match == 1: balance = balance + 4 earnings = earnings + 4 if match == 2: balance = balance + 7 earnings = earnings + 7 if match == 3: balance = balance + 100 earnings = earnings + 100 if match == 4: balance = balance + 50000 earnings = earnings + 50000 if match == 5: balance = balance + 1000000 earnings = earnings + 1000000 if match == 6: balance = balance + 25000000 earnings = earnings + 25000000 count = count + 1 #8. After the loop, print the final balance print(f"Your current ${balance}...you lost") roi = round((earnings - expenses) / earnings) * 0.01 print(f"Your earnings were ${earnings} but your expenses were ${expenses} so your ROI (return on investment) is {roi}%... Not great. ")
82ef1519965203526bf480fc9b989e73fb955f54
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab17-palidrome_anagramv2.py
312
4.5625
5
# Python Program to Check a Given String is Palindrome or Not string = input("Please enter enter a word : ") str1 = "" for i in string: str1 = i + str1 print("Your word backwards is : ", str1) if(string == str1): print("This is a Palindrome String") else: print("This is Not a Palindrome String")
713f27ced7d6e57dc790dc700c996d0046584b74
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/opt-lab-lcr-v2.py
2,739
3.59375
4
''' Lab: LCR Simulator https://github.com/PdxCodeGuild/2019-10-28-fullstack-night/blob/master/1%20Python/labs/optional-LCR.md ''' import random #this is the function for each player turn: def player_roll(player_name, chips, player_L, player_R): die_sides = ["L", "C", "R", "*", "*", "*"] player_roll = [] if chips[player_name] < 3: for die in range(chips[player_name]): player_roll.append(random.choice(die_sides)) else: for roll in range(3): player_roll.append(random.choice(die_sides)) print(f"{player_name} rolled {player_roll}.") for die in player_roll: if die in ['L', 'C', 'R']: chips[player_name] -= 1 if die == 'L': chips[player_L] += 1 print(f"{player_name} passed a chip to {player_L}.") elif die == 'C': chips['Center'] += 1 print(f"{player_name} passed a chip to Center.") elif die == 'R': chips[player_R] += 1 print(f"{player_name} passed a chip to {player_R}.") print(f"The chip count is:\n{chips}") return chips #break function: def break_out(chips, player1, player2, player3): if chips[player1] + chips['Center'] == 9 or chips[player1] + chips['Center'] == 9 or chips[player3] + chips['Center'] == 9: return True # #turn counter function: ##FUNCTION DIDN'T WORK # def turn_counter(turns): # print(f"Turn {turns}:") # turns += 1 # return turns #we get the player names: player1 = input("Enter Player One's name: ") player2 = input("Enter Player Two's name: ") player3 = input("Enter Player Three's name: ") #we establish the starting chip count: chips = { player1: 3, player2: 3, player3: 3, 'Center': 0, } turns= 0 #this loop runs the whole game while True: #player 1 turn: # turn_counter(turns) turns += 1 print(f"\nTurn {turns}:") player_roll(player1, chips, player2, player3) if break_out(chips, player1, player2, player3) == True: break #player 2 turn: # turn_counter(turns) turns += 1 print(f"\nTurn {turns}:") player_roll(player2, chips, player3, player1) if break_out(chips, player1, player2, player3) == True: break #player 3 turn: # turn_counter(turns) turns += 1 print(f"\nTurn {turns}:") player_roll(player3, chips, player1, player2) if break_out(chips, player1, player2, player3) == True: break print() for player in chips: if chips[player] > 0: print(f"{player} won with {chips[player]} chip(s) left. {player} takes the pot. Congrats") break print(f"\nAfter {turns} turns, here is the final chip count:\n{chips}")
ae03c569f2eb80951263f0556482c783d009e549
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/tic-tac-toe/tic_tac_toev2.py
2,803
3.890625
4
''' Tic-Tac-Toe ''' # import numpy class Player: def __init__(self, name, token): self.name = name self.token = token class Game: def __init__(self): board = { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', } # for row in range(3): # row_list = [] # for column in range(3): # column = ' ' # row_list.append(column) # board.append(row_list) self.board = board def __repr__(self): board = self.board return board[1] + '|' + board[2] + '|' + board[3] + '\n' + board[4] + '|' + board[5] + '|' + board[6] + '\n' + board[7] + '|' + board[8] + '|' + board[9] def move(self, player): while True: move = int(input("Which move? (1-9): ")) if self.board[move] in '123456789': self.board[move] = player.token break else: print("You can't do that") continue # x = int(input(f"{player.name} x: ")) # y = int(input(f"{player.name} y: ")) # if self.board[y - 1][x - 1] == ' ': # self.board[y - 1][x - 1] = player.token # break # else: # print("You can't do that") # continue print(self) Game.calc_winner(self) if Game.is_full(self) == True: print("Board full. Game Over") quit() # return __r def calc_winner(self): X_O = ['X', 'O'] for token in X_O: for row in self.board: if set(row) == {token}: print(f"{token} wins!") quit() for i in range(3): column = [] for row in self.board: column.append(row[i]) if set(column) == {token}: print(f"{token} wins!") quit() diagonal_1 = self.board[0][0], self.board[1][1], self.board[2][2] diagonal_2 = self.board[0][2], self.board[1][1], self.board[2][0] if set(diagonal_1) == {token} or set(diagonal_2) == {token}: print(f"{token} wins!") quit() def is_full(self): long_board = [] for row in self.board: for column in row: long_board.append(column) return ' ' not in long_board player1_name = 'Pete' player2_name = 'Matt' test = Game() player1 = Player(player1_name, 'X') player2 = Player(player2_name, 'O') print(test) while True: test.move(player1) test.move(player2)
2928ceeee16232bba71cac568fab3e3c19ee15bf
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab20.py
649
3.640625
4
def get_second_digit(num): if num < 10: return None return num % 10 def validate_credit_card(cc_str): if len(cc_str) != 16: return False cc = [] for i in range(len(cc_str)): cc.append(int(cc_str[i])) check_digit = cc.pop(-1) cc.reverse() for i in range(0, len(cc), 2): cc[i] *= 2 total = 0 for i in range(len(cc)): if cc[i] > 9: cc[i] -= 9 total += cc[i] second_digit = get_second_digit(total) return second_digit == check_digit credit_card_str = '4556737586899855' print(validate_credit_card(credit_card_str))
eb0bf7381ff1ea3d9f11dec46d6e2ff775d65c7e
pjz987/2019-10-28-fullstack-night
/Assignments/dustin/lab23.py
586
3.515625
4
''' By: Dustin DeShane Filename: lab23.py ''' songs = [] with open("songlist.csv", 'r') as song_list: rows = song_list.read().split('\n') headers = rows.pop(0).split(',') #set first row as headers/keys #print(headers) for row in rows: row = row.split(',') #iterate through rows and split them into component parts # Normal way # song = {} # for i in range(len(headers)): # song[headers[i]] = row[i] # Fancy python way song = dict(zip(headers, row)) songs.append(song) print(songs)
abacfce7f2c434836cfdcbbe6f763df0dce691fe
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab09.py
177
4
4
import decimal #user input d_ft = int(input("Input distance in feet: ")) #conversion d_meters = d_ft/0.3048 #equals print("The distance in meters is %i meters." % d_meters)
c41cf49d568bee4f2e2caaf24483b0e032b247eb
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab11_v1.py
146
3.640625
4
operation = input("What operation would you like to do?") num_1 = int(input("Enter first number.")) num_2 = int(input("Enter second number."))
8ed3fb8ef261e016ce96a2af1f955eab2003e599
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab20-credit_card_check.py
1,172
3.6875
4
def validator(n): validatelist=[] for i in n: validatelist.append(int(i)) for i in range(0,len(n),2): validatelist[i] = validatelist[i]*2 if validatelist[i] >= 10: validatelist[i] = validatelist[i]//10 + validatelist[i]%10 if sum(validatelist)%10 == 0: print('This a valid credit card') else: print('This is not valid credit card') def cardnumber(): result='' while True: try: result = input('Please enter the 16 digit credit card number : ') if not (len(result) == 16) or not type(int(result) == int) : raise Exception except Exception: print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.') continue else: break return result def goagain(): return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y' def main(): while True: result = cardnumber() validator(result) if not goagain(): break if __name__ == '__main__': main()
2d304bd9b8bcae2dc320a8a252ca066983467326
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab23-contact-list/lab23-contact-list-v3.py
3,638
3.828125
4
''' Lab 23: Contact List Version3 When REPL loop finishes, write the updated contact info to the CSV file to be saved. I highly recommend saving a backup contacts.csv because you likely won't write it correctly the first time. ''' with open('cities_list.csv', 'r') as cities: #establish the rows rows = cities.read().split('\n') #find the header headers = rows[0] #split the headers into its own list header_list = headers.split(',') cities_list = [] #for each line other than the header for city in rows[1:]: #get a list for each row row_list = city.split(',') city_dict = {} #for each item in the row list for i in range(len(row_list)): city_dict[header_list[i]] = row_list[i] cities_list.append(city_dict) print(f"cities_list:\n{cities_list}") ####START VERSION 2 while True: #create a record new_city_yn = input("Add new city to list (Y/N)? ").lower() while True: if new_city_yn == 'n': break else: user_city = input("Enter City: ") user_country = input("Enter Country: ") user_landmark = input("Enter Landmark: ") user_food = input("Enter Food: ") user_list = [user_city, user_country, user_landmark, user_food] user_dict = {} for i in range(len(user_list)): user_dict[header_list[i]] = user_list[i] cities_list.append(user_dict) print(f"Updated list:\n{cities_list}") break #retrieve a record retrieve_city_yn = input("Retrieve City info (Y/N)? ").lower() while True: if retrieve_city_yn == 'n': break else: user_retrieve = input("Enter City for info retrieval: ") for city_dict in cities_list: if city_dict['City'] == user_retrieve: break print(f"City info:\n{city_dict}") break #update a record update_yn = input("Update a city's info (Y/N)? ").lower() while True: if update_yn == 'n': break else: user_update_city = input("Which City would you like to update? ") user_update_attribute = input("Which attribute would you like to update? ") user_update_new_attribute = input("And what would you like to change it to? ") for city_dict in cities_list: if city_dict['City'] == user_update_city: break city_dict[user_update_attribute] = user_update_new_attribute print(f"Updated List:\n{cities_list}") break #delete a record remove_city_yn = input("Would you like to remove a City from the list (Y/N)? ").lower() while True: if remove_city_yn == 'n': break else: user_remove_city = input("Which city would you like to delete from the list? ") for city_dict in cities_list: if city_dict['City'] == user_remove_city: break cities_list.remove(city_dict) print(f"Updated List:\n{cities_list}") break again_yn = input("Would you like to change anything else (Y/N)? ").lower() if again_yn == 'n': break save_changes = input("Save Changes (Y/N)? ").lower() if save_changes == 'y': out_data = headers for row in cities_list: out_data += '\n' for header in header_list: out_data += row[header] + ',' out_data = out_data[:-1] # print(out_data) with open('cities_list.csv', 'w') as cities: cities.write(out_data)
61902e6f6ac8f23acb98798c79228bab0c09d829
pjz987/2019-10-28-fullstack-night
/Assignments/duncan/python/lab03_grading.py
1,030
4.0625
4
''' A = range(90, 100) B = range(80, 89) C = range(70, 79) D = range(60, 69) F = range(0, 59) ''' import random print("Welcome to the Grading Program!") user_grade = int(input("What is your numerical score?")) # set up +/- if user_grade % 10 in range(1,6): sign = "-" elif user_grade % 10 in range(6,11): sign = "+" # 90 <= grade <= 100: # if user_grade in range(min, max) if user_grade in range(90, 101): print(f"You received the grade A{sign}") elif 80 <= user_grade <= 89: print(f"You received the grade: B{sign}") elif user_grade in range(70, 80): print(f"You received the grade: C{sign}") elif user_grade in range(60, 70): print(f"You received the grade: D{sign}") else: print(f"You received the grade: F{sign}") rival = random.randint(1,100) print(f"Your rival's score is {rival}.") if rival > user_grade: print("Your rival is better than you.") elif rival < user_grade: print("You are better than your rival") else: print("You have tied with your rival. That's the worst.")
b3a7d72bede78555fe345a47f43661641b90e65d
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab12_v1.py
265
3.984375
4
import random target = random.randint(1,10) guess = '' while True: guess = input('guess the number! ') guess = int(guess) if guess == target: print('that\'s correct!') break else: print('that\'s incorrect!')
188fa1987331719b38bedc7fc2ecfa785328c1fd
harshidkoladara/Python_Projects
/PoliceComplainSystem/Template Files/mainconnection.py
466
3.625
4
import sqlite3 from sqlite3 import Error def sql_connection(): try: con = sqlite3.connect('mydatabase.db') return con except Error: print(Error) def sql_table(con): cursorObj = con.cursor() #cursorObj.execute('insert into data VALUES(1,0," "))') cursorObj.execute("select num from data where id=1") rows = cursorObj.fetchall() for row in rows: return row[0] con.commit()
1d9b46c9cf7ecff4ea5e4ea41dc18f269dcf1ff6
soupierbucket/Lets-Build
/Calculator_Using_Python/Calc_Using_Python.py
4,608
4.125
4
#Import section from tkinter import * #Funtion definations def click(num): """ To display the number num: input onclick parameter """ value = entry.get() entry.delete(0, END) entry.insert(0, str(value) + str(num)) return def clear(): """ To clear the screen """ entry.delete(0, END) return def add(): """ To perform addition """ global num1 num1 = "0" num1 = entry.get() + "+" entry.delete(0, END) return def subtract(): """ To perform Substraction """ global num1 num1 = "0" num1 = entry.get() + "-" entry.delete(0, END) return def divide(): """ To perform float division """ global num1 num1 = "0" num1 = entry.get() + "/" entry.delete(0, END) return def multiply(): """ To perform Multiplication """ global num1 num1 = "0" num1 = entry.get() + "*" entry.delete(0, END) return def mod(): """ To Find the remainder """ global num1 num1 = "0" num1 = entry.get() + "%" entry.delete(0, END) return def compute(): """ Logic to perform the said function """ try: num2 = entry.get() num3 = str(num1)+str(num2) e = eval(num3) entry.delete(0, END) entry.insert(0,e) except: entry.delete(0, END) entry.insert(0,"ERROR") root = Tk() #Initialises a blank window root.title("Calculator") entry = Entry(root, width = 45, borderwidth = 4) entry.grid(row = 0, column = 1, columnspan = 4, padx =8, pady=10) #Buttons definations #Number buttons button1 = Button(root, text = "1", padx = 40, pady = 20, command = lambda : click(1), fg = "Black") button2 = Button(root, text = "2", padx = 40, pady = 20, command = lambda : click(2), fg = "Black") button3 = Button(root, text = "3", padx = 40, pady = 20, command = lambda : click(3), fg = "Black") button4 = Button(root, text = "4", padx = 40, pady = 20, command = lambda : click(4), fg = "Black") button5 = Button(root, text = "5", padx = 40, pady = 20, command = lambda : click(5), fg = "Black") button6 = Button(root, text = "6", padx = 40, pady = 20, command = lambda : click(6), fg = "Black") button7 = Button(root, text = "7", padx = 40, pady = 20, command = lambda : click(7), fg = "Black") button8 = Button(root, text = "8", padx = 40, pady = 20, command = lambda : click(8), fg = "Black") button9 = Button(root, text = "9", padx = 40, pady = 20, command = lambda : click(9), fg = "Black") button0 = Button(root, text = "0", padx = 40, pady = 20, command = lambda : click(0), fg = "Black") button = Button(root, text = ".", padx = 42, pady = 20, command = lambda : click(".")) #Clear button buttonClear = Button(root, text = "AC", padx = 36, pady = 20, command = clear) #Function buttons buttonAdd = Button(root, text = "+", padx = 25, pady = 13, command = lambda : add()) buttonSub = Button(root, text = "-", padx = 25, pady = 13, command = lambda : subtract()) buttonDiv = Button(root, text = "/", padx = 25, pady = 13, command = lambda : divide()) buttonMul = Button(root, text = "*", padx = 25, pady = 13, command = lambda : multiply()) buttonMod = Button(root, text = "%", padx = 25, pady = 13, command = lambda : mod()) buttonEqual = Button(root, text = "CALCULATE", padx = 117, pady = 20, command = compute) #To place buttons in grid button1.grid(row = 3, column = 0,padx =5, pady=3) button2.grid(row = 3, column = 1) button3.grid(row = 3, column = 2) button4.grid(row = 2, column = 0) button5.grid(row = 2, column = 1) button6.grid(row = 2, column = 2) button7.grid(row = 1, column = 0) button8.grid(row = 1, column = 1) button9.grid(row = 1, column = 2) button0.grid(row = 4, column = 1) button.grid(row = 4, column = 0) buttonClear.grid(row = 4, column = 2, pady=3) buttonAdd.grid(row = 1, column = 4) buttonSub.grid(row = 2, column = 4) buttonDiv.grid(row = 3, column = 4) buttonMul.grid(row = 4, column = 4) buttonMod.grid(row = 5, column = 4) buttonEqual.grid(row = 5, column = 0, columnspan=3, pady=5) #To add some colors to the buttons! buttonAdd.config(bg = "#AAAAAA", fg = "WHITE") buttonSub.config(bg = "#AAAAAA", fg = "WHITE") buttonDiv.config(bg = "#AAAAAA", fg = "WHITE") buttonMul.config(bg = "#AAAAAA", fg = "WHITE") buttonMod.config(bg = "#AAAAAA", fg = "WHITE") buttonEqual.config(bg = "#BDBDBD", fg = "WHITE") root.mainloop() #Finally lets render
3a495c4e7a920cda01b5805f0eaebc9f3fc455ae
n20002/Task
/0813.py
2,637
3.734375
4
import sys from itertools import count from random import randint def checkfn(left, right, guess): if left < right and guess == 'h': return True if left == right and (guess == 'h' or guess == 'l'): return True if left > right and guess == 'l': return False def create_title(title): separator = '*' * 14 return '\n'.join([ separator, f'* {title} *', separator ]) message = 'High or Low ?(h/l)' print(create_title('High & Low')) for i in count(): left = randint(1,13) right = randint(1,13) print(' [問題表示]') print('***** *****') print('* * * *') print('* {0} * * *'.format(left)) print('* * * *') print('***** *****') guess = input(message) if checkfn(left, right, guess) == True and guess == 'h': print('→Highを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Win!') if checkfn(left, right, guess) == True and guess == 'l': print('→Lowを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Win!') if checkfn(left, right, guess) == False and guess == 'h': print('→Highを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Lose...') print('---ゲーム終了---') sys.exit() if checkfn(left, right, guess) == False and guess == 'l': print('→lowを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Lose...') print('---ゲーム終了---') sys.exit()
e128273e27389122b8d02b180980fa8562c940fb
jostaylor/Word_Search_Generator
/WordSearch.py
7,628
4.125
4
import random import sys # TODO What can I add? # Make the program more user-friendly: # Maybe if we get an infiniteError, allow the user to alter the words or the size of the grid and retry # Add a file writer for the key to the word search # Make it easier for the user to input without having to type them in all over again if something goes wrong # TODO NOTE: Max length for an rtf file (and all other file types I think) is 28 class colors: # Allows me to use colors in the terminal HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # All letters into one string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" elements = [] # Empty List # Asks for size of grid length = int(input("Length of grid:")) height = int(input("Height of grid:")) # Adds <height> lists to elements count1 = 0 while count1 < height: elements.append([]) count1 += 1 # Adds random letters to fill a length x height grid for i in range(height): count2 = 0 while count2 < length: elements[i].append(letters[random.randint(0, 25)]) count2 += 1 # Prints grid for i in range(height): print(elements[i]) # Asks for words to put in word search print("Input the words you want in the word search:\nType \'done\' when you are finished") # Puts words into a list called words words = [] repeat = True while repeat is True: inpt = input() if inpt.lower() == 'done': repeat = False elif inpt.lower() == 'undo': # Allows user to undo the word the recently inputted print("Removed %s" % words[len(words) - 1]) words.remove(words[(len(words) - 1)]) # Checks if word will fit inside grid elif len(inpt) > height and len(inpt) > length: print("Word too large.") else: words.append(inpt.upper()) # Prints set of words print(words) alreadyUsed = [] # Empty list # Dictionary holding all the slot directions with with xy coord changes allDirections = {'directionx0': 0, 'directionx1': 1, 'directionx2': 1, 'directionx3': 1, 'directionx4': 0, 'directionx5': -1, 'directionx6': -1, 'directionx7': -1, 'directiony0': -1, 'directiony1': -1, 'directiony2': 0, 'directiony3': 1, 'directiony4': 1, 'directiony5': 1, 'directiony6': 0, 'directiony7': -1} ''' DIRECTION KEY: 0 = North 1 = NorthEast 2 = East 3 = SouthEast 4 = South 5 = SouthWest 6 = West 7 = NorthWest Y Value is flipped! ''' def canWordBeInserted(word, direction, x, y): # Checks if word can be inserted result = True i = 0 for letter in range(0, len(word)): # Checks if the whole word will fit in the grid if isSpotAvailable([x + (i * (allDirections['directionx%d' % direction])), y + (i * (allDirections['directiony%d' % direction]))], word[i]) is False: result = False i += 1 return result def insertLetter(letter, x, y): # Inserts letter into the grid elements[y][x] = letter # Inserts letter alreadyUsed.append([x, y]) alreadyUsed.append(letter) def isSpotAvailable(location, letter): # Checks if 'location'(given as [x, y]) is available for 'letter' result = True for i in range(len(alreadyUsed)): # Loops through alreadyUsed if i % 2 == 0: # If the spot being looked at is a coord pair if alreadyUsed[i][0] == location[0] and \ alreadyUsed[i][1] == location[1] and alreadyUsed[i + 1] != letter: result = False if location[0] >= length or location[0] < 0: # Checks if x-value of location is within the grid result = False if location[1] >= height or location[1] < 0: # Checks if y-value of location is within the grid result = False return result def printKey(): # Finds and prints grid with letters of words standing out for i in range(height): # Iterates through y values string = '' # Empty string for j in range(len(elements[i])): # Iterates through x values doThis = True for k in range(len(alreadyUsed)): # Iterates through alreadyUsed if k % 2 == 0: # Only checks coord pair in alreadyUsed if [j, i] == alreadyUsed[k]: # If that spot is being taken up by part of a word string += (colors.OKBLUE + '%s ' + colors.ENDC) % (elements[i][j]) # Prints letter with color doThis = False # Makes sure it doesn't print again normally (non-colored) break if doThis is True: string += '%s ' % elements[i][j] print(string) def printGrid(): # Prints grid for i in range(height): string = '' for j in range(len(elements[i])): string += '%s ' % elements[i][j] print(string) # Inserts word into grid for word in words: infiniteError = 0 retry = True while retry is True: # Loops until a the word has found a spot where it will fit retry = False infiniteError += 1 if infiniteError >= 15000: # Is this number alright? sys.exit("Process expired. Perhaps there were too many words in too small of a space..") # Chooses random values for x, y, and direction y = random.randint(0, height - 1) x = random.randint(0, length - 1) direction = random.randint(0, 7) if canWordBeInserted(word, direction, x, y) is False: retry = True else: i = 0 for letter in range(0, len(word)): # Inserts word into grid insertLetter(word[letter], x + (i * (allDirections['directionx%d' % direction])), y + (i * (allDirections['directiony%d' % direction]))) i += 1 printGrid() print(words) print("Press ENTER when you would like to the key") input() printKey() response = input("Would you like to save this word search?") if response.lower() == 'yes': title = input("What would you like to call this word search?") path = '' house = input("Are you at your (moms) house or your (dads) house?") if house.lower() == 'dads': path = 'C:\\Users\\jtlov_000\\Desktop\\Everything\\Coding and Programming\\PythonWordSearches' else: path = 'C:\\Users\\Josh\\Desktop\\Everything\\Coding and Programming\\PythonWordSearches' askfiletype = int(input("Do you want a 1)docx file \t2)txt file \t3)rtf file")) filetype = '' while True: if askfiletype == 1: filetype = '.docx' break elif askfiletype == 2: filetype = ".txt" break elif askfiletype == 3: filetype == ".rtf" break else: print("Please re-enter") file1 = open(path + '//' + title + filetype, 'w') # Creates a file of name with title file1.write(title + '\n\n') # Prints grid for i in range(height): string = '' for j in range(len(elements[i])): string += '%s ' % elements[i][j] file1.write(string + '\n') # Prints words file1.write("\n\n") for word in words: file1.write(word + '\t') file1.close() print("Goodbye") sys.exit()
e3131b62735d783016b26f1b6f25ca8754cb2458
IamGianluca/algorithms
/ml/sampling/metropolis.py
2,929
3.625
4
import numpy as np class MetropolisHastings(object): """Implementation of the Metropolis-Hastings algorithm to efficiently sample from a desired probability distributioni for which direct sampling is difficult. """ def __init__(self, target, data, iterations=1000): """Instantiate a *MetropolisHastings* object. Args: target (scipy.stats.Distribution): The target distribution. This distribution should proportionally approximate the desired distribution. NOTE: Any object implementing a *logpdf* method would do the job. data (numpy.array): N-dimensional array containing the observed data. NOTE: Will be soon deprecated. iterations (int): The number of iterations the algorithm needs to run. Attributes: shape (tuple): The dimensions of the *data* array. traces (list): The points sampled through the Markov chain sampling algorithm. """ self.target = target self.data = data # NOTE: will be deprecated in future release self.iterations = iterations self.shape = data.shape self.traces = list() def optimise(self): """Sample from target distribution. Returns: list: A sample of points from the target distribution. """ current_position = self._random_initialisation() for iteration in range(self.iterations): proposal = self._suggest_move(current_position=current_position) if self._evaluate_proposal(current_position, proposal): current_position = proposal self.traces.extend([current_position]) return self.traces def _random_initialisation(self): """Find random point to start Markov chain. """ # TODO: make sure point is within function domain return np.random.rand(self.shape[0]) def _suggest_move(self, current_position): """Suggest new point. Args: current_position (numpy.array): Current position. Returns: numpy.array: New candidate point. """ # TODO: use current_position as mean of randn, to improve efficiency jump = np.random.randn(self.shape[0]) return np.sum((current_position, jump), axis=0) def _evaluate_proposal(self, current, proposal): """Evaluate proposed move. Args: current (numpy.array): Current position. proposal (numpy.array): Proposed move. Returns: bool: Whether the proposed move is accepted. """ acceptance_probability = min( np.exp(self.target.logpdf(x=proposal) - \ self.target.logpdf(x=current)), 1 ) return np.random.uniform() < acceptance_probability
f008d73d640609771b8f2aaa149449a10f7706ee
aniroxxsc/Hackerrank-ProblemSolving-Python
/SuperReducedString
632
3.59375
4
#!/bin/python3 import math import os import random import re import sys # Complete the superReducedString function below. def superReducedString(s): for i in range(0,len(s)-1): if s[i]==s[i+1]: s1=s[0:i] if (i+2)<=len(s): s2=s[i+2:] else: s2="" s=s1+s2 s=superReducedString(s) break if(s==""): s="Empty String" return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = superReducedString(s) fptr.write(result + '\n') fptr.close()
fe82e7566405f33f301201bd5cce475c0147d805
mohasinac/Learn-LeetCode-Interview
/Strings/Count and Say.py
1,812
4.0625
4
""" he count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Explanation: This is the base case. Example 2: Input: 4 Output: "1211" Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". """ class Solution: def countAndSay(self, terms: int) -> str: """ 1 has only 1 2 will 11 as (previous had only single 1) 3 will have 21 as (previous had 2 continous 1 ) 4 will have 1211 as prvious has a single 2 and single 1 5 will have 111221 as previous has single 1 single 2 and then double 1 6 will have 312211 as previous has thrice 1 twice 2 and then double 1 """ ans="1" for i in range(1,terms): n=ans last=n[0] count=0 ans="" for c in n: if c==last: count+=1 else: ans+=str(count)+str(last) count=1 last=c if count: ans+=str(count)+str(last) return ans
81ff46e99809f962f6642b33aa03dd274ac7a16e
mohasinac/Learn-LeetCode-Interview
/Strings/Implement strStr().py
963
4.28125
4
""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). """ class Solution: def strStr(self, haystack: str, needle: str) -> int: n = len(needle) h = len(haystack) if n<1 or needle==haystack: return 0 if h<1: return -1 for i, c in enumerate(haystack): if c==needle[0] and (i+n)<=h and all([haystack[i+j]==needle[j] for j in range(1,n)]): return i return -1
7e558fb4d31490ea5317a9b131c8e022e0504f20
msam04/Assignment2.2
/Python_Module2_2.py
236
3.890625
4
# coding: utf-8 # In[19]: for i in range (1, 6): str = "*" for j in range (1, i): str = str + "*" print(str) length = len(str) for j in range (1, len(str) + 1): print(str[:length]) length -= 1
885a56023c3b3877e0d2bccf0db93f3c65351b95
i2mint/stream2py
/stream2py/simply.py
4,464
3.5625
4
""" Helper Function to construct a SourceReader and StreamBuffer in one Example of usage: :: from stream2py.simply import mk_stream_buffer counter = iter(range(10)) with mk_stream_buffer( read_stream=lambda open_inst: next(counter), open_stream=lambda: print('open'), close_stream=lambda open_inst: print('close'), auto_drop=False, maxlen=2, ) as count_stream_buffer: count_reader = count_stream_buffer.mk_reader() print(f'start reading {count_reader.source_reader_info}') for i in count_reader: # do stuff with read data print(i) if count_stream_buffer.auto_drop is False: count_stream_buffer.drop() print('done reading') """ import contextlib from typing import Callable, Any, Optional from stream2py import SourceReader, StreamBuffer from stream2py.utility.typing_hints import ComparableType, OpenInstance @contextlib.contextmanager def mk_stream_buffer( read_stream: Callable[[OpenInstance], Optional[Any]], open_stream: Callable[[], OpenInstance] = None, close_stream: Callable[[OpenInstance], None] = None, info: Callable[[OpenInstance], dict] = None, key: Callable[[Any], ComparableType] = None, maxlen: Optional[int] = 100, sleep_time_on_read_none_seconds: float = None, auto_drop: bool = True, enumerate_data: bool = True, ): """Helper Function to construct a SourceReader and StreamBuffer in one :: from time import sleep from stream2py import mk_stream_buffer # download txt from: https://www.gutenberg.org/cache/epub/1524/pg1524.txt FILE = 'hamlet.txt' with mk_stream_buffer( read_stream=lambda open_inst: next(open_inst, None), open_stream=lambda: open(FILE, 'rt'), close_stream=lambda open_inst: open_inst.close(), key=lambda read_data: read_data[0], maxlen=None, ) as stream_buffer: buffer_reader = stream_buffer.mk_reader() sleep(1) # do stuff with buffer_reader print(buffer_reader.range(start=40, stop=50)) :param read_stream: takes open instance and returns the next read item :param open_stream: open stream and return an open instance such as a file descriptor :param close_stream: take open instance and close the instance :param info: dict help in describing the instance :param key: sort key for read items :param maxlen: max read items to keep in buffer window :param sleep_time_on_read_none_seconds: time to wait if data is not ready to be read :param auto_drop: False is useful when data can be read independent of time and will quickly overflow the buffer maxlen before data is consumed. StreamBuffer.drop() must be called to continue reading after buffer has filled up. Default True. :param enumerate_data: wrap read data in an enumerated tuple. Default True. :return: """ class SimplifiedSourceReader(SourceReader): open_instance: OpenInstance = None open_time = 0 sleep_time_on_read_none_s = sleep_time_on_read_none_seconds read_idx = 0 def open(self): self.read_idx = 0 if open_stream is not None: self.open_instance = open_stream() self.open_time = self.get_timestamp() def read(self): read_data = read_stream(self.open_instance) if enumerate_data: read_data = (self.read_idx, read_data) self.read_idx += 1 return read_data def close(self): if close_stream is not None: close_stream(self.open_instance) @property def info(self): if info is not None: return info(self.open_instance) return { 'open_time': self.open_time, 'open_instance': str(self.open_instance), } def key(self, data: Any): if key is not None: return key(data) return data stream_buffer = StreamBuffer( source_reader=SimplifiedSourceReader(), maxlen=maxlen, sleep_time_on_read_none_s=sleep_time_on_read_none_seconds, auto_drop=auto_drop, ) try: stream_buffer.start() yield stream_buffer finally: stream_buffer.stop()
78ae22f42201983039a2b6aba20195284063b3e4
andrei10t/AdventOfCode
/AdventOfCode2020/day3.py
968
3.546875
4
def readFile(filename) -> list: with open(filename, "r") as f: return [line[:-1] for line in f.readlines()] def readtest() -> list: input = list() with open("test.txt", "r") as f: for line in f.readlines(): input.append(line) return input def part1(file): counter = check(3, 1, file) return counter def check(x, y, input): counter = 0 xs = 0 ys = 0 mod = len(input[0]) while ys < len(input) - 1: xs = (xs + x) % mod ys += y print(xs) print(ys) if input[ys][xs] == "#": counter += 1 print("c" + str(counter)) return counter def part2(input): result = ( check(1, 1, input) * check(3, 1, input) * check(5, 1, input) * check(7, 1, input) * check(1, 2, input) ) return result if __name__ == "__main__": # print(part1(readFile("in.txt"))) print(part2(readFile("in.txt")))
997f0d32c5609f5e9dac7fb94b933f4e28d64809
jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO
/exercicio11.py
410
4.15625
4
# 11. Altere o programa anterior para mostrar no final a soma dos números. # Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01 num1 = int(input("Digite o primeiro número inteiro: ")) num2 = int(input("Digite o segundo número inteiro: ")) for i in range (num1 + 1, num2): print(i) for i in range (num2 + 1, num1): print(i) soma = num1 + num2 print("A soma dos dois números inteiros é: ", i + i)
2d0c69eabcd187406a0e982cbc343c88d88a26cb
jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO
/exercicio14.py
601
3.96875
4
# 14. Faça um programa que peça 10 números inteiros, calcule e mostre a # quantidade de números pares e a quantidade de números impares. # Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01 import math numero = [[], []] valor = 10 for c in range(1, 11): valor = int(input(f"Digite o {c}º valor: ")) if valor % 2 ==0: numero[0].append(valor) else: numero[1].append(valor) numero[0].sort() numero[1].sort() print(f"Os valores digitados são: {numero}") print(f"Os valores pares digitados são: {numero[0]}") print(f"Os valores ímpares digitados são: {numero[1]}")
16cbb114d0a13ac1c2a25c4be46dd7c14db6584c
Divyendra-pro/Calculator
/Calculator.py
761
4.25
4
#Calculator program in python #User input for the first number num1 = float(input("Enter the first number: ")) #User input for the operator op=input("Choose operator: ") #User input for the second number num2 = float(input("Enter the second number:" )) #Difine the operator (How t will it show the results) if op == '+': print("You choosed for Addition ") print(num1+num2) elif op == '-': print("You choosed for subtraction ") print(num1-num2) elif op == '*': print("You choosed for multiplication ") print(num1*num2) elif op == '/': print("Your choosed for division ") print(num1/num2) else: print("Enter a valid operator") print("Some valid operators: " "+ " "- " "* " "/ ")
1f8f158a5528bff42b1eb0876794211096386475
gruenwalds/geekbrains
/Gruenwald_4_4.py
396
3.921875
4
digits = [int(element) for element in input("Введите числа: ").split()] even_number = 0 sum_numbers = 0 for counter in digits: if counter % 2 == 0: even_number = even_number + counter for nums in range(1, len(digits), 2): sum_numbers = sum_numbers + digits[nums] sum_numbers = sum_numbers + even_number print("Сумма чисел равна: ", sum_numbers)
006703a80291ab29120be71a5a713a213d8d45bc
DeFeNdog/LeetCode
/arrays_and_strings/first-unique-character-in-a-string.py
667
4.0625
4
''' ## First Unique Character in a String Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. ''' from collections import Counter hash class Solution: def firstUniqChar(self, s): count = Counter(s) for idx, ch in enumerate(s): if count[ch] == 1: return idx return -1 if __name__ == '__main__': s = Solution() print(s.firstUniqChar("leetcode")) print(s.firstUniqChar("loveleetcode"))
b7ce6e275957e54ae4a4fd8e70f44a422396cbae
DeFeNdog/LeetCode
/linked_lists/add-two-numbers.py
2,323
3.90625
4
''' ## Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. Solution: Doubly-linked list Time complexity: O(max(m,n)). Assume that mmm and nnn represents the length of l1 and l2 respectively, the algorithm above iterates at most max⁡(m,n) times. Space complexity : O(max⁡(m,n)). The length of the new list is at most max⁡(m,n)+1. ''' class ListNode: def __init__(self, val): self.val = val self.next = None self.previous = None self.head = None self.tail = None return def add_list_item(self, item): if not isinstance(item, ListNode): item = ListNode(item) if self.head is None: self.head = item else: self.tail.next = item self.tail = item return def traverse_list(self): if self.head is None: return else: n = self.head while n is not None: print(n.val, " ") n = n.next class Solution: def addTwoNumbers(self, l1=None, l2=None): dummyHead = ListNode(0) p, q = l1, l2 curr = dummyHead carry = 0 while p or q: x = p.val if p else 0 y = q.val if q else 0 sum = carry + x + y carry = sum / 10 curr.next = ListNode(sum % 10) curr = curr.next if p: p = p.next if q: q = q.next if carry > 0: curr.next = ListNode(carry) return dummyHead.next if __name__ == '__main__': s = Solution() ll1 = ListNode(0) ll1.add_list_item(3) ll1.add_list_item(4) ll1.add_list_item(2) # ll1.traverse_list() ll2 = ListNode(0) ll2.add_list_item(4) ll2.add_list_item(6) ll2.add_list_item(5) # ll2.traverse_list() print(s.addTwoNumbers(ll1, ll2))
8a3f462060774d17383f404bf97467015cd94489
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex053_detector_de_palindromo.py
1,157
4.15625
4
# Class Challenge 13 # Ler uma frase e verificar se é um Palindromo # Palindromo: Frase que quando lida de frente para traz e de traz para frente # Serão a mesma coisa # Ex.: Apos a sopa; a sacada da casa; a torre da derrota; o lobo ama o bolo; # Anotaram a data da maratona. # Desconsiderar os espaços e acentos. Programa tira os espaços print('Descobrindo se a frase é um Palindromo.') frase = str(input('Digite uma frase: ')).strip().upper() array = frase.split() junto = ''.join(array) n = len(junto) s = 0 for a in range(1, n+1): if junto[a-1] != junto[n-a]: s += 1 if s == 0: print('A frase é um Palindromo.') else: print('A frase não é um Palindromo') # Exemplo do professor print('\nExemplo do professor: ') palavras = frase.split() inverso = '' for letra in range(len(junto)-1, -1, -1): inverso += junto[letra] print('O inverso de {} é {}.'.format(junto, inverso)) if inverso == junto: print('Temos um Palindromo') else: print('Não temos um Palindromo') # 3ª Alternativa como o Python inverso2 = junto[::-1] # Frase junto, do começo ao fim, porém de traz para frente # Por isso o -1 print(inverso2)
51fba057f0a7253f1ad30a5c0d6c38171b888e77
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex082_dividindo_valores_em_varias_listas.py
1,188
4.03125
4
# Class Challenge 17 # Ler vaios números # Ter duas listas extras, só com pares e ímpares # Mostrar as 3 listas # Dica: Primeiro le os valores, depois monta as outras duas listas big = list() par = list() impar = list() while True: big.append(int(input('Enter a number: '))) resp = ' ' while resp not in 'YN': resp = str(input('Do you want to continue? [Y/N] ')).strip().upper()[0] if resp == 'N': break print('='*50) print(f'All numbers entered have been: {big}') for a in big: if a % 2 == 0: if a not in par: par.append(a) if a % 2 == 1: if a not in impar: impar.append(a) print(f'All the even numbers that appear are: {par}') print(f'All the odd numbers that appear are: {impar}') # Teacher example: print('\nTeacher exaple:') num = [] p = [] i = [] while True: num.append(int(input('Enter a number: '))) resp = str(input('Do you wanna continue? [S/N]')) if resp in 'Nn': break for v in num: if v % 2 == 0: p.append(v) else: i.append(v) print('-=' * 30) print(f'The full list is: {num}') print(f'The even list is: {p}') print(f'The odd list is: {i}')
9d82ae750f0a2f3d2531e9832d9e32ae142a67ea
NathanaelV/CeV-Python
/Aulas Mundo 1/aula09_manipulando_texto.py
4,673
4.34375
4
# Challenge 022 - 027 # Python armazena os carcteres de uma string, as letras de uma frase, separadamente # Python conta os espaços e a contagem começa com 0 # Para exibir um caracter específico só especificar entre [] # Fatiamento frase = 'Curso em Vídeo Python' print('\nFATIAMENTO!\n') print('frase[9]:', frase[9]) print('frase[13]:', frase[13]) print('frase[9:13]:', frase[9:13]) # Do 9 ao 13, sem incluir o 13 # Caso eu queira incluir até o final da frase se inclui um número a mais do que # foi contado. Se a contagem acabar em 20 coloco [9:21] assim aparece tudo print('frase[9:21:2]:', frase[9:21:2]) # Vai do 9 ao 21 pulando de 2 em 2 print('frase[:5]:', frase[:5]) # Começa no 0 e vai até o 4, pois exclui o 5 print('frase[15:]:', frase[15:]) # Começa no 15 e vai até o último print('frase[9::3]:', frase[9::3]) # Começa no 9 e vai até o final pulando de 3 em 3 # Analise print('\nANALISE!\n') # fução length print('Sentence Length. len(frase): ', len(frase)) # Quantos carcteres tem na palavra, incluindo so espaços # Caso use com uma lista, mostrará quantos componentes tem o Array o = frase.count('o') # Conta quantas vezes o letra 'o' minusculo aparece na frase # Python diferencia maiúsculo de minúsculo print('Quantas vezes a letra o aparece na frase: ', format(o)) print('Quantas veses a letra o aparece até o carcater 13:', end=' ') print(frase.count('o', 0, 13)) # Quantas vezes a letra 'o' aparece na frase # Até o caracter 13, sem contar o 13, contagem com fatiamento print('Apartir de que carcter aparece o trecho deo:', end=' ') print(frase.find('deo')) # Indica onde começa os caracteres procurados, 'deo' print('Encontrar a palavra Android: ', end='') print(frase.find('Android')) # Se pedir para localizar uma palavra que não existe # na String, será retornado um valor: -1 print('A palavra Curso está na frase?: ', 'Curso' in frase) # para saber se a palavra Curso existe na frase # Responde True or False print('Prucurar vídeo, v minúsculo: ', frase.find('vídeo')) print('Usando comando lower: ', frase.lower().find('vídeo')) #Transformação print('\nTRANSFORMAÇÃO!\n') print('frase.replace(Python,android): ', frase.replace('Python', 'Android')) # Troca a primeira palavra pela segunda. # Não precisa ter o mesmo tamanho. o Python adapta # Não é possível atribuir outroa valor a String. O adroid só aparece no lugar # de Python na impressão, mas na memoria ainda é Python # Para conseguir mudar é necessário usar outro comando frase = frase.replace('Python', 'Android') print('O Valor da Str frase foi alterada: {}'.format(frase)) frase.upper() # Coloca todas as letras em maiúscula frase.lower() # Transforma tudo em minúsculo frase.capitalize() # Joga tudo para minusculo e depois só coloca a primeira letra maiúscula frase.title() # Transforma todas as letras depois dos espaços em Maiúsculo # Funções para remover os espaços no começo da frase # Acontece da pessoa dar alguns espaços antes de começar a digitar frase2 = ' Aprenda Python ' frase2.strip() # Remove os espaços antes da primeira letra e os que vem depois # Da ultima letra frase2.rstrip() # Só Remove os espaços do lado direito Right, por causa do r frase2.lstrip() # Só Remove os espços do lado esquerdo left, por causa do l # Divisão print('\nDIVISÃO E JUNSÃO\n') print('Comando frase.split(): \n', frase.split()) # Cria uma divisão onde existir espaços. Criando uma nova lista separada = frase.split() print(separada[0]) # Mostra o primeiro intem da lista print(separada[0][2]) # No primeiro intem da lista, vai mostrar a 3ª letra print(len(separada)) # Mostra a quantidade de elementos na lista print('Join: ') print('-'.join(frase)) # Junta as palvras divididas usado o que tiver entre ''. # Nesse caso teria - entre as palavras, pois fiz '-'.join(frase) # Para escrever um texto grande usa-se: print("""Texto muito Grande com Enter""") # O texto é impresso incluindo os Enter print('\nTexto ' # Desse jeito o python pula linhas aqui 'pequeno com aspas ' # Mas na hora de colocar na tela 'simples e enter') # Sai tudo em uma só linha # Combinação de funções: print('Quntos O maiúsculos tem na frase: ') print(frase.count('O')) print('E agora? Usando função upper():') print(frase.upper().count('O')) # Espaço também conta como carcter frase3 = ' Curso em Video Python ' # Não aparece os espaços na impressão print('Frase com espaços: {}.\nQuantidade: {}'.format(frase, len(frase3))) print('Com corte de espaços: {}'.format(len(frase3.strip())))
4d7ae2dfa428ee674fdd151230a36c39c09e7055
NathanaelV/CeV-Python
/Aulas Mundo 3/aula19_dicionarios.py
2,623
4.21875
4
# Challenge 90 - 95 # dados = dict() # dados = {'nome':'Pedro', 'idade':25} nome é o identificador e Pedro é o valor # idade é o identificador e 25 é a idade. # Para criar um novo elemento # dados['sexo'] = 'M'. Ele cria o elemento sexo e adiciona ao dicionario # Para apagar # del dados['idade'] # print(dados.values()) Ele retornará - 'Pedro', 25, 'M' # print(dados.keys()) It will return - 'nome', 'idade', 'sexo' # print(dados.items()) it will return all things - 'name', 'Pedro' ... # Esses conceitos são bons para laços, for, while filme = {'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'} for k, v in filme.items(): print(f'O {k} é {v}') print() person = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 40} print(f'{person["nome"]} is {person["idade"]} years old.') # Não posso usar person[0] ele não reconhece print(f'Using person.keys(): {person.keys()}') print(f'Using person.values(): {person.values()}') print(f'Using person.items(): {person.items()}') # Using for: print('\nUsing for:') print('\nUsing For k in person.key: or For k in person:') for k in person.keys(): # = to use person print(k) print('\nUsing k in person.values():') for k in person.values(): print(k) print('\nUsing k, v in person.items():') for k, v in person.items(): print(f'V = {v}; K = {k}') del person['sexo'] print("\nAfter using del person['sexo']") for k, v in person.items(): print(f'V = {v}; K = {k}') # Alterando e adicionando elementos: print('\nChanging the name and adding weight.') person['peso'] = 98.5 person['nome'] = 'Leandro' for k, v in person.items(): print(f'V = {v}; K = {k}') # Criando um dicionário dentro de uma lista: Brazil = list() estado1 = {'UF': 'Rio Janeiro', 'sigla': 'RJ'} estado2 = {'UF': 'São Paulo', 'sigla': 'SP'} Brazil.append(estado1) Brazil.append(estado2) print(f'Brazil: {Brazil}') print(f'Estado 2: {estado2}') print(f'Brazil[0]: {Brazil[0]}') print(f"Brazil[0]['uf']: {Brazil[0]['UF']}") print(f"Brazil[1]['sigla']: {Brazil[1]['sigla']}") # Introsuzindo Valores: print('\nIntroduzindo Valores: ') brasil = list() estado = dict() for a in range(0, 3): estado['uf'] = str(input('UF: ')) estado['sigla'] = str(input('Sigla: ')) brasil.append(estado.copy()) # Caso use o [:] dará erro. for e in brasil: print(e['sigla'], ' = ', e['uf']) # Mostra os identificadores e os valores print('\nItems: ') for e in brasil: for k, v in e.items(): print(f'O compo {k} tem o valor {v}') # Mostra os valore dentro da lista print('\nValues:') for e in brasil: for v in e.values(): print(v, end=' - ') print()
c8ac81bcd8433c0749e3afc2330ff91a325b5180
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex068_jogo_do_par_ou_impar.py
1,810
3.921875
4
# Class Challenge 15 # Make a game to play 'par ou impar' (even or odd). The game will only stop if the player loses. # Show how many times the player has won. from random import randint c = 0 print('Lets play Par ou Impar') while True: comp = randint(1, 4) np = int(input('Enter a number: ')) rp = str(input('type a guess [P/I]: ')).strip().upper()[0] while rp not in 'PpIi': rp = str(input('Enter a valid guess [P/I]: ')).strip().upper()[0] print(f'You played {np} and computer played {comp}') s = np + comp if s % 2 == 0: r = 'P' else: r = 'I' if rp == r: print('~~' * 20) print('CONGRATULATIONS! You Win.') print('Lets play again...') print('~~' * 20) c += 1 else: print('~~' * 20) print('The Computer win') print(f'You won {c} matches in a row') print('Try again.') print('~~' * 20) break # Teacher Example: print('\nTeacher example: ') v = 0 while True: jogador = int(input('Digite um valor: ')) computador = randint(1, 4) total = jogador + computador tipo = '' while tipo not in 'PI': tipo = str(input('Par ou Ímpar? [P/I] ')).strip().upper()[0] print(f'Você jogou {jogador} e o computador {computador}. Total de {total}', end='') print('DEU PAR' if total % 2 == 0 else 'DEU ÍMPAR') if tipo == 'P': if total % 2 == 0: print('Você VENCEU!') v += 1 else: print('Você PERDEU!') break elif tipo == 'I': if total % 2 == 1: print('Você VENCEU!') v += 1 else: print('Você PERDEU!') break print('Vamos Jogar Novamente...') print(f'GAME OVER. Você venceu {v} vez(es).')
1426a37e040bc9a849200f43c5cc612fee91e36e
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex040_aquele_classico_da_media.py
1,058
3.875
4
# Class Challenge 12 # Calcular a média e exibir uma mensagem: # Abaixo de 5.0 reprovado, entre 5 e 6.9 recuperação e acima de 7 aprovado cores = {'limpo': '\033[m', 'negrito': '\033[1m', 'vermelho': '\033[1;31m', 'amarelo': '\033[1;33m', 'verde': '\033[1;32m'} n1 = float(input('Insira a 1ª nota do aluno: ')) n2 = float(input('Insira a 2ª nota do aluno: ')) m = n1 * 0.5 + n2 * 0.5 if m < 5: print('Voce foi {0}REPROVADO!{1} Sua média foi {2}{3:.1f}{1}' .format(cores['vermelho'], cores['limpo'], cores['negrito'], m)) elif 5 <= m < 6.9: print('Você está de {0}RECUPERAÇÃO!{1} Sua média foi {2}{3:.1f}{1}' .format(cores['amarelo'], cores['limpo'], cores['negrito'], m)) else: print('{0}PARABÉNS{1} você foi {2}APROVADO!{1} Sua média foi {0}{3:.1f}{1}' .format(cores['negrito'], cores['limpo'], cores['verde'], m)) # Exemplo do professor: print('Com a nota {:.1f} e a nota {:.1f} sua média foi {:.1f}.'.format(n1, n2, m)) # Teste lógico segue da mesma maneira
c6bd3a2159ebf010f5a9e17f9e1b1c8a968f88f2
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex005_antecessor_e_sucessor.py
386
4.03125
4
# Class challenge 007 # Mostrar o antecessor e o sucessor de um numero inteiro n = int(input('\nDigite Um numero inteiro: ')) a = n - 1 s = n + 1 print('O antecessor do numero {} é {}.'.format(n, a), end=' ') print('E o sucessor é {}'.format(s)) # Exemplo do professor n = int(input('Digite um número: ')) print('O antecessor de {} é {} e o sucessor é {}.'.format(n, n-1, n+1))
1bc7549e958d98847832cc25cf3ce84a242bb458
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex027_primeiro_e_ultimo_nome_de_uma_pessoa.py
421
3.9375
4
# Class Challenge 09 # Ler o nome completo de uma pessoa e mostar o primeiro e o último nome = str(input('Digite o seu nome completo: ')).strip() a = nome.split() print('O primeiro nome é {} e o último é {}'.format(a[0], a[0])) # Exemplo do Professor print('\nExemplo do Professor\n') print('Olá, muito prazer.') print('Seu primeiro nome é: {}'.format(a[0])) print('Seu útimo nome é: {}'.format(a[len(a)-1]))
8ca33acd165cec49c7c84b75394da1cf6b7d1f0d
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex090_dicionario_em_python.py
930
3.84375
4
# Class Challenge 19 # Read name and media of several students # Show whether the student has failed or passed student = dict() na = str(input('Enter the student name: ')) m = float(input('Enter the student media: ')) student['name'] = na student['media'] = m if m >= 7: student['Situation'] = 'Aprovado' elif 5 <= m < 7: student['Situation'] = 'Recuperação' else: student['Situation'] = 'Reprovado' print('-=' * 30) for v, i in student.items(): print(f' - {v.capitalize()} es equal a {i}') # Teacher Example: print('\nTeacher Example:') aluno = dict() aluno['Nome'] = str(input('NOme: ')) aluno['media'] = float(input(f'Media do {aluno["nome"]}')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) for k, v in student.items(): print(f' - {k} é igual {v}')
1e8dc17f6182d9c87f9c60a56e49021c5c4c7114
NathanaelV/CeV-Python
/Modulos Curso em Video/ex107_exercitando_modulos_em_python.py
499
3.828125
4
# Class Challenge 22 # Criar um módulo chamado moeda.py # Ter as funções aumentar() %; diminuir() %; dobrar() e metade() # Fazer um programa(esse) que importa e usa esses módulos # from ex107 import moeda from ex107 import moeda num = float(input('Enter a value: ')) print(f'Double of {num} is {moeda.dobrar(num)}') print(f'A half of {num} is {moeda.metade(num)}') print(f'{num} with 15% increase is {moeda.aumentar(num, 15)}') print(f'{num} with 30% reduction is {moeda.diminuir(num, 30)}')
ee8ebbe66eaae522f183e71a96c5b6bf218b34ad
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex031_custo_da_viagem.py
538
3.84375
4
# Class Challenge 10 # Calcular o preço da passagem de ônibus # R$ 0,50 para viagens até 200 km # R$ 0,45 para viages acima de 200 km d = int(input('Qual a distância da sua viagem? ')) if d <= 200: p = d * 0.5 else: p = d * 0.45 print('O preço da sua passagem é R$ {:.2f}'.format(p)) # Exemplo do professor print('\nExemplo do professor!') print('você está prestes a começar uma viagem de {} km'.format(d)) preço = d * 0.50 if d <= 200 else d * 0.45 print('E o preço da sua passagem será {:.2f}'.format(preço))
d76dc80b873a755892779f45844e57ce177ac511
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex088_palpites_para_a_mega_sena.py
1,652
4.0625
4
# Class Challenge 18 # Ask the user how many guesses he wants. # Draw 6 numbers for each guess in a list. # In a interval between 1 and 60. Numbers can't be repeated # Show numbers in ascending order. # To use sleep(1) from random import randint from time import sleep luck = list() mega = list() print('=' * 30) print(f'{"MEGA SENNA!":^30}') print('=' * 30) guess = int(input('How many guesses would you like? ')) for a in range(0, guess): while True: num = randint(1, 60) if num not in luck: luck.append(num) if len(luck) == 6: break luck.sort() mega.append(luck[:]) luck.clear() print(f'\n=-=-=-=-= Drawing {guess} Games =-=-=-=-=') sleep(0.5) for n, m in enumerate(mega): print(f'Game {n+1:<2}: [ ', end='') for a in range(0, 6): if a < 5: print(f'{m[a]:>2}', end=' - ') else: print(f'{m[a]:>2} ]') sleep(0.5) print(f'{" < GOOD LUCK! > ":=^35}') # Teacher Example: print('\nTeacher Example: ') lista = list() jogos = list() print('-' * 30) print(f'{"JOGA NA MEGA SENA":^30}') print('-' * 30) quant = int(input('Quantos jogos você quer que eu sorteie? ')) tot = 1 while tot <= quant: cont = 0 while True: num = randint(1, 60) if num not in lista: lista.append(num) cont += 1 if cont >= 6: break lista.sort() jogos.append(lista[:]) lista.clear() tot += 1 print('-=' * 3, f' SORTEANDO {quant} JOGOS ', '-=' * 3) for i, l in enumerate(jogos): print(f'Jogo {i+1}: {l}') sleep(0.5) print('-=' * 5, f'{"< BOA SORTE >":^20}', '-=' * 5)
8ea4a1eae9758fac4e17895d3a290b4b5b7e56bf
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex024_verificando_as_primeiras_letras_de_um_texto.py
839
4.0625
4
# Class Challenge 09 # Ler o nome da Cidade e ver se começa com a palavra 'Santo' cidade = input('Digite o nome da sua cidade: ') minusculo = cidade.lower().strip().split() # primeira = minu.strip() # p = primeira.split() print('Essa cidade tem a palavra santo?: {}'.format('santo ' in minusculo)) print('Santo é a primeira palavra?: {}'.format('santo ' in minusculo[0])) # Se escrever kjalSANTO ele avisa como True # print('Posição sem espaços: {}'.format(minu.find('santo'))) print('A palavra Santo aparece na posição: {}'.format(cidade.lower().find('santo'))) # Exemplo do Professor print('\nExemplo do Professor:') cid = str(cidade).strip() # Sempre que for ler uma String, usar o strip() para tirar os espaços indesejados print(cid[:5].lower() == 'santo') # Irá ler só até a 5ª lentra e comparar se é igual a santo
8e28da8e0eb769a6a9735bb6edf36567011b2a0a
NathanaelV/CeV-Python
/Aulas Mundo 3/aula20_funçoes_parte1.py
1,450
4.1875
4
# Challenge 96 - 100 # Bom para ser usado quando um comando é muito repetido. def lin(): print('-' * 30) def título(msg): # No lugar de msg, posso colocar qualquer coia. print('-' * 30) print(msg) print('-' * 30) print(len(msg)) título('Im Learning Python') print('Good Bye') lin() def soma(a, b): print(F'A = {a} e B = {b}') s = a + b print(f'A soma A + B = {s}') print('\nSomando dois Valores') soma(4, 6) soma(b=5, a=8) # Posso inverter a ordem, contanto que deixe explicito quem é quem # Emapacotamento def cont(*num): # Vai pegar os parametros e desempacotar, não importq quantos print(num) # Vai mostrar uma tupla, entre parenteses. # Posso fazer tudo que faria com uma tupla def contfor(*num): for v in num: print(f'{v}', end=', ') print('Fim') def contar(*num): tam = len(num) print(f'Recebi os valores {num} e ao todo são {tam} números') print('\nContando o número de itens') contfor(1, 2, 3, 5, 3, 2) cont(1, 7, 3) contar(3) def dobra(lst): # Por ser uma lista, não preciso usar o * pos = 0 while pos < len(lst): lst[pos] *= 2 pos += 1 print('\nDobrando valores') value = [5, 3, 6, 3, 8, 9, 0] print(value) dobra(value) print(value) def somamelhor(*num): s = 0 for n in num: s += n print(f'A soma de {num} é igual a {s}.') print('\nSoma varios valores') somamelhor(3, 5, 1, 3) somamelhor(3, 5)
560596b12e9cda1ebdadfb4ab2b5c945ad0265d1
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex103_ficha_do_jogador.py
1,173
4.21875
4
# Class Challenge 21 # Montar a função ficha(): # Que recebe parametros opcionais: NOME de um jogador e quantos GOLS # O programa deve mostrar os dados, mesmo que um dos valores não tenha sido informado corretamente # jogador <desconhecido> fez 0 gols # Adicionar as docstrings da função def ficha(name='<unknown>', goals=0): """ -> Function to read a player name and scored :param name: (Optional) If user don't enter a name, the program will print '<unknown>' :param goals: (Optional) If user don't enter number of goals, the program will print 0 :return: No return """ print(f'Player {name} scored {goals} goals.') n = input('Whats player name: ') g = input('How many goals player scored: ') if n == '' and g == '': ficha() elif n == '': ficha(goals=g) elif g == '': ficha(n) else: ficha(n, g) # Teacher example: def fichap(nome='<desconhecido>', gol=0): print(f'O jogador {nome} fez {gol} gol(s).') # Principal Program n = str(input('Nome do Jogador: ')) g = str(input('Número de gol(s): ')) if g.isnumeric(): g = int(g) else: g = 0 if n.strip() == '': ficha(goals=g) else: ficha(n, g)
f1f9c6ff93b2e33c013618b98735aa2c128f980f
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex051_progressao_aritimetica.py
300
3.859375
4
# Class Challenge 13 # Ler o primeiro termo e a razão da P.A. e mostrar os 10 primeiros números print('{:=^40}'.format(' 10 TERMOS DE UMA PA ')) t = int(input('Digite o 1º termo: ')) r = int(input('Digete a razão da PA: ')) for a in range(t, t + 10*r, r): print(a, end=', ') print('\nFim!')
143b16bde692bfc1ace62443b270d9dd50d8185c
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex003b.py
357
4.09375
4
# Class Challenge 006 # Para números Inteiros a = int(input('Digite um número: ')) b = int(input('Digete outro número: ')) c = a + b print('A soma entre {} e {} é: {}'.format(a, b, c)) #Para números Reais d = float(input('Digite um número: ')) e = float(input('Digite outro número: ')) f = d + e print('A soma entre {} e {} é: {}'.format(d, e, f))
c0f6d267dcdcd1a2dc364976bb815a9e7a524cb9
arjngpta/miscellaneous
/experiment.py
239
3.5625
4
import os i = 0 n = [1,2,3] file_list = os.listdir(os.getcwd()) for file_name in file_list: i = i + 1 if i in n: print "i is in n" else: print "i is not in n" print i print n
090e9e030c462324d39a04eab7f05a2e44e2c8a9
Scuba-Chris/game_of_greed
/game_of_greed.py
3,808
3.53125
4
import random from collections import Counter import re class Game: def __init__(self, _print=print, _input=input): self._print = print self._input = input # self._roll_dice = roll_dice self._round_num = 10 self._score = 0 self.rolled = [] self.keepers = [] def calculate_score(self, dice): roll_counter = Counter(dice) while True: score_count = 0 if len(roll_counter) > 0: if len(roll_counter) == 6: return 1500 elif len(roll_counter) == 3 and roll_counter.most_common()[2][1] == 2: return 1500 for key, value in roll_counter.items(): if roll_counter[5] == 4 and roll_counter[1] == 2: score_count += 2000 elif key == 1 and value == 6: score_count += 4000 elif key == 1 and value == 5: score_count += 3000 elif key == 1 and value == 4: score_count += 2000 elif key == 1 and value == 3: score_count += 1000 elif key >= 2 and value == 3: score_count += (key)*100 elif key >= 2 and value == 4: score_count += (key)*200 elif key >= 2 and value == 5: score_count += (key)*300 elif key >= 2 and value == 6: score_count += (key)*400 elif key == 1 and value <= 2: score_count += (value)*100 elif key == 5 and value < 3: score_count += (value)*50 roll_counter.popitem() else: break return score_count return 0 def roll_dice(self, num_dice): return [random.randint(1,6) for i in range(num_dice)] def dice_handling(self, num_dice=6): selected_dice = () self.rolled = self.roll_dice(num_dice) # selected_dice = tuple(int(char) for char in self.keepers) self._print(selected_dice) # def validate_roll(): # roll_counter = Counter(roll) # keepers_counter = Counter(keepers) # return len(keepers_counter - roll_counter) def dice_inputs(self, message): while True: try: user_input = self._input(message) user_input = [int(num) for num in user_input] for num in user_input: if 1 > num or num > 6: raise ValueError('please enter 1 -6') # regex_obj = re.compile(r'[1-6]{1-6}') # match_obj = regex_obj.match(user_input) except ValueError: self._print('Please only enter numbers') continue else: return user_input def play(self): self._print('welcome to game of greed!') start_awnser = self._input('are you ready to play? - ') if start_awnser == 'y': self.dice_handling() self._print(self.rolled) held_dice_returned_str = (self.dice_inputs('what numbers would you like to keep? - ')) # held_dice = re.findall(r'[1-6]{1,6}', str) self.keepers.append(held_dice_returned_str) else: self._print('ok. maybe another time') if __name__ == "__main__": game = Game() game.play() game.dice_handling() # try: # game.calculate_score(dice) # print(game.roll_dice(6)) # except: # print('well then')
5d86ca4b127b79be2a7edc2a93e45dfc0502ccd7
JiJibrto/lab_rab_12
/individual2.py
1,358
4.34375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # Реализовать класс-оболочку Number для числового типа float. Реализовать методы # сложения и деления. Создать производный класс Real, в котором реализовать метод # возведения в произвольную степень, и метод для вычисления логарифма числа. import math class Number: def __init__(self, num): self.a = float(num) def sum(self, b): return self.a + b def deg(self, b): return self.a / b class Real (Number): def expo(self, b): return self.a ** b def log(self, b): return math.log(self.a, b) if __name__ == '__main__': print("Инициализация обьекта класса Number") a = Number(input("Enter a> ")) print(f"Сумма чисел: {a.sum(float(input('Enter b> ')))}") print(f"Деление чисел: {a.deg(float(input('Enter b> ')))}") print("Инициализация обьекта класса Real") b = Real(input("Enter a> ")) print(f"Нахождение логарифма: {b.log(int(input('Enter b> ')))}") print(f"Возведение в степень: {b.expo(int(input('Enter b> ')))}")
c1ab809f56fb6edf4827b1978bdb32bc9b7bb532
nickolasbmm/lista2ces22
/ex11.py
550
3.78125
4
#Function with argument list def square_sequence(*arglist): print("Squared sequence: ",end="") for x in arglist: print("{} ".format(x**2),end="") print("") print("Example function with argument list") print("Initial sequence: 1 2 3 4 5") square_sequence(1,2,3,4,5) #Functio with argument dictionary def person_function(**argdict): for key in argdict: print(key," works as: ",argdict[key]) print("Example function with argument dictionary") person_function(Anne = "Student", John = "Professor", Ralph = "Shopkeeper")
b765209f2c2fc302496ec89993d73d87e2d80d56
rbngtm1/Python
/data_structure_algorithm/array/Plus_0ne.py
464
3.90625
4
given_array = [1, 2, 3, 4, 5] # length = len(given_array)-1 #print(length) # for i in range(0, len(given_array)): # #print(i) # if i==length: # given_array[i]=given_array[i]+1 # else: # given_array[i]=given_array[i] # print(given_array) ############################################ mylastindex=(given_array[-1]+1) print(mylastindex) remaining_array=(given_array[:-1]) remaining_array.append(mylastindex) print(remaining_array)
0036738f5c4ebd10ed148ed836ff304ead8b66f0
rbngtm1/Python
/data_structure_algorithm/array/contains_duplicate.py
374
3.96875
4
array = [1,2,3,4] my_array = [] # for i in array: # if i not in my_array: # my_array.append(i) # if array == my_array: # print('false') # else: # print('true') def myfunc(): for i in range(len(array)): if array[i] in my_array: return True else: my_array.append(array[i]) return False a=myfunc() print(a)
c80bffe95bc94308989cec03948a4a91239d13aa
rbngtm1/Python
/data_structure_algorithm/array/remove_duplicate_string.py
398
4.25
4
# Remove duplicates from a string # For example: Input: string = 'banana' # Output: 'ban' ########################## given_string = 'banana apple' my_list = list() for letters in given_string: if letters not in my_list: my_list.append(letters) print(my_list) print (''.join(my_list)) ## possile solution exist using set data structure but ## set structure is disorder
ee2da66a029f7bc9afad26c6025573e21bea8ae9
gyeongchan-yun/useful-python
/threading_event_queue.py
679
3.515625
4
import threading from queue import Queue evt_q = Queue() def func(): number = int(threading.currentThread().getName().split(":")[1]) if (number < 2): evt = threading.Event() evt_q.put(evt) evt.wait() for i in range(10): print ("[%d] %d" % (number, i)) if (number > 2): for _ in range(evt_q.qsize()): evt = evt_q.get() evt.set() if __name__ == '__main__': threads = [threading.Thread(target=func, name="name:%i" % i) for i in range(0, 4)] for thread in threads: thread.start() for thread in threads: thread.join() print ("exit")
1984969edc15b4e08db867aae9241e40ad8ff8ec
AbdAyyad/opensouq
/opensouqback/stringsapp/hamming_distance.py
546
3.671875
4
class hamming_distance: def __init__(self, first_string, second_string): self.first_string = first_string self.second_string = second_string self.initlize_disance() def initlize_disance(self): self.distance = 0 for i in range(len(self.first_string)): if self.first_string[i] != self.second_string[i]: self.distance +=1 def __str__(self): return 'strings: {} {}\nhamming distance: {}'.format(self.first_string, self.second_string, self.distance)
30e54e336c427637344711d8f9646d2b1fd6d43e
wendyzou02/python-test
/demolib.py
147
3.953125
4
def sum_even(start_num, end_num): sum = 0 for x in range( start_num, end_num+1 ): if x%2==0: sum += x return sum
bee174e6985d80c2a2cceb86590b5db9dbc00af6
ingridcoda/knapsack-problem
/src/model.py
575
3.578125
4
class Item: def __init__(self, size, value): self.size = size self.value = value def __str__(self): return f"{self.__dict__}" def __repr__(self): return self.__str__() class Knapsack: def __init__(self, size=0, items=None): self.size = size self.items = [] if items: self.items = items def __str__(self): return f"{self.__dict__}" def __repr__(self): return self.__str__() def get_total_value(self): return sum([item.value for item in self.items])
d2b48f3f46963d6b8a07c766acd0475e6adb4487
jbloom04/python-test
/functions.py
193
3.546875
4
batteries=[1,3,7,5] def light(batt1,batt2): # if batt1 % 2 == 0 and batt2 % 2 == 0: if batt1 in batteries and batt2 in batteries: return True else: return False
342c9e28fead18d6fc82c40892f6743b1926564a
sofieditmer/cds-visual
/assignments/assignment3_EdgeDetection/edge_detection.py
4,205
3.578125
4
#!/usr/bin/env python """ Load image, draw ROI on the image, crop the image to only contain ROI, apply canny edge detection, draw contous around detected letters, save output. Parameters: image_path: str <path-to-image-dir> ROI_coordinates: int x1 y1 x2 y2 output_path: str <filename-to-save-results> Usage: edge_detection.py --image_path <path-to-image> --ROI_coordinates x1 y1 x2 y2 --output_path <filename-to-save-results> Example: $ python edge_detection.py --image_path data/img/jefferson_memorial.jpeg --ROI_coordinates 1400 880 2900 2800 --output_path output/ Output: image_with_ROI.jpg image_cropped.jpg image_letters.jpg """ # Import dependencies import os import sys sys.path.append(os.path.join("..")) import cv2 import numpy as np import argparse # Define a function that automatically finds the upper and lower thresholds to be used when performing canny edge detection. def auto_canny(image, sigma=0.33): # Compute the median of the single channel pixel intensities v = np.median(image) # Apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edged = cv2.Canny(image, lower, upper) # Return the edged image return edged # Define main function def main(): # Initialise ArgumentParser class ap = argparse.ArgumentParser() # Argument 1: the path to the image ap.add_argument("-i", "--image_path", required = True, help = "Path to image") # Argument 2: the coordinates of the ROI ap.add_argument("-r", "--ROI_coordinates", required = True, help = "Coordinates of ROI in the image", nargs='+') # Argument 3: the path to the output directory ap.add_argument("-o", "--output_path", required = True, help = "Path to output directory") # Parse arguments args = vars(ap.parse_args()) # Output path output_path = args["output_path"] # Create output directory if it doesn't exist already if not os.path.exists("output_path"): os.mkdir("output_path") # Image path image_path = args["image_path"] # Read image image = cv2.imread(image_path) # Extract filename from image path to give image a unique name image_name, _ = os.path.splitext(os.path.basename(image_path)) ## DRAW ROI AND CROP IMAGE ## # Define ROI coordinates ROI_coordinates = args["ROI_coordinates"] # Define top left point of ROI top_left = (int(ROI_coordinates[0]), int(ROI_coordinates[1])) # Define bottom right point of ROI bottom_right = (int(ROI_coordinates[2]), int(ROI_coordinates[3])) # Draw green ROI rectangle on image ROI_image = cv2.rectangle(image.copy(), top_left, bottom_right, (0, 255, 0), (2)) # Save image with ROI cv2.imwrite(os.path.join(output_path, f"{image_name}_with_ROI.jpg"), ROI_image) # Crop image to only include ROI image_cropped = image[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]] # Save the cropped image cv2.imwrite(os.path.join(output_path, f"{image_name}_cropped.jpg"), image_cropped) ## CANNY EDGE DETECTION ## # Convert the croppe image to greyscale grey_cropped_image = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2GRAY) # Perform Gaussian blurring blurred_image = cv2.GaussianBlur(grey_cropped_image, (3,3), 0) # I use a 3x3 kernel # Perform canny edge detection with the auto_canny function canny = auto_canny(blurred_image) ## FIND AND DRAW CONTOURS ## # Find contours (contours, _) = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw green contours on the cropped image image_letters = cv2.drawContours(image_cropped.copy(), contours, -1, (0,255,0), 2) # Save cropped image with contours cv2.imwrite(os.path.join(output_path, f"{image_name}_letters.jpg"), image_letters) # Message to user print(f"\nThe output images are now saved in {output_path}.\n") # Define behaviour when called from command line if __name__=="__main__": main()
bed107a24a36afeb2176c3200aec2c525a24a55a
Silicon-beep/UNT_coursework
/info_4501/home_assignments/fraction_class/main.py
1,432
4.21875
4
from fractions import * print() ####################### print('--- setup -----------------') try: print(f'attempting fraction 17/0 ...') Fraction(17, 0) except: print() pass f1, f2 = Fraction(1, 2), Fraction(6, 1) print(f'fraction 1 : f1 = {f1}') print(f'fraction 2 : f2 = {f2}') ###################### print('--- math -------------------') # addition print(f'{f1} + {f2} = {f1 + f2}') # subtraction print(f'{f1} - {f2} = {f1 - f2}') # multiplication print(f'{f1} * {f2} = {f1 * f2}') # division print(f'{f1} / {f2} = {f1 / f2}') # floor division print(f'{f2} // {f1} = {f2 // f1}') # modulo print(f'{Fraction(7,1)} % {Fraction(2,1)} = {Fraction(7,1) % Fraction(2,1)}') # exponentiation # only works with a whole number as fraction 2 print(f'{f1} ** {f2} = {f1 ** f2}') # print(f'{Fraction(2,1)} ** {Fraction(5,4)} = {Fraction(2,1) ** Fraction(5,4)}') # print(2**(5/4), (Fraction(2, 1) ** Fraction(5, 4)).float) ##################### print('--- simplifying ------------') print(f'{f1} = {f1.simplify()}') print(f'{f2} = {f2.simplify()}') print(f'18/602 = {Fraction(18,602).simplify()}') print(f'72/144 = {Fraction(72,144).simplify()}') print(f'0/13 = {Fraction(0,10).simplify()}') #################### print('--- other things -----------') print(f'convert to float ... {f1} = {f1.float}, {f2} = {f2.float}') print(f'inverting a fraction ... {f1} inverts to {f1.invert()}') #################### print()
04dbc79957d16af67ab89c8aa72796517db8b5a6
madboy/adventofcode
/2015/days/twelve.py
734
3.78125
4
#!/usr/bin/env python import fileinput import json def count(numbers, ignore): if type(numbers) == dict: if ignore and "red" in numbers.values(): return 0 else: return count(numbers.values(), ignore) elif type(numbers) == list: inner_sum = 0 for e in numbers: inner_sum += count(e, ignore) return inner_sum elif type(numbers) == int: return numbers return 0 def bookkeeping(ignore): total = 0 for i in j: total += count(i, ignore) return total s = "" for line in fileinput.input(): s += line.strip() j = json.loads(s) print("first attempt:", bookkeeping(False)) print("second attempt:", bookkeeping(True))
c1f76fc8405ea15ec3d9112ff8efc51c5801fcb5
Nduwal3/Python-Basics-III
/academy-cli/academy/student.py
2,517
3.703125
4
import csv class Student: def __init__(self): # this.mode = mode # this.data = data pass def file_read_write(self, mode, data=None): with open ('files/students.csv', mode) as student_data: result=[] if mode == 'r': students = csv.DictReader(student_data) if students is not None: for row in students: result.append(row) else: # Create a writer object from csv module students = csv.writer(student_data) # Add contents of list as last row in the csv file students.writerow(data) return result def get_all_students(self, mode): students_list = self.file_read_write(mode) val = next(iter(students_list)) print(list(val.keys())) for item in students_list: print(list(item.values())) def get_Student_info(self, name, mode): students_list = self.file_read_write(mode) for item in students_list: if name in item.values(): print(item) else: print("no record found") break def update_student_detail(self, id, mode): students_list = self.file_read_write(mode) print("update_student_detail") print(mode) def create_new_student(self, student_data, mode): print(student_data) students_list = self.file_read_write(mode, data = student_data) print(self.__get_records_count(students_list)) print("update_student_detail") print(mode) pass def delete_student(self, name, mode): updated_list =[] students_list = self.file_read_write(mode) for student in students_list: if student.get('student_name') != name: updated_list.append(student) self.__update_file(updated_list) def __update_file(self, updatedlist): print(updatedlist) val = next(iter(updatedlist)) header = list(val.keys()) print(header) with open('files/students.csv',"w") as f: Writer=csv.DictWriter(f, fieldnames=header) Writer.writeheader() for row in updatedlist: Writer.writerow(row) print("File has been updated") def __get_records_count(self, student_list): return student_list[-1:]
7413ffdb53524a72e59fae9138e1b143a9a2e046
quanghona/Caro2
/board.py
3,919
3.515625
4
import os import curses import random class CaroBoard(object): """A class handle everything realted to the caro board""" def __init__(self, width, height): self.width = width self.height = height self.board = [[' ' for x in range(self.width)] for y in range(self.height)] self._turnCount = 0 def ConfigBoard(self): pass def UpdateBoard(self, Pos_X, Pos_Y, Marker): if self.board[Pos_X][Pos_Y] == ' ': self.board[Pos_X][Pos_Y] = Marker self._turnCount += 1 return True else: return False def CheckBoard(self, Pos_X, Pos_Y, PlayerMarker): CheckProcess = 'UpperLeft' Combo = 1 CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y # Checking if the current player has won the game # this is written for python 2 so it doesn't support nonlocal keyword while CheckProcess != 'Complete': if CheckProcess == 'UpperLeft': if CurrentCheckPosX - 1 >= 0 and CurrentCheckPosY - 1 >= 0 and \ self.board[max(0, CurrentCheckPosX - 1)][max(0, CurrentCheckPosY - 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX -= 1 CurrentCheckPosY -= 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Up' elif CheckProcess == 'Up': if CurrentCheckPosY - 1 >= 0 and \ self.board[CurrentCheckPosX][max(0, CurrentCheckPosY - 1)] == PlayerMarker: Combo += 1 CurrentCheckPosY -= 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'UpperRight' elif CheckProcess == 'UpperRight': if CurrentCheckPosX + 1 < self.width and CurrentCheckPosY - 1 >= 0 \ and self.board[min(self.width-1, CurrentCheckPosX + 1)][max(0, CurrentCheckPosY - 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX += 1 CurrentCheckPosY -= 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Right' elif CheckProcess == 'Right': if CurrentCheckPosX + 1 < self.width and \ self.board[min(self.width-1, CurrentCheckPosX + 1)][CurrentCheckPosY] == PlayerMarker: Combo += 1 CurrentCheckPosX += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'DownRight' elif CheckProcess == 'DownRight': if CurrentCheckPosX + 1 < self.width and \ CurrentCheckPosY + 1 < self.height and \ self.board[min(self.width-1, CurrentCheckPosX + 1)][min(self.height-1, CurrentCheckPosY + 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX += 1 CurrentCheckPosY += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Down' elif CheckProcess == 'Down': if CurrentCheckPosY + 1 < self.height and \ self.board[CurrentCheckPosX][min(self.height-1, CurrentCheckPosY + 1)] == PlayerMarker: Combo += 1 CurrentCheckPosY += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'DownLeft' elif CheckProcess == 'DownLeft': if CurrentCheckPosX - 1 >= 0 and \ CurrentCheckPosY + 1 < self.height and \ self.board[max(0, CurrentCheckPosX - 1)][min(self.height-1, CurrentCheckPosY + 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX -= 1 CurrentCheckPosY += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Left' elif CheckProcess == 'Left': if CurrentCheckPosX - 1 >= 0 and \ self.board[max(0, CurrentCheckPosX - 1)][CurrentCheckPosY] == PlayerMarker: Combo += 1 CurrentCheckPosX -= 1 else: CheckProcess = 'Complete' if Combo >= 5: return True return False def CheckMarkPos(self, Pos_X, Pos_Y): return self.board[Pos_X][Pos_Y] == ' ' def CheckFull(self): return self._turnCount == (self.width * self.height) def GetParameters(self): return {'Width':self.width, 'Height':self.height}
23aeff17e64ba6acfdcf8c85ae0dab9ae2ebf676
divanescu/python_stuff
/coursera/webd/func_assn42.py
926
3.765625
4
# Note - this code must run in Python 2.x and you must download # http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib from BeautifulSoup import * global url url = raw_input('Enter - ') position = int(raw_input('Position: ')) def retrieve_url(url): #url = raw_input('Enter - ') #position = int(raw_input("Position: ")) html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # Retrieve all of the anchor tags tags = soup('a') list_of_urls = list() for tag in tags: urls = tag.get('href', None) #print urls strings = str(urls) list_of_urls.append(strings.split()) #print 'url on position ',position,":", list_of_urls[position - 1] new_url = list_of_urls[position-1] print 'Retrieving:', new_url url = new_url return new_url for i in range(3): retrieve_url(url)
3474489ac3abf4439f4af04a6f2a69a743e168d6
divanescu/python_stuff
/coursera/PR4E/assn46.py
348
4.15625
4
input = raw_input("Enter Hours: ") hours = float(input) input = raw_input("Enter Rate: ") rate = float(input) def computepay(): extra_hours = hours - 40 extra_rate = rate * 1.5 pay = (40 * rate) + (extra_hours * extra_rate) return pay if hours <= 40: pay = hours * rate print pay elif hours > 40: print computepay()
a15be41097001cf7f26c42b7dbb076e8ed2bf45c
divanescu/python_stuff
/coursera/PR4E/assn33.py
347
3.84375
4
input = raw_input("Enter Score:") try: score = float(input) except: print "Please use 0.0 - 1.0 range !" exit() if (score < 0 or score > 1): print "Please use 0.0 - 1.0 range !" elif score >= 0.9: print "A" elif score >= 0.8: print "B" elif score >= 0.7: print "C" elif score >= 0.6: print "D" else: print "F"
17d4df0314c967d5cb2192b274b40cf8c3abd248
Eladfundo/task_1_18
/Code/nnet/wbg.py
1,412
3.625
4
import torch def weight_initialiser(N_prev_layer,N_current_layer,device='cpu'): """ Initializes the weight in the constructor class as a tensor. The value of the weight will be w=1/sqr_root(N_prev_layer) Where U(a,b)= Args: N_prev_layer: Number of element in the previous layer. N_current_layer:Number of elmemets in current Layer. Returns: weight: Tensor of value of weight. """ weight_val = 1.0/(N_prev_layer**0.5) print(weight_val) tensor = torch.ones((N_current_layer,N_prev_layer),requires_grad=True) weight=tensor.new_full((N_current_layer, N_prev_layer), weight_val) weight=weight.to(device) return weight def bias_initialiser(N_current_layer,device='cpu'): """ Initializes the bias as a tensor. The value of the bias will be b=0 Args: N_current_layer:Number of elmemets in current Layer. Returns: bias: Tensor of filled with 0. """ bias=torch.zeros((N_current_layer,1),requires_grad=True) bias=bias.to(device) return bias def batch_size_calc(inputs): """ parm:Takes in the input tensor returns:batch size(Integer) """ inputs_size_arr=list(inputs.size()) batch_size=inputs_size_arr[0] return batch_size
a6dd4e5cf972068af342c8e08e10b4c7355188e6
DivyaRavichandr/infytq-FP
/strong .py
562
4.21875
4
def factorial(number): i=1 f=1 while(i<=number and number!=0): f=f*i i=i+1 return f def find_strong_numbers(num_list): list1=[] for num in num_list: sum1=0 temp=num while(num): number=num%10 f=factorial(number) sum1=sum1+f num=num//10 if(sum1==temp and temp!=0): list1.append(temp) return list1 num_list=[145,375,100,2,10] strong_num_list=find_strong_numbers(num_list) print(strong_num_list)
fa798298cb31dce23c22393e07eaa94e0bb0a655
DivyaRavichandr/infytq-FP
/ticketcost.py
511
3.765625
4
def calculate_total_ticket_cost(no_of_adults, no_of_children): total_ticket_cost=0 ticket_amount=0 Rate_per_adult=37550 Rate_per_child=37550/3 ticket_amount=(no_of_adults*Rate_per_adult)+(no_of_children*Rate_per_child) service_tax=0.07*ticket_amount total_cost=ticket_amount+service_tax total_ticket_cost=total_cost-(0.1*total_cost) return total_ticket_cost total_ticket_cost=calculate_total_ticket_cost(2,3) print("Total Ticket Cost:",total_ticket_cost)
c60d478bce2ff6881160fa2045b2d10860d2730f
DivyaRavichandr/infytq-FP
/sumofdigits.py
131
3.765625
4
def sumofnum(n): sum=0 while(n!=0): sum=sum+int(n%10) n=int(n/10) return sum n=int(input("")) print(sumofnum(n))
4f7fdbff2edfa799c9db9ff345873be308face22
anfauglit/recursion
/prntstr.py
1,834
3.875
4
import random def print_str(n): # decompose the integer n and prints its digits one by one if n < 0: print('-',end='') print_str(-n) else: if n > 9: print_str(int(n / 10)) print(n % 10, end='') def digitsum(n): # calculate the sum of all its digits if n < 0: return digitsum(-n) else: if n > 0: return digitsum(int(n / 10)) + (n % 10) return 0 def digital_root(n): # digital root of an integer calculated recursivly as the sum of # all its digits and stops when the sum becomes a signle digit integer print(n) if int(n / 10) == 0: return n return digital_root(digitsum(n)) def ithdigit(n, i): # returns digit at the i'th position in the integer n # positions are counted from the right if i == 0: return n % 10 return ithdigit(int(n/10), i-1) def l_ithdigit(n, i): # returns digit at the i'th position in the integer n # positions are counted from the left n_len = len(str(n)) return ithdigit(n,n_len - i - 1) def print_str_iter(n): for i in range(len(str(n))): print(l_ithdigit(n,i), end='') def print_str_1(n): # print empty string if n equals zero if n > 0: print_str_1(int(n / 10)) print(n % 10, end='') def print_tab(n): print(n * ' ', end='') def do_nothing(d): return def simple_statement(d): print_tab(d) print('this is a python statement') def if_statement(d): print_tab(d) print('if (condition):') make_block(d+1) def for_statement(d): print_tab(d) print('for x in y:') make_block(d+1) def make_statement(d): n = random.randint(0,2) opts = [simple_statement, if_statement, for_statement] opts[n](d) def make_block(d): # generating random syntactically correct python-like programs if d > 10: simple_statement(d) else: n = random.randint(0,1) make_statement(d) opts = [do_nothing, make_block] opts[n](d) make_block(0)
d9f949f598d68412fa4035e6fe8b613d006b4dc3
AlfredKai/KaiCodingNotes
/LeetCode/Easy/Power of Three.py
392
3.703125
4
class Solution: def isPowerOfThree(self, n: int) -> bool: if n == 1: return True powOf3 = 3 while powOf3 <= n: if powOf3 == n: return True powOf3 *= 3 return False a = Solution() print(a.isPowerOfThree(27)) print(a.isPowerOfThree(0)) print(a.isPowerOfThree(9)) print(a.isPowerOfThree(45))
67b9abf27cf5751ad6b1085fe81235d4b5880d64
AlfredKai/KaiCodingNotes
/LeetCode/Medium/328. Odd Even Linked List.py
1,258
3.828125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return None if not head.next: return head oddHead = ListNode() oddTail = ListNode() evenHead = ListNode() evenTail = ListNode() odd = True pointHead = ListNode() pointHead.next = head while pointHead.next: if odd: if not oddHead.next: oddHead.next = pointHead.next oddTail.next = pointHead.next pointHead.next = pointHead.next.next oddTail = oddTail.next oddTail.next = None odd = False else: if not evenHead.next: evenHead.next = pointHead.next evenTail.next = pointHead.next pointHead.next = pointHead.next.next evenTail = evenTail.next evenTail.next = None odd = True oddTail.next = evenHead.next return oddHead.next
d31c7945dae63c6f6aff2d57588108bcbc3e492e
AlfredKai/KaiCodingNotes
/LeetCode/Hard/1044. Longest Duplicate Substring.py
1,255
3.625
4
from collections import Counter class Solution: def longestDupSubstring(self, S: str) -> str: def check_size(size): hash = set() hash.add(S[:size]) for i in range(1, len(S) - size + 1): temp = S[i:i+size] if temp in hash: return S[i:i+size] else: hash.add(temp) return '' n = len(S) i = 0 j = n - 1 while i <= j: mid = (i+j)//2 if len(check_size(mid)) > 0: i = mid if i + 1 == j: r = check_size(j) if len(r) > 0: return r else: return check_size(i) else: j = mid if i + 1 == j: r = check_size(mid-1) if len(r) > 0: return r else: return check_size(mid-2) if i == j: return check_size(mid-1) a = Solution() print(a.longestDupSubstring('abcd')) print(a.longestDupSubstring('banana'))
14dfc412b8f990b71480104de064457d69f91493
AlfredKai/KaiCodingNotes
/LeetCode/Medium/Construct Binary Tree from Preorder and Inorder Traversal.py
1,146
3.8125
4
# Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if len(preorder) == 0: return None def x(root, innerPre, innerIn): if len(innerPre) == 0: return None if len(innerPre) == 1: return TreeNode(innerPre[0]) rootInorder = innerIn.index(root.val) preLeft = innerPre[1:rootInorder+1] preRight = innerPre[rootInorder+1:] inLeft = innerIn[0:rootInorder] inRight = innerIn[rootInorder+1:] if len(preLeft) > 0: root.left = x(TreeNode(preLeft[0]), preLeft, inLeft) if len(preRight) > 0: root.right = x(TreeNode(preRight[0]), preRight, inRight) return root return x(TreeNode(preorder[0]), preorder, inorder) a = Solution() a.buildTree([3,9,20,15,7], [9,3,15,20,7])
2ecc33dd88220ed4fe133c1260a92bb34a872e5d
AlfredKai/KaiCodingNotes
/LeetCode/Contests/185/1418. Display Table of Food Orders in a Restaurant.py
1,306
3.921875
4
from typing import List class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: # ["David","3","Ceviche"] foods = set() tableNum = set() tableDish = {} for order in orders: tableN = int(order[1]) if (tableN, order[2]) not in tableDish: tableDish[(tableN, order[2])] = 1 else: tableDish[(tableN, order[2])] += 1 if order[2] not in foods: foods.add(order[2]) if tableN not in tableNum: tableNum.add(tableN) heads = ['Table'] foods = sorted(foods) for f in foods: heads.append(f) result = [heads] for t in sorted(tableNum): row = [] row.append(str(t)) for f in foods: if (t,f) in tableDish: row.append(str(tableDish[(t, f)])) else: row.append('0') result.append(row) return result # study python sorted() a = Solution() a.displayTable([["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]])
72db36b3000749d043e69702b38ef7c345cc99ef
mathtenote01/python
/triple_step.py
334
3.765625
4
def pattern_of_triple_step(N: int): if N < 0: return 0 elif N == 0: return 1 else: return ( pattern_of_triple_step(N - 1) + pattern_of_triple_step(N - 2) + pattern_of_triple_step(N - 3) ) if __name__ == "__main__": print(pattern_of_triple_step(1))
ccc3586c6e51d05a034f6f02781b0e307ae3a93e
Mariliacaps/teste-python
/CAP05/EXERCICIO05-13.py
747
3.75
4
divida=float(input("Valor da dívida: ")) taxa=float(input("Taxa de juros mensal (Ex.: 3 para 3%):")) pagamento=float(input("Valor a ser pago mensal: ")) mes=1 if (divida*(taxa/100)>= pagamento): print("O juros são superiores ao pagamento mensal.") else: saldo = divida juros_pago=0 while saldo>pagamento: juros=saldo*taxa/100 saldo=saldo+juros-pagamento juros_pago=juros_pago+juros print ("Saldo da dívida do mês %d é de R$%6.2f."%(mes,saldo)) mes=mes+1 print("Para pagar a divida de R$%8.2f, a %5.2f %% de juros,"%(divida,taxa)) print("Você precisa de %d meses, pagando R$%8.2f de juros."%(mes-1, juros_pago)) print("No ultimo mês, você teria um saldo de R$%8.2f a pagar." %(saldo))
763f30a67c364954d0b3539145857295a684329f
Mariliacaps/teste-python
/CAP03/EXERCICIO3-7.py
264
3.890625
4
#programa que peça 2 numeros inteiros e imprima a soma dos 2 numeros na tela numero01=int(input("Digite o primeiro numero: ")) numero02=int(input("Digite o segundo numero: ")) resultado=numero01+numero02 print(f"o resultado da soma dos numeros é: {resultado} ")
5703e7ab721d71cb537c3eb659ea65352c81d4d1
Mariliacaps/teste-python
/CAP04/programa4-3.py
281
4.09375
4
salario=float(input("Digite o salario para o calculo do imposto: ")) base=salario imposto=0 if base>3000: imposto=imposto+((base-3000)*0.35) base=3000 if base>1000: imposto=imposto+((base-1000)*0.20) print(f"salario: R${salario:6.2f} imposto a pagar: R${imposto:6.2f}")
be1ae90fe39e8bfdc0b0bc64ab50ba9c62650c8e
tobetobe/python_start
/hello.py
504
4
4
# for index, item in enumerate(['a', 'b', 'c']): # print(index, item) def printHello(): """ say Hello to the console Just print a "hello """ print("hello") # printHello() # list = ['bca', 'abc', 'ccc'] # sorted(list) # print(list) # list = [v*2 for v in range(1, 10)] # print(list) list = ['aa', 'b', 'c'] for v in list: print(v.title()) # a = [1] # if a: # print(a) # b = a # print(b) # b.append(2) # print(a, b) # b = [] # print(bool(b)) # if b: # print(b)
580a0daea555236dcc97ca069180fc26d3cb1093
yangtuothink/Python_AI_note
/other_add/sock(key=) demo.py
372
4
4
""" sort() 函数内含有 key 可以指定相关的函数来作为排序依据 比如这里指定每一项的索引为1 的元素作为排序依据 默认是以第一个作为排序依据 """ def func(i): return i[1] a = [(2, 2), (3, 4), (4, 1), (1, 3)] a.sort(key=func) # [(4, 1), (2, 2), (1, 3), (3, 4)] # a.sort() # [(1, 3), (2, 2), (3, 4), (4, 1)] print(a)