blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
018792850a4d1e3aa7a73c3666fb854f28fe4937
adityasharma2057/pythonUdemy
/Assignments.py
489
3.859375
4
class MaxSizeList: maxSize = 0 def __init__(self, val): self.maxSize = val self.list = [] def push(self, value): print "pushing " + value + ", Len = " + str(len(self.list)) + " with maxsize = " + str(self.maxSize) if len(self.list) < self.maxSize: self.list.append(value) elif len(self.list) >= self.maxSize: self.list.pop(0) self.list.append(value) def get_list(self): print(self.list)
528bd7b3b98b93f086701f0936e989e1a2f793dd
greenfox-zerda-lasers/bednayb
/week-03/day-03/bonus.py
276
3.6875
4
a = "*" maxstar = 6; i = 0; j = 0; for j in range(2): if j == 1: while i>0: print (a*(i-1)) i -= 1; if i == 0: exit() for i in range(maxstar): print (a*i) if i == 5: j += 1;
a4b65bf536c1081d5365b0c2de7ef0a17a45f951
aayushmaanhooda/python-projects
/snake.py
1,045
3.6875
4
from turtle import * import random from freegames import square , vector import time food= vector(0,0) snake =[vector(10,0)] aim = vector(0 , -10) def change(x,y): aim.x =x aim.y = y def inside(head): return -200 <head.x <190 and -200 <head.y <190 def move(): head = snake[-1].copy() head.move(aim) if head in snake or not inside(head): square(head.x , head.y , 9 , 'red') update() return snake.append(head) if head ==food: print("snake :" , len(snake)) food.x = random.randrange(-15 , 15)*10 food.y = random.randrange(-15 , 15) *10 else: snake.pop(0) for body in snake: square(body.x , body.y , 9 , "black") square(food.x , food.y , 9 , 'green') update() ontimer(move , 100) listen() onkey(lambda : change(10,0) , 'Right' ) onkey(lambda : change(-10,0) , 'Left' ) onkey(lambda : change(0,10) , 'Up' ) onkey(lambda : change(0,-10) , 'Down' ) setup(420 , 420 , 370 ,0) hideturtle() tracer(False) move() done()
b3d6838c6d2ab5e977967a87206483038ab09354
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/kstavr001/question2.py
338
4.125
4
#Assignment 8,Question 2 #Avreyna Kistensamy #3 May 2014 def pairs(check): num_of_p = 0 if len(check) < 2: return 0 elif check[0] == check[1]: return 1 + pairs(check[2:]) else: return pairs(check[1:]) x = input("Enter a message:\n") check = x print("Number of pairs:",pairs(check))
c9abebdc7585c5e4c967c0e9aa2f991d4002482d
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_118/2174.py
712
3.984375
4
from math import sqrt def is_palindrome(n): s = str(n) return True if s == s[::-1] else False def is_fairly_square(n): sqrt_of_n = sqrt(n) return sqrt_of_n.is_integer() and is_palindrome(int(sqrt_of_n)) def is_fair_and_square(n): return True if is_palindrome(n) and is_fairly_square(n) else False def main(): f = open('1.in', 'r') o = open('1.out', 'w') T = int(f.readline().strip()) for t in xrange(T): res = 0 start, end = f.readline().split() #print start + ' ' + end for n in xrange(int(start), int(end) + 1): if is_fair_and_square(n): res += 1 s = "Case #%d: %s\n" % (t+1, res) #print s o.write(s) if __name__ == "__main__": main()
7bc0954a1012d781c23a2b9dd391529ab96e1d40
winlp4ever/algos
/codeforces/r638/science.py
801
3.578125
4
t = int(input()) def ord2(k): i = 0 while k: k //= 2 i += 1 return i def binsearch(nums, val, l, h): if nums[h] <= val: return h if nums[0] > val: return -1 if l + 1 >= h: return l m = (l+h)//2 if val >= nums[m]: return binsearch(nums, val, m, h) return binsearch(nums, val, l, m) def sol(): n = int(input()) k = ord2(n) # days = k-1 nbs = [] i = 1 pw2 = 0 while pw2 < k-1: nbs.append(i) i *= 2 pw2 += 1 d = n+1-i ix = binsearch(nbs, d, 0, k-2) nbs.insert(ix+1, d) res = [] for i in range(1, k): res.append(str(nbs[i]-nbs[i-1])) return '%d\n%s' % (k-1, ' '.join(res)) for _ in range(t): print(sol())
861eb8f978b35244a4e39d77b9a502fedccf2289
prabhatse/pricing2k19
/common/utils.py
436
3.578125
4
import re class Utils: @staticmethod def email_is_valid(email: str) -> bool: email_address_matcher = re.search("[a-z][a-z.,0-9]+@[a-z]+.[a-z]+", email) found_email = email_address_matcher.group(0) if email == found_email: return True return False @staticmethod def check_password(password: str, user_password: str) -> bool: return password == user_password
ddf420405028668bd9e6adb7a88158c3f1b1d064
DheerajJoshi/Python-tribble
/PythonString/src/isnumeric.py
109
3.578125
4
#!/usr/bin/python str1 = u"this2009"; print (str1.isnumeric()); str1 = u"23443434"; print (str1.isnumeric());
61d2eac595c6f92ebad8cc34f6e6f4692cb47d54
ataylor1184/cse231
/proj09/proj09.py
10,021
3.9375
4
#============================================================================== #Project 9 # Prompts for file. Returns file point. # Pulls relevant data from file using loops. # Sends tweets to several functions to find the hashtags # Calls several functions to organize data by counting the hashtags in a given month # or by counting hashtags by a given user # Sends the hashtag counts to another function to check for similarities # between user tweets # Displays data in table format # Data is sent to function to be graphed and displayed. #============================================================================== import string, calendar, pylab MONTH_NAMES = [calendar.month_name[month] for month in range(1,13)] def open_file(): '''tries to open a file, prompts user again if file is not found''' bool_loop = False while bool_loop == False: file_str = input('Input a filename:') try: fp = open(file_str,"r") #fp = open('smalldata.csv') return(fp) bool_loop = True except: print(" Error in input filename. Please try again.") pass def validate_hashtag(s): '''makes sure the hashtag found is in correct format''' for c in s: if c in string.punctuation and c != '#': #print('post',s) return False if len(s) == 2 and s[1].isdigit(): #print('post',s) return False else: return True pass # def get_hashtags(s): '''finds the hashtag in the tweet and sends it to be validated''' hashtags_list = [] s = s.split(" ") for word in s: if word != '': if word[0]== '#': #print('pre',word) if validate_hashtag(word) == True: hashtags_list.append(word) return hashtags_list pass def read_data(fp): '''reads the data from the file and organizes it into a list''' data_list = [] for line in fp: line = line.split(',') username = line[0] month = int(line[1]) tweet = line[2] hashtags_list = get_hashtags(tweet) data = [] data.append(username) data.append(month) data.append(hashtags_list) data_list.append(data) return(data_list) pass def get_histogram_tag_count_for_users(data,usernames): '''counts the hashtags used by a given user''' dict_count = {} for listt in data: if listt[0] in usernames: tag = listt[2] for i,c in enumerate(tag): if c in dict_count: dict_count[c] += 1 else: dict_count[c] = 1 #print(dict_count) return(dict_count) pass def get_tags_by_month_for_users(data,usernames): '''counts the hashtag used by the user in a given month''' empty_set = set() key = 0 month_list = [] m=0 temp_list = [] for m in range(1,13): key = m for listt in data: if key == int(listt[1]): if listt[0] in usernames: for tag in listt[2]: empty_set.add(tag) temp_list.append(m) temp_list.append(empty_set) temp_list = tuple(temp_list) month_list.append(temp_list) empty_set = set() temp_list = [] return(month_list) pass def get_user_names(L): '''creates a list of usernames given a set of data''' user_name_list = [] for tup in L: if tup[0] not in user_name_list: user_name_list.append(tup[0]) user_name_list = sorted(user_name_list) return(user_name_list) def three_most_common_hashtags_combined(L,usernames): '''returns the 3 most common hashtags out of all users''' dict_count = {} data = L most_common_list = [] num = 0 tag = '' create_tup = [] for listt in data: if listt[0] in usernames: tag = listt[2] for i,c in enumerate(tag): if c in dict_count: dict_count[c] += 1 else: dict_count[c] = 1 dict_count = sorted(dict_count.items(), key=lambda x: x[1],reverse = True) n = 0 for tup in dict_count: for k in tup: if n == 2: create_tup.append(num) create_tup.append(tag) create_tup = tuple(create_tup) most_common_list.append(create_tup) create_tup = [] n=0 if n == 0 : tag = k if n == 1 : num = k n+=1 most_common_list = most_common_list[0:3] return (most_common_list) pass def three_most_common_hashtags_individuals(data_lst,usernames): '''finds the 3 most common hashtags for all individual users then returns the highest 3''' most_common_list = [] num = 0 tag = '' create_tup = [] count = 0 n = 0 for name in usernames: num = get_histogram_tag_count_for_users(data_lst,name) num = sorted(num.items(), key=lambda x: x[1],reverse = True) for tup in num: for element in tup: if n ==2: create_tup.append(count) create_tup.append(tag) create_tup.append(name) create_tup = tuple(create_tup) most_common_list.append(create_tup) create_tup=[] n = 0 if n % 2 == 0: tag = element if n % 2 != 0: count = element n+=1 most_common_list = sorted(most_common_list, reverse = True) most_common_list = most_common_list[0:3] return(most_common_list) pass def similarity(data_lst,user1,user2): '''counts the similar hashtags used between users for each month''' data = data_lst tup_list = [] sim_list = [] user1_month = get_tags_by_month_for_users(data,[user1]) user2_month = get_tags_by_month_for_users(data,[user2]) for n in range(0,len(user1_month)): intersection = user1_month[n][1].intersection(user2_month[n][1]) # print('intersection:',intersection) tup_list.append(n+1) tup_list.append(intersection) tup_list = tuple(tup_list) sim_list.append(tup_list) tup_list = [] #print(sim_list) # xxx #twitterdata.csv # #xxx # #xxx, yyy # #WKARnewsroom, michiganstateu # #no return(sim_list) pass def plot_similarity(x_list,y_list,name1,name2): '''Plot y vs. x with name1 and name2 in the title.''' pylab.plot(x_list,y_list) pylab.xticks(x_list,MONTH_NAMES,rotation=45,ha='right') pylab.ylabel('Hashtag Similarity') pylab.title('Twitter Similarity Between '+name1+' and '+name2) pylab.tight_layout() pylab.show() # the next line is simply to illustrate how to save the plot # leave it commented out in the version you submit #pylab.savefig("plot.png") def main(): data_list = [] usernames = [] usernames_str = '' y_list = [] fp = open_file() data_list = read_data(fp) usernames = get_user_names(data_list) tag_count_dict = get_histogram_tag_count_for_users(data_list,usernames) tag_month = get_tags_by_month_for_users(data_list,usernames) most_common_combined = three_most_common_hashtags_combined(data_list,usernames) most_common_individual = three_most_common_hashtags_individuals(data_list,usernames) similarity_list = similarity(data_list,usernames[0],usernames[1]) print("Top Three Hashtags Combined") print("{:>6s} {:<20s}".format("Count","Hashtag")) for element in most_common_combined: print("{:>6} {:<20}".format(element[0],element[1])) print() print("Top Three Hashtags by Individual") print("{:>6s} {:<20s} {:<20s}".format("Count","Hashtag","User")) for element in most_common_individual: print("{:>6} {:<20} {:<20s}".format(element[0],element[1],element[2])) print() usernames_str = ', '.join(usernames) print("Usernames: ", usernames_str) while True: # prompt for and validate user names user_str = input("Input two user names from the list, comma separated: ") user_str = user_str.replace(" ",'') # print(user_str) try: user_str = user_str.split(',') username1 = user_str[0] username2 = user_str[1] except: pass if username1 in usernames_str and username2 in usernames_str: break else: print("Error in user names. Please try again") similarity_list = similarity(data_list,username1,username2) print() print("Similarities for "+username1+" and "+username2) print("{:12}{:2}".format("Month","Count")) for tup in similarity_list: count = 0 n = tup[0] for tag in tup[1]: count +=1 y_list.append(count) print("{:10}{:3}".format(MONTH_NAMES[n-1],count)) print() # Prompt for a plot choice = input("Do you want to plot (yes/no)?: ") if choice.lower() == 'yes': x_list = [1,2,3,4,5,6,7,8,9,10,11,12] plot_similarity(x_list,y_list,username1,username2) if __name__ == '__main__': main()
ef6e5e2af0bdee506feb526144489e3cb2a527da
shankar7791/MI-10-DevOps
/Personel/Yash/Python/Practice/March25Inheritance/prog2.py
324
3.84375
4
#Multilevel Inheritance class Parent: def func1(self): print("I am parent of child 1 ") class Child1(Parent): def func2(self): print("I am Parent of child 2") class Child2(Child1): def func3(self) : print("I am not Parent now") ob = Child2() ob.func1() ob.func2() ob.func3()
c92544454e89feadf91976007ac88a36f9f16e13
schwarzwaldsvd/PythonFundamentals
/07_iterables/iterables.py
503
3.9375
4
from math import factorial words = "Why sometimes I have believed as many as six impossible things before breakfast".split() def print_words_lengths1(): return [len(word) for word in words] def print_words_lengths2(): lengths = [] for word in words: lengths.append(len(word)) return lengths def print_fac_lengths(number): return [len(str(factorial(x))) for x in range(number)] def print_fac_lengths_set(number): return {len(str(factorial(x))) for x in range(number)}
bc25b4b643e9f391158a8d4dd60c3d88c63c99ba
swapnil-narwade/PythonProgramming
/chatroom/chatroom_with_multithread/client.py
3,835
3.625
4
#name Swapnil Narwade #UTA ID-- smn6025 #Assignment-1 #referances:-- 1) https://docs.python.org/2/library/httplib.html # 2) https://docs.python.org/2/library/datetime.html # 3) https://www.learnpython.org/en/Modules_and_Packages # 4) https://github.com/buckyroberts/Turtle/tree/master/Multiple_Clients # 5) https://www.youtube.com/watch?v=Po5JHXIoDr0&t=5s import os #importing standerd libraries import socket import urllib import datetime import time class Client(object): #created a Client class def __init__(self): #initialized attributes self.host = '127.0.0.1' #this is the host of our server self.port = 8000 #this is the port of server where connection bind self.s = None #this is a socket def create_socket(self): #creating a socket self.s = socket.socket() def connect_socket(self): #connect to a server socket try: self.s.connect((self.host, self.port)) # connect host and port except: print("Socket connection error: ") time.sleep(5) #wait for 5 second and connect again def commands(self): name = input("enter your name ") self.s.send(name.encode()) #send message to client in string while True: #run in loop to get and send request try: message = input("-->") #message is getting from terminal while message != 'q': #checking if message is not q self.s.send(message.encode()) #sending the message in byte format by encoding data = self.s.recv(1024) print("data received from server " + data.decode())#data received from server and decoded message = input("-->") #message is getting from terminal self.s.close() #socket is closed # msg = self.s.recv(2048) #to receive string # print("-->" + msg.decode()) #print message # sent_message = input("-->") #accept input from terminal # message1 = datetime.datetime.now().strftime('%M:%S') #message with time # message2 = sent_message + str(" (") + str(message1) + str(")") # self.s.send(message2.encode()) continue #continue to commands functions except: time.sleep(5) #wait for 5 minute to receive text print("type something") continue def main(): client = Client() #assign Client class to client client.create_socket() #create socket for client while True: #run in loop try: client.connect_socket() #connect socket except: print("Error on socket connections:") time.sleep(5) #wait for 5 second to reconnect try: client.commands() #run command function except: print("Error") client.s.close() #close client socket if __name__ == '__main__': while True: main()
9fee471adf05593a3ab5f373b79153fec8b90ad8
Vinodk-17/Random-password-generator
/password.py
385
3.796875
4
import password_creator a=input("u = Uppercase Alphabet\nl = lowercase Alphabet\nd = Numerical Digits\ns = Special Characters\n Enter the character set : ") b=int(input("Enter the length of your password : ")) password=password_creator.Password(a,b) password.char_in_the_pass() password.generate_the_password() print("The Randomly generated strong password : ",password.get_password())
f0e5add3431eb82292b336eb61a7ae6614f6b4f2
Ad7siem/Projekt
/Klasa jako dekorator funkcji.py
2,684
3.796875
4
import random class MemoryClass: list_of_already_selected_itemes = [] def __init__(self, funct): # print('>> this is init od MemoryClass') self.funct = funct def __call__(self, list): # print('>> this is call of MemoryClass instance') items_nor_selected = [i for i in list if i not in MemoryClass.list_of_already_selected_itemes] # print('+-- selecting only from a list of', items_nor_selected) item = self.funct(items_nor_selected) MemoryClass.list_of_already_selected_itemes.append(item) return item cars = ['Opel', 'Toyota', 'Fiat', 'Ford', 'Renault', 'Mercedes', 'BMW', 'Peugeot', 'Porsche', 'Audi', 'VW', 'Mazda'] @MemoryClass def SelectTodayPromation(list_of_cars): return random.choice(list_of_cars) @MemoryClass def SelectTodayShow(list_of_cars): return random.choice(list_of_cars) @MemoryClass def SelectFreeAccessories(list_of_cars): return random.choice(list_of_cars) print('Promotion:', SelectTodayPromation(cars), '\n', '-' * 30) print('Show:', SelectTodayShow(cars), '\n', '-' * 30) print('Free accessories', SelectFreeAccessories(cars), '\n', '-' * 30) print('\n') # ćwiczenia class NoDuplicates: def __init__(self, funct): self.funct = funct def __call__(self, cake, additives): no_duplicate_list = [] for a in additives: if not a in cake.additives: no_duplicate_list.append(a) self.funct(cake, no_duplicate_list) class Cake: bakery_offer = [] def __init__(self, name, kind, taste, additives, filling): self.name = name self.kind = kind self.taste = taste self.additives = additives.copy() self.filling = filling self.bakery_offer.append(self) def show_info(self): print("{}".format(self.name.upper())) print("Kind: {}".format(self.kind)) print("Taste: {}".format(self.taste)) if len(self.additives) > 0: print("Additives:") for a in self.additives: print("\t\t{}".format(a)) if len(self.filling) > 0: print("Filling: {}".format(self.filling)) print('-' * 20) def add_additives(self, additives): self.additives.extend(additives) cake01 = Cake('Vanilla Cake', 'cake', 'vanilla', ['chocolade', 'nuts'], 'cream') @NoDuplicates def add_extra_additives(cake, additives): cake.add_additives(additives) add_extra_additives(cake01, ['strawberries', 'sugar-flowers']) cake01.show_info() add_extra_additives(cake01, ['strawberries', 'sugar-flowers', 'chocolade', 'nuts']) cake01.show_info()
a48f4bedef4ee09fb71b80baaff19261b727334f
Anne19953/Algorithmspractice
/数据结构之排序与查找/排序算法/快排.py
1,196
3.96875
4
#!/usr/bin/env python # coding:utf-8 """ Name : 快排.py Author : anne Time : 2019-08-28 21:16 Desc: """ def quick_sort(alist,start,end): #递归退出条件 if start >= end : return #设定起始划分元素 mid = alist[start] #low为序列左边的由左向右移动的游标 low = start #high为序列右边从由右向左移动的游标 high = end while low < high: while low < high and alist[high] >= mid: high -= 1 #将high指向的元素放到low的位置 alist[low] = alist[high] # 如果low与high未重合,low指向的元素比基准元素小,则low向右移动 while low < high and alist[low] <= mid: low += 1 #将low指向的元素放到high的位置 alist[high] = alist[low] #退出循环后,low和high重合,此时所指的位置为基准元素的正确位置 #此时的low和high相等 alist[low] = mid #对基准右边子序列进行快排 quick_sort(alist,low+1,end) #对基准左边子序列进行快排 quick_sort(alist,start,low-1) alist = [56,99,34,10,38,7] quick_sort(alist,0,len(alist)-1) print(alist)
ff3d2fefd117c5876665da1ec03ced80f8116125
Derfies/nodebox-opengl
/examples/10-gui/02-panel.py
2,400
3.640625
4
# Add the upper directory (where the nodebox module is) to the search path. import os, sys; sys.path.insert(0, os.path.join("..","..")) from nodebox.graphics import * from nodebox.gui import * # A panel is a container for other GUI controls. # Controls can be added to the panel, # and organized by setting the controls' x and y properties # (since all controls inherit from Layer, they all have the same properties as a layer). panel = Panel("Example", width=200, height=200, fixed=False, modal=False) # Alternatively, a layout manager can be added to a panel. # A layout manager is itself a group of controls. # By calling Layout.apply(), the manager will take care of arranging its controls. # A simple layout manager is "Rows" layout, in which each control is drawn on a new row. # A caption can be defined for each control in the Rows layout, # it will be placed to the left of each control. layout = Rows() layout.extend([ Field(value="hello world", hint="text", id="text"), ("size", Slider(default=1.0, min=0.0, max=2.0, steps=100, id="size")), ("alpha", Slider(default=1.0, min=0.0, max=1.0, steps=100, id="alpha")), ("show?", Flag(default=True, id="show")) ]) # The panel will automatically call Layout.apply() when the layout is added. panel.append(layout) # With Panel.pack(), the size of the panel is condensed as much as possible. panel.pack() # Panel inherits from Layer, # so we append it to the canvas just as we do with a layer: canvas.append(panel) def draw(canvas): canvas.clear() # In this simple example, # we link the values from the controls in the panel to a displayed text. # Controls with an id are available as properties of the panel # (e.g. a control with id "slider" can be retrieved as Panel.slider). # Most controls have a Control.value property that retrieves the current value: if panel.show.value == True: font("Droid Serif") fontsize(50 * panel.size.value) fill(0, panel.alpha.value) text(panel.text.value, 50, 250) canvas.size = 500, 500 canvas.run(draw) # Note: # We named one of the sliders "alpha" instead of "opacity", # which would be a more comprehensible id, but which is already taken # because there is a Panel.opacity property (inherited from Layer). # In reality, it is much better to choose less ambiguous id's, # such as "field1_text" or "slider2_opacity".
2d9ffdb78d9e3b36ffd5ca5cd5b909fbc6ca8a31
arara90/AlgorithmAndDataStructure
/Practice_python/bb.py
357
3.90625
4
user_input = input() orderArr = { '8' : 0, '5' : 1, '2' : 2, '4' : 3, '3' : 4, '7' : 5, '6' : 6, '1' : 7, '0' : 8, '9' : 9, } res = user_input.split(' ') resdict= {} for i in res: resdict.setdefault(orderArr[i], i) sorteddict = sorted(resdict.items()) resList = [] for item in sorteddict: resList.append(item[1]) print(' '.join(resList))
3b7843fb03488875924b9ed983b0cbfea7ea6bea
Bharadwaja92/HackerRank10DaysStats
/Day1_StdDev.py
465
4.03125
4
"""""" """ Given an array, X, of N integers, calculate and print the standard deviation. Your answer should be in decimal form, rounded to a scale of 1 decimal place (i.e., 12.3 format). An error margin of +-0.1 will be tolerated for the SD. """ n = int(input()) nums = list(map(int, input().split())) mean = sum(nums) / n squared_deviations = [(x-mean)**2 for x in nums] variance = sum(squared_deviations) / n stddev = variance ** 0.5 print('%.1f'%stddev)
a39a4591c82ecd97f4ad4fe12a010473d48f5949
jonathanengelbert/data_structures_and_algos
/data-structures/recursion/sum_with_recursion.py
139
3.890625
4
nums = [1, 3, 5, 7, 9] def add(nums): if len(nums) == 1: return nums[0] return nums[0] + add(nums[1:]) print(add(nums))
232ab1b44fa286e0e04a63c6635a6e5d6560dca4
featherblacker/LeetCode
/Easy/653/653.py
1,099
3.8125
4
# -*- coding: utf-8 -*- # @Time : 09:25 2020/3/26 2020 # @Author : chuqiguang # @FileName: 653.py # @Software: PyCharm # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ res = [] res = self.findAll(root, res) res.sort() if len(res) < 2 or res[0] + res[1] > k or res[-1] + res[-2] < k: return False l = 0 r = len(res) - 1 while l < r: if res[l] + res[r] == k: return True elif res[l] + res[r] < k: l += 1 elif res[l] + res[r] > k: r -= 1 return False def findAll(self, root, res): if root.left: self.findAll(root.left, res) res += [root.val] if root.right: self.findAll(root.right, res) return res
5ad31ac2cb3ad2f578dba0273e79c35d4ea4f2fc
ZYZMarshall/GitHubApi567
/HW04567.py
1,598
3.90625
4
import requests import json """ You should write a function that will take as input a GitHub user ID. The output from the function will be a list of the names of the repositories that the user has, along with the number of commits that are in each of the listed repositories. """ def getUserRepos(userName): API = ("https://api.github.com/users/" + userName + "/repos") userData = requests.get(API) repositories = json.loads(userData.text) userRepos = [] for repository in repositories: try: userRepos.append(repository.get("name")) except: userRepos = [] return userRepos def getCommitnum(userName, repoName): # number of commits that are in each of the listed repositories. API = "https://api.github.com/repos/" + userName + "/" + repoName + "/commits" repoData = requests.get(API) commits = json.loads(repoData.text) Commitnum = len(commits) return Commitnum """ Main function that lists all the repos and lists each commit count given a specific github user name. """ if __name__ == "__main__": userName = input("Enter Github username: ") #Ask for username userRepos = getUserRepos(userName) # Get Respos according to the username print("User: " + userName) for repository in userRepos: #Use for Loop to printing name and their commit in associated repos Commitnum = getCommitnum(userName, repository) print("Repo: " + repository + " Number of Commits: " + str(Commitnum))
b75c49b42046b36b2fa7e7d04b5b57db92757817
GaryLouisStewart/EDX_6.00.2X
/pset_1.py
502
3.546875
4
List = [('Gold', 10, 500), ('Silver', 5, 200), ('Diamond', 2, 2000), ('Platinum', 20, 1000)] aList = sorted(List, key = lambda x : x[2]) # sort the list above def plunder(aList, c): aList[-1] = list(aList[-1]) i = aList[-1] r = 0 if c > 0 and i[1] != 0: c -= 1 i[1] -=1 r += 1 return plunder(aList, c-r) elif c == 0: pass print('Done') else: return plunder(aList[:-1], c-r) plunder(aList, 10) print(plunder(aList, 100))
d5acd63f01a172e59b527aa2cdb2540c14c2229c
cjbassi/pymath
/pymath/other.py
860
3.765625
4
import string __all__ = ['convert_base', 'convert_to_base_10'] def convert_to_base_10(x: int, base: int) -> str: """https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-in-any-base-to-a-string""" digits = string.digits + string.ascii_uppercase if x < 0: sign = -1 elif x == 0: return digits[0] else: sign = 1 x *= sign converted = [] while x: converted.append(digits[int(x % base)]) x = int(x // base) if sign < 0: converted.append('-') converted.reverse() return ''.join(converted) def convert_base(x: str, source: int, dest: int) -> str: """ Returns: 'n' converted from base 'source' to base 'dest' """ if source == 10: return convert_to_base_10(int(x), dest) return convert_to_base_10(int(x, source), dest)
b508c503d96b180cb024c2a37829aee84fa40030
BizaoDeBizancio/ufabc
/poo/simulado/fila.py
7,753
4
4
# -*- coding: utf-8 -*- import random class Fila(object): """ Implementa uma fila simples (o primeiro a entrar é o primeiro a sair) que pode receber qualquer tipo de objeto. """ def __init__(self): self.data = [] def insere(self, elemento): elemento.na_fila = True self.data.append(elemento) def retira(self): elem = self.data.pop(0) return elem def vazia(self): """Devolve True se fila vazia, False do contrário""" return len(self.data) == 0 def tamanho(self): """Devolve a quantidade de objetos ainda guardados na fila. """ return len(self.data) class Caixa(object): """ Implementa o comportamento de caixa para simulaçao de fila de banco. """ def __init__(self): self.fim_atendimento = 0 def livre(self, instante): """Devolve True se o caixa está livre para receber um novo cliente, False do contrário. """ return instante > self.fim_atendimento def atende(self, cliente, instante): """Tenta atender um cliente em determinado instante de tempo. cliente: objeto do tipo cliente a ser atendido instante: instante de tempo em que o atendimento se inicia Devolve True caso o caixa consiga atender o cliente, False do contrário. """ if self.livre(instante): cliente.atende(instante) self.fim_atendimento = instante + cliente.duracao_atendimento atendido = True return atendido class Cliente(object): """Implementa o comportamento do cliente do banco. """ def __init__(self, instante_chegada, duracao_atendimento): """Parametros: instante_chegada: momento em que o cliente chega no banco. duracao_atendimento: duração do procedimento que o cliente deseja realizar no banco. """ self.instante_chegada = instante_chegada self.duracao_atendimento = duracao_atendimento self.instante_atendimento = -1 self.espera = -1 # contabiliza o tempo de espera do cliente self.atendido = False self.na_fila = False def atende(self, instante_atendimento): """ Esse método deve ser chamado pelo objeto que coordena a simulação. instante_atendimento: instante em que o caixa atende o cliente. Esse método calcula o valor da espera total do cliente. """ self.atendido = True self.instante_atendimento = instante_atendimento self.espera = instante_atendimento - self.instante_chegada class DistribuicaoClientes(object): """Responsável por criar um sequência de clientes, de acordo com uma distribuição probabilistica. """ def __init__(self, intervalo_medio, duracao_media): # intervalo medio entre um cliente e outro self.duracao_minima = 60 # duracao minima de um atendimento # intervalo medio entre chegadas de clientes consecutivos self.intervalo_medio = intervalo_medio # duracao média do atendimento dos clientes self.duracao_media = duracao_media def cria_clientes(self, tempo_maximo): """ Cria uma lista de clientes, ordenada por instante de chegada """ clientes = [] tempo = 0 while tempo < tempo_maximo: # distribuição uniforme dos intervalos entre # chegada de clientes -- não é um modelo # realista, escolhido por simplicidade delta_t = random.randint(0, 2*self.intervalo_medio) # distribuição uniforme dos tempos de atendimento # dos clientes -- não é um modelo # realista, escolhido por simplicidade duracao_max = 2*self.duracao_media - self.duracao_minima atendimento = random.randint(self.duracao_minima, duracao_max) # print tempo + delta_t cl = Cliente(tempo + delta_t, atendimento) tempo += delta_t clientes.append(cl) return clientes def calcula_max(clientes): """Recebe uma sequência de clientes que já foram atendidos e calcula os valores máximos de espera e tempo de atendimento. Devolve uma tupla (espera_max, tempo_de_atendimento_max) """ espera_max = 0 tempo_max = 0 for cl in clientes: if cl.duracao_atendimento > tempo_max: tempo_max = cl.duracao_atendimento if cl.espera > espera_max: espera_max = cl.espera return (espera_max, tempo_max) def calcula_medias(clientes): """Recebe uma sequência de clientes que já foram atendidos e calcula os valores médios de espera e tempo de atendimento. Devolve uma tupla (espera_media, tempo_de_atendimento_medio) """ contador = 0 espera_acumulada = 0 tempo_acumulado = 0 for cl in clientes: contador += 1 tempo_acumulado += cl.duracao_atendimento espera_acumulada += cl.espera espera_media = espera_acumulada/contador tempo_de_atendimento_medio = tempo_acumulado/contador return (espera_media, tempo_de_atendimento_medio) class Simula(): def __init__(self): # constroi self.intervalo_medio = int(raw_input("Digite o intervalo medio de chegada dos clientes:\n")) self.duracao_media = int(raw_input("Digite a duração média de atendimento dos clientes:\n")) self.tempo_maximo = int(raw_input("Digite o tempo maximo:\n")) # cria a lista de clientes self.clients = DistribuicaoClientes(self.intervalo_medio, self.duracao_media).cria_clientes(self.tempo_maximo) # cria caixas de atendimento self.num_caixas = int(raw_input("Com quantos caixas você deseja simular:\n")) self.caixas = [] for i in range (0, self.num_caixas): self.caixas.append(Caixa()) # cria fila self.fila = Fila() def inicia (self): contador = 0 # or not self.fila.vazia() -> pode causar erros caso o intervalo de chegada seja menor que a duracao media # cai num loop infinito while (contador < self.tempo_maximo): # verifica o tempo atual e o do cliente for client in self.clients: # insere todos os clientes com tempo de chegada menor que o contador # verifica se nao esta na fila e se ja nao foi atendido # nao posso remover porque os calculos de tempo dependem dos clientes if (client.instante_chegada <= contador) and not client.na_fila and not client.atendido: self.fila.insere(client) # verifica se o caixa esta livre for caixa in self.caixas: # sabe se o caixa esta livre pelo contador (!?) if caixa.livre(contador): # tenta pegar o primeiro da fila e o atende # caso nao haja ninguem na fila passa direto try: primeiro_fila = self.fila.retira() caixa.atende(primeiro_fila, contador) except: pass contador += 1 return {"maximos" : calcula_max(self.clients), "medias": calcula_medias(self.clients)}
abddc8bee465cf39473fac798d31bb5ece93bc94
markabdullah/Schoolwork
/csc148/assignments/a1/bikeshare.py
5,388
3.8125
4
"""Assignment 1 - Bike-share objects === CSC148 Fall 2017 === Diane Horton and David Liu Department of Computer Science, University of Toronto === Module Description === This file contains the Station and Ride classes, which store the data for the objects in this simulation. There is also an abstract Drawable class that is the superclass for both Station and Ride. It enables the simulation to visualize these objects in a graphical window. """ from datetime import datetime from typing import Tuple # Sprite files STATION_SPRITE = 'stationsprite.png' RIDE_SPRITE = 'bikesprite.png' class Drawable: """A base class for objects that the graphical renderer can be drawn. === Public Attributes === sprite: The filename of the image to be drawn for this object. """ sprite: str def __init__(self, sprite_file: str) -> None: """Initialize this drawable object with the given sprite file. """ self.sprite = sprite_file def get_position(self, time: datetime) -> Tuple[float, float]: """Return the (long, lat) position of this object at the given time. """ raise NotImplementedError class Station(Drawable): """A Bixi station. === Public Attributes === location: the location of the station in lat/long coordinates capacity: the total number of bikes the station can store num_bikes: int current number of bikes at the station name: str name of the station rides_started: int number of rides that started at this station rides_ended: int number of rides that ended at this station low_availability: datetime total ammount of time in seconds this station spent with at most 5 bikes low_unoccupied: datetime total ammount of time in seconds this station spend with at most 5 unoccupied spots === Representation Invariants === - 0 <= num_bikes <= capacity - rides_started >= 0 - rides_ended >= 0 """ location: Tuple[float, float] capacity: int num_bikes: int name: str rides_started: int rides_ended: int low_availability: int low_unoccupied: int def __init__(self, pos: Tuple[float, float], cap: int, num_bikes: int, name: str) -> None: """Initialize a new station. Precondition: 0 <= num_bikes <= cap """ super(Station, self).__init__(STATION_SPRITE) self.location = pos self.capacity = cap self.num_bikes = num_bikes self.name = name self.rides_started = 0 self.rides_ended = 0 self.low_availability = 0 self.low_unoccupied = 0 def get_position(self, time: datetime) -> Tuple[float, float]: """Return the (long, lat) position of this station for the given time. Note that the station's location does *not* change over time. The <time> parameter is included only because we should not change the header of an overridden method. """ return (self.location[0], self.location[1]) class Ride(Drawable): """A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time """ start: Station end: Station start_time: datetime end_time: datetime def __init__(self, start: Station, end: Station, times: Tuple[datetime, datetime]) -> None: """Initialize a ride object with the given start and end information. """ super(Ride, self).__init__(RIDE_SPRITE) self.start, self.end = start, end self.start_time, self.end_time = times[0], times[1] def get_position(self, time: datetime) -> Tuple[float, float]: """Return the (long, lat) position of this ride for the given time. A ride travels in a straight line between its start and end stations at a constant speed. === Preconditions === self.start_time <= time <= self.end_time """ # Number of mins the ride takes and mins past since the ride started ride_mins = (self.end_time - self.start_time).total_seconds() / 60 mins_past = (time - self.start_time).total_seconds() / 60 # Calculating the distance traveled in long/lat per minute diff_long = (self.end.location[0] - self.start.location[0]) / ride_mins diff_lat = (self.end.location[1] - self.start.location[1]) / ride_mins # Calculating current long/lat as start position plus the distance # traveled for each minute past the start time current_long = self.start.location[0] + diff_long * mins_past current_lat = self.start.location[1] + diff_lat * mins_past return (current_long, current_lat) if __name__ == '__main__': import python_ta python_ta.check_all(config={ 'allowed-import-modules': [ 'doctest', 'python_ta', 'typing', 'datetime'], 'max-attributes': 15 })
3e3fa441e4dc87130e1212531441ef45359ed0d4
rafaelribeiroo/scripts_py
/+100 exercícios com enunciados/RANDOM/Combustível.py
320
3.609375
4
print('Você pretende colocar quanto de combustível? ') c = float(input('R$ ')) print('Qual o tipo? ') t = str(input('> ')) print('Quanto está o lt. do {}?'.format(t)) p = float(input('R$ ')) lt = float(input('Seu automóvel faz quantos km/h com 1lt? ')) print('Você pagará R${} pelo {} que está a R${}, ')
7c7b5b7e47a75199291c8a6e7da227df23f686c8
remoteworkerstory/modularisasi
/modularisasi_tahap_1.py
641
3.890625
4
""" Program meghitung luas segitiga luas_segitiga = alas * tinggi /2 """ alas = 10 tinggi = 6 luas_segitiga = alas * tinggi /2 print(f'Segitiga dengan alas = {alas}, tinggi = {tinggi} \nmemiliki luas = {luas_segitiga}') def hitung_luas_segitiga(alas, tinggi): luas_segitiga = alas * tinggi / 2 return luas_segitiga print(f' menghitung segitiga dengan fungsi {hitung_luas_segitiga(10, 6)}') print(f' menghitung segitiga dengan fungsi {hitung_luas_segitiga(20, 16)}') print('alas = ') alas = input() print('tinggi = ') tinggi = input() print(f'Segitiga dengan alas = {alas}, tinggi = {tinggi} \nmemiliki luas = {luas_segitiga}')
fd369513c8623643803d280765c089d0cd03a2e9
sharkwhite21/Desarrollo_web
/POO/Polimor.py
1,349
3.890625
4
class Numero: value = 0 def __init__(self,value): self.value= value def compare(self,numero): if numero.value > self.value: return numero.value return self.value class Cadena: value = "" def __init__(self,value): self.value= value def compare(self,cadena): palabras=[self.value,cadena.value] palabras.sort() return palabras[0] class Lista: value = [] def __init__(self,value): self.value= value def compare(self,lista): if len(self.value) > len(lista.value): return self.value return lista.value def retornElMayor(a,b): return a.compare(b) num1 = Numero(100) num2 = Numero(12) cad1 = Cadena("Marlon") cad2 = Cadena("Andrea") list1 = Lista([1,2,3]) list2 = Lista([1,2,3,4,5]) print(retornElMayor(num1,num2)) print(retornElMayor(cad1,cad2)) print(retornElMayor(list1,list2)) """ def retornElMayor(a,b): if isinstance(a,int) and isinstance(b,int): if a > b: return a return b if isinstance(a,str) and isinstance(b,str): palabras=[a,b] palabras.sort() return palabras[0] if isinstance(a,list) and isinstance(b,list): if len(a) > len(b): return a return b print(retornElMayor("Marlon","Andrea")) """
e5dc30ca7319db68aafc3d6d057e9b237a08381a
shalakatakale/Python_leetcode
/Leet_Code/100SameTree.py
2,241
3.859375
4
'''#100 Same Tree - Tree, Depth first search, recursion Time complexity : O(N), where N is a number of nodes in the tree, since one visits each node exactly once. Space complexity : O(log(N)) in the best case of completely balanced tree and O(N) in the worst case of completely unbalanced tree, to keep a recursion stack.''' """ :type p: TreeNode :type q: TreeNode :rtype: bool """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isSameTree(self, p, q): # here p and q are two trees, we see if they are same if not p and not q: # if p and q both are NULL return True if not p or not q: # if one of p and q is NULL return False if p.val != q.val: return False # recursion below return self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left) ## Try to understand below from collections import deque class Solution: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ def check(p, q): # if both are None if not p and not q: return True # one of p and q is None if not q or not p: return False if p.val != q.val: return False return True deq = deque([(p, q), ]) while deq: p, q = deq.popleft() if not check(p, q): return False if p: deq.append((p.left, q.left)) deq.append((p.right, q.right)) return True # understand below solution class Solution: def isSameTree(self, p, q): stack = [(p, q)] while stack: (p, q) = stack.pop() if p and q and p.val == q.val: stack.extend([ (p.left, q.left), (p.right, q.right) ]) elif p or q: return False return True
f382bfeb2217fe37a03fb4786032849c6e335cc9
gu9/Python-data-Structures
/Hash_tables/hash_table.py
1,478
4.3125
4
# Standard implementation of Hash table in Python hash_table = [[] for _ in range(10)] print (hash_table) def delete(hash_table, key): """ Deleting elements from hash table :param hash_table: Given hash table :param key: input by user :return: None """ hash_key = hash(key) % len(hash_table) key_exists = False bucket = hash_table[hash_key] for i, kv in enumerate(bucket): k, v = kv if key == k: key_exists = True break if key_exists: del bucket[i] print ('Key {} deleted'.format(key)) else: print ('Key {} not found'.format(key)) def insert(hash_table, key, value): """ This function takes user input and assign a bucket to it using Chaining :param hash_table: :param key: :param value: :return: """ hash_key = hash(key) % len(hash_table) key_exists = False bucket = hash_table[hash_key] for i, kv in enumerate(bucket): k, v = kv if key == k: key_exists = True break if key_exists: bucket[i] = ((key, value)) else: bucket.append((key, value)) insert(hash_table, 10, 'Nepal') insert(hash_table, 25, 'USA') insert(hash_table, 20, 'India') insert(hash_table, 11, 'Nepal') insert(hash_table, 253, 'USA') insert(hash_table, 220, 'India') insert(hash_table, 120, 'Nepal') insert(hash_table, 225, 'USA') insert(hash_table, 250, 'India') print (hash_table)
15a672e87c3223f7951a5cd9ec88db294d251b43
CaptainChuenthavorn/DATA-STRUCTURE-AND-AlGORITHM
/recursive.py
707
3.9375
4
''' เป็นการ backtrack วิธีสร้าง 1.ต้องมีพารามิเตอร์ 2.recursive call โดยเปลี่ยน parameter 3.ต้องมี base case / simple case ''' def Fac(n): #n>=0 Fac(n-1)*n def EatUp(n): if n>1: EatUp(n-1) print('eat1') #n<=1 elif n==1: #base case print('eatq') #base case : n<=0: do nothing def binarySearch(low,high,x): if high< low: return -1 mid = (low+high)/2 if x==a[mid]: return mid elif a[mid]<x: return binarySearch(mid+1,high,x)#recursive else: return binarySearch(low,mid-1,x) #EatUp(8)
9d0df74309ff1166cee00f435cbd05c0dfd22ef1
shivansh-max/Algos
/Random/correctly_closed.py
1,143
3.96875
4
import sys finding = input("ENTER STRING >>>") finding_list = list(finding) def DOIT(list): # dictionary = {"OPEN" : "", "INDEX" : 0} a = [] IMPORTANTLIST = ["(", "{", "["] for i in range(len(list)): if list[i] == IMPORTANTLIST[0] or list[i] == IMPORTANTLIST[1] or list[i] == IMPORTANTLIST[2]: print(list[i]) a.append(list[i]) elif list[i] == ")": if a[len(a) - 1] == "]" or a[len(a) - 1] == "}": return False else: a.pop(len(a) - 1) elif list[i] == "]": if a[len(a) - 1] == ")" or a[len(a) - 1] == "}": return False else: a.pop(len(a) - 1) elif list[i] == "}": if a[len(a) - 1] == "]" or a[len(a) - 1] == ")": return False else: a.pop(len(a) - 1) if len(a) > 0: return False else: return True # return dictionary if DOIT(finding_list): print(f"THIS STRING : {finding}; IS CORRECTLY CLOSED.") else: print(f"THIS STRING : {finding}; IS NOT CORRECTLY CLOSED")
c71df463472b5514b7b85e8e23eb3443ce3d8399
NikDestrave/Python_Algos_Homework
/Lesson_2.3.1.py
804
4.4375
4
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. Подсказка: Используйте арифм операции для формирования числа, обратного введенному Пример: Введите число: 123 Перевернутое число: 321 ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ """ NUMBER = int(input('Введите число: ')) RESULT = 0 while NUMBER > 0: RESULT = RESULT * 10 + NUMBER % 10 NUMBER = NUMBER // 10 print(f'Перевернутое число: {RESULT}')
94f048c1e55b8573ee7e5c6a4f8bc1d72532478d
b21228797/gravity-calculator
/quiz1.py
323
3.921875
4
#write throught to code input values print("welcome to the gravity calculatios:") FT=float(input("Please enter the following time:")) GV=float(input("please enter the gravity constant:")) İV=0 // A=GV*FT*FT //multply operations B=İV*FT+İP output = float((A/2)+B) print("The final position :",output)
93e98223ebbd75bcd494720a59321cfb0206a356
chrissmart/python_tutorial_basic_part
/football_data_preprocess.py
997
3.8125
4
""" This py file introduces the basic manipulation of data """ """ import data """ import pandas as pd df_match = pd.read_csv(r"C:\Users\chris\Desktop\StatisticsAIDevp\techFun\WorldCupPlayers.csv\WorldCupMatches.csv") df_match.info() df_match.head() # As a coach, what kind of information you would like to know more so that you can help your team? """ data preprocess """ df_match_target = df_match[(df_match['Home Team Name'] == 'Spain') | (df_match['Away Team Name'] == 'Spain')].reset_index(drop=True) df_match_target = df_match[(df_match['Home Team Name'] == 'Spain')].reset_index(drop=True) df_match_target.tail() """ calculate data """ # + operator df_match_target['Home Team Goals'].iloc[-1] + df_match_target['Away Team Goals'].iloc[-1] # - operator df_match_target['Home Team Goals'].iloc[-1] - df_match_target['Away Team Goals'].iloc[-1] # * operator # / operator # % operator # placeholder slogan = "The best team in the world in %d is %s !" print(slogan%(2018, "Spanin"))
65f4f61d8c87d6188a827975976f6719070111c2
KanuKim97/Python_Tutorial
/14_List.py
638
4.09375
4
# List [] subway = [10, 20, 30] print(subway) subway = ["mike", "mike2", "mike3"] print(subway) print(subway.index("mike3")) # Add factor at List subway.append("mike4") print(subway) # Insert factor at List subway.insert(1, "chris") print(subway) # Pop factor at List subway.pop() print(subway) # Count same factor subway.append("mike") print(subway) print(subway.count("mike")) # Sort List_num = [1, 3, 2, 5, 7] List_num.sort() print(List_num) # Reverse List Factor List_num.reverse() print(List_num) # Remove All List_num.clear() print(List_num) # Extend List List_Upper = ["A", "B"] subway.extend(List_Upper) print(subway)
e8c36a8bc8c9d7b02684f532a62a1b70424ce124
sandeepmishramca/python
/examples/examples.py
5,157
4
4
#These examples based on https://www.practicepython.org/ exercise import random import json def exercise1(name,age): return name ,' will be 100 year in ',(2017-int(age))+100 def exercise4(num): return [x for x in range(1,num) if num%x==0] def exercise5(l1,l2): """comman=[] for e in l2: if e not in l1: comman.append(e) return comman""" #list comprihension return [x for x in l2 if x not in l1] def exercise8(): while True: ans = raw_input("new or quit") num = random.randint(1, 100) print num if 'quit' == ans: break else: nextnum=int(raw_input("what will be next number ")) if nextnum==num: print 'Congratulation your number is, ',num else: print ' the Correct num is ', num def exercise15(l): token=l.split() #print token[::-1] return ' '.join(token[::-1]) def number_compare(numh,guess): cowbull=[0,0] if numh==guess: cowbull[0]+=1 else: cowbull[1]+=1 return cowbull #print number_compare(1234,1234) #l='this is my guide ' #print exercise15(l) """a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print exercise5(a,b) """ def get_names(): input = "D:\data\\names.txt" with open(input,'r') as names: name_list=names.read().strip().split('\n') d={x:name_list.count(x) for x in name_list} return d def get_category_count(): path="D:\data\images.txt" path1 = "D:\\data\\result_images.txt" with open(path,'r') as f: image_list=f.read().strip().split('/') result=[x for x in image_list if len(x)>1 ] d={x:result.count(x) for x in result if result.count(x)>1} with open(path1,'w') as wfile: wfile.write(json.dumps(d)) #print wfile return d def happy_prime_numbers(): path ="D:\\data\\happy_number.txt" path1="D:\\data\\prime_number.txt" with open(path1,'r') as happy: happy_list=happy.read().strip().split('\n') with open(path1,'r') as prime: prime_list=prime.read().strip().split('\n') overlaplist =[int(x) for x in prime_list if x in happy_list] return overlaplist def max(*args): max=args[0] for n in args: if max<n: max=n return max #print max(34,2,56,9) def picks_random_word(): path="D:\data\words.txt" with open(path,'r') as f: word_list=f.read().strip().split('\n') word=random.choice(word_list) return word #print picks_random_word() def guess_word(): word='EVAPORATE' guessed='_'*len(word) word=list(word) guessed=list(guessed) gussed_list=[] letter = raw_input("guess word") while True: if letter.upper() in gussed_list: letter='' print "Already guessed" elif letter.upper() in word: index=word.index(letter.upper()) guessed[index]=letter.upper() word[index]='_' else: print ''.join(gussed_list) if letter.upper() is not '': gussed_list.append(letter.upper()) letter=raw_input("guess word") if '_' not in guessed: print 'you won!!!' break def add_birthday(): print "welcome to birthday dictinory!" path ="D:\\data\\birthday.json" with open(path,'r') as f: birthdays=json.load(f) # print birthdays['name'] for name in birthdays: print name print 'Type "add" to add another birthday. Type "exit" to quit' while True: print 'who\'s birthday do you want to look up' name=raw_input() if name=='exit': break elif name=='add': new_name=raw_input('Enter Name') new_dob=raw_input('Enter DOB') birthdays[new_name]=new_dob with open(path,'w') as w: json.dump(birthdays,w) elif name in birthdays: print '{}\'s birthday is {}'.format(name,birthdays[name]) else: print 'sorry we don\'t have {} birthday '.format(name) #add_birthday() def read_json(): path="D:\data\sample.json" with open(path,'r') as f: jobj=json.load(f) print jobj['om_points'] print jobj['maps'][0]['iscategorical'] print jobj['maps'][1]['id'] name='sandeep' bir='2018-02-05' jobj[name]=bir with open(path,'w') as fw: json.dump(jobj,fw) #read_json() from collections import Counter def read_dob(): month=[] num_to_string = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } path="D:\\data\\birthday.json" with open(path,'r') as j: d=json.load(j) for name,dob in d.items(): month.append(num_to_string[int(dob.split('-')[1])]) print Counter(month) #read_dob()
252735eb8e2c76b9442cd045eac3c9a73d05966e
gabriellaec/desoft-analise-exercicios
/backup/user_214/ch84_2019_04_02_20_09_55_305092.py
124
3.625
4
def inverte_dicionario(lista1): lista2={} for a in lista1: x=lista1[a] lista2[x]=a return lista2
4f238537c6e2c52bd639778c7c6ee6e66f76543b
carloslvm/learning-python
/book_exercise/crash/Chapter 8: Functions/unchanged_magicians.py
926
3.859375
4
#!/usr/bin/python3 def magicians_original(magicians): print("\nThis is the original list of magicians:") for magician in magicians: print("\t" + magician.title()) def make_great(copy_magicians): while copy_magicians: making_magicians_great = copy_magicians.pop() print("Upgrading: ", making_magicians_great.title()) magicians_great.append(making_magicians_great) def great_magicians(magicians_great): print('\nThe following magicians have been upgraded:') for magician_great in magicians_great: print("\tThe Great " + magician_great) #Original list available_magicians = [ 'himiko', 'diana', 'aurora', 'lyn', 'jion', 'sakura', ] magicians_great = [] #Copying the list copy = available_magicians[:] #Calling functions make_great(copy) great_magicians(magicians_great) #Printing the orignal list magicians_original(available_magicians)
38966a44ae90b8c273592c94b4da2da6e57286a1
shankar7791/MI-10-DevOps
/Personel/Sandesh/Python/23feb/calculate.py
241
3.84375
4
A = input("Enter the combination: ") wcount = 0 ncount = 0 ncount = sum(B.isdigit() for B in A) wcount = sum(B.isalpha() for B in A) print ("number of letters in the string is", wcount) print ("number of digits in the string is ", ncount)
660fb93af1502914880ede1cf5cf81da4d11c1ea
Seen3/Space-Jam-Amazon-Tracker
/Amazon_Tracker.py
4,475
3.5
4
# used to get the data from webpages when url is provided import requests # used to delay the code from time import sleep # Used to parse data provided by requests to extract the data required from bs4 import BeautifulSoup # miscellaneous functions that are repeated but simple from OtherFunctions.MiscFunctions import * # Import the sql functions that access database from OtherFunctions.SQL_Functions import Database from OtherFunctions.Send_Email import send_mail class AmazonTracker: # Constructor of the class it checks if the database file exists, and if it doesn't it creates one # and asks for user details and product urls def __init__(self, alert_confirmation, loop=True, debug=False): print('Accessing product data. If you are tracking many products this may take a while.') while KeyboardInterrupt: self.debug = debug params = db.access_product_params() self.name, self.to_addr, self.check_freq = db.access_user_data() self.check_freq = float(self.check_freq) for param in params: self.product_id = param[0] self.url = param[1] self.maxPrice = int(param[2]) self.connect() self.extract_data() if alert_confirmation: self.send_alert() print('\n\nAll products have been checked\n') if not loop: break print('Enter ctrl + c to exit code') sleep(self.check_freq * 60) # Stops the code process for 20 seconds # connects to the webpage provided using the url def connect(self): if self.debug: print("\n\nPlease wait. We are attempting to connect to the product page") # The headers are used to make the code imitate a browser and prevent amazon from block it access to the site. headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' '71.0.3578.98 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip', 'DNT': '1', # Do Not Track Request Header 'Connection': 'close' } # Get the code of the product page using the url provided self.response = requests.get(self.url, headers=headers) # code proceeds only if the connection to the product page is successful if self.response: if self.debug: print("Connected successfully\n\n") else: print("Connection failed") exit() # After the web page data is obtained the required data such as the product price is extracted. def extract_data(self): soup = BeautifulSoup(self.response.content, 'lxml') deal_price = None self.price = None # Extracting data from the amazon html code self.product_title = soup.find(id='productTitle').get_text().strip() availability = soup.find(id='availability').get_text().strip() # In stock. self.price = soup.find(id='price') # Exception handling is used to prevent the code from crashing if the required data is missing try: deal_price = int(soup.find(id='priceblock_dealprice').get_text().strip()[2:-3].replace(',', '')) except: pass try: self.price = int(soup.find(id='priceblock_ourprice').get_text().strip()[2:-3].replace(',', '')) except: pass print("\nProduct ID: ", self.product_id) print('\tProduct Title: ', self.product_title) print('\tAvailability: ', availability) # Print the data if it is found in the code if deal_price: print('\tDeal Price =', deal_price) if self.price: print('\tPrice = ', self.price) print('\tMax price set by user = ', self.maxPrice) # Send alert to the user if price falls below the max price set by the user. def send_alert(self): if self.price <= self.maxPrice: send_mail(self.to_addr, self.name, self.product_title, self.price, self.url) db = Database() if __name__ == '__main__': # The one is telling the constructor to enable user alerts. AmazonTracker(alert_confirmation=True)
f999b76fd43222d1b23aaee59825a38ea961d68e
caianne/mc102
/exercicios/Aula 10/Slide_31.py
268
3.75
4
#Slide 31 da Aula 10 lista=[] maior=0 for i in range(10): lista.append(int(input('Digite o valor para a posição '+str(i)+' da lista: '))) if lista[i]>maior: maior=lista[i] indice=i print('O índice do maior valor da lista é: '+str(indice))
17f1b3b879aa963fe49139c526d8ada58cd3d7ab
Sandra23U/strings_Python
/Jogo da Adivinhação.py
970
3.984375
4
from random import randint print('#### Iníciando Jogo ####') random = randint(0, 100) chute = 0; chances = 20; while chute != random: chute = input('Chute um número entre 0 a 100: ') if chute.isnumeric(): chute = int(chute) chances = chances - 1 if chute == random: print('') print('Parabéns, você venceu! O número era {} e você ainda tinha {} chances.'.format(random, chances)) print('') break; else: print('') if chute > random: print('Você errou!!! Dica: É um número menor.') else: print('Você errou!!! Dica: É um número maior.') print('Você ainda possui {} chances.'.format(chances)) print('') if chances == 0: print('') print('Suas chances acabaram, você perdeu!') print('') break; print('#### Fim do Jogo ####')
f9070bc47c9df347667edceb916ee10e3c80f27c
AnaErmakov/python
/hw_6_4.py
2,310
4.09375
4
class Car: def __init__(self, colour): self.speed = 0 self.colour = colour self.name = '' self.is_police = False def go(self, speed): self.speed = speed print(f'Машина {self.colour} {self.name} поехала со скоростью {speed}') def stop(self): self.speed = 0 print(f'Машина {self.name} остановилась') def turn(self, direction): print(f'Машина {self.name} повернула {direction}') def show_speed(self): print(f'Машина {self.name} едет со скоростью {self.speed}') class TownCar(Car): def __init__(self, colour): super().__init__(colour) self.name = 'Town car' def show_speed(self): super().show_speed() if self.speed > 60: print('Внимание! Превышение скорости!') class WorkCar(Car): def __init__(self, colour): super().__init__(colour) self.name = 'Work car' def show_speed(self): super().show_speed() if self.speed > 40: print('Внимание! Превышение скорости!') class PoliceCar(Car): def __init__(self, colour): super().__init__(colour) self.name = 'Police car' self.is_police = True class SportCar(Car): def __init__(self, colour): super().__init__(colour) self.name = 'Sport car' town_car = TownCar('red') town_car.go(50) town_car.turn('направо') town_car.show_speed() town_car.go(80) town_car.show_speed() town_car.stop() print(f"Это полицейская машина? {'Да' if town_car.is_police else 'Нет'}\n") police_car = PoliceCar('blue') police_car.go(80) police_car.speed = 50 police_car.show_speed() print(f"Это полицейская машина? {'Да' if police_car.is_police else 'Нет'}\n") sport_car = SportCar('black with white stripes') sport_car.go(80) sport_car.show_speed() sport_car.turn('around') sport_car.stop() print(f"Это полицейская машина? {'Да' if town_car.is_police else 'Нет'}\n") work_car = WorkCar('yellow') work_car.go(30) work_car.turn('налево') work_car.show_speed() work_car.go(50) work_car.show_speed() work_car.stop()
5826c6d384c286ff8eea9f74c0e2d27314caa6fb
andrewermel/curso-em-video
/37.py
230
3.875
4
#Escreva um programa que leia um numero inteiro qualquer e peça para o usuario escolher qual sera a base de conversão: #1 para binario # 2 para octal # 3 para hexadecimal #exercicio: num=int(input('digite um numero qualquer'))
5531858fafe39849b83522b60cedffa4b5f3104e
Matheus-Morais/Atividades_treino
/Python Brasil/Estrutura de Decisão/3.py
155
3.640625
4
sexo = input('Insira o seu sexo (F ou M):') if sexo == 'F': print('Feminino') if sexo == 'M': print('Masculino') else: print('Sexo Inválido')
df20f5be6cffcebc40d75f40e00f7f73183d70c2
ijoshi90/Python
/Python/unique_names_with_set.py
354
3.921875
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 20-12-2019 at 11:35 """ names1 = ["Ava", "Emma", "Olivia","Joshi","Sangeetha"] names2 = ["Olivia", "Sophia", "Emma","Akshay","Joshi"] def unique_names (names1, names2): return list(set(names1 + names2)) print(unique_names(names1, names2)) # should print Ava, Emma, Olivia, Sophia
a09244d3f24dea6c9689a0e5782e4dcf0416fe3b
iitwebdev/lectures_database_example
/2.sqlalchemy/2.metadata.py
4,862
3.765625
4
# ## title:: Schema and MetaData # The structure of a relational schema is represented in Python # using MetaData, Table, and other objects. from sqlalchemy import MetaData from sqlalchemy import Table, Column from sqlalchemy import Integer, String metadata = MetaData() user_table = Table('user', metadata, Column('id', Integer, primary_key=True), Column('name', String), Column('fullname', String) ) # Table provides a single point of information regarding # the structure of a table in a schema. user_table.name # The .c. attribute of Table is an associative array # of Column objects, keyed on name. user_table.c.name # It's a bit like a Python dictionary but not totally. print(user_table.c) # Column itself has information about each Column, such as # name and type user_table.c.name.name user_table.c.name.type # Table has other information available, such as the collection # of columns which comprise the table's primary key. user_table.primary_key # The Table object is at the core of the SQL expression # system - this is a quick preview of that. print(user_table.select()) # Table and MetaData objects can be used to generate a schema # in a database. from sqlalchemy import create_engine engine = create_engine("sqlite://") metadata.create_all(engine) # Types are represented using objects such as String, Integer, # DateTime. These objects can be specified as "class keywords", # or can be instantiated with arguments. from sqlalchemy import String, Numeric, DateTime, Enum fancy_table = Table('fancy', metadata, Column('key', String(50), primary_key=True), Column('timestamp', DateTime), Column('amount', Numeric(10, 2)), Column('type', Enum('a', 'b', 'c')) ) fancy_table.create(engine) # table metadata also allows for constraints and indexes. # ForeignKey is used to link one column to a remote primary # key. from sqlalchemy import ForeignKey addresses_table = Table('address', metadata, Column('id', Integer, primary_key=True), Column('email_address', String(100), nullable=False), Column('user_id', Integer, ForeignKey('user.id')) ) addresses_table.create(engine) # ForeignKey is a shortcut for ForeignKeyConstraint, # which should be used for composite references. from sqlalchemy import Unicode, UnicodeText, DateTime from sqlalchemy import ForeignKeyConstraint story_table = Table('story', metadata, Column('story_id', Integer, primary_key=True), Column('version_id', Integer, primary_key=True), Column('headline', Unicode(100), nullable=False), Column('body', UnicodeText) ) published_table = Table('published', metadata, Column('pub_id', Integer, primary_key=True), Column('pub_timestamp', DateTime, nullable=False), Column('story_id', Integer), Column('version_id', Integer), ForeignKeyConstraint( ['story_id', 'version_id'], ['story.story_id', 'story.version_id']) ) # create_all() by default checks for tables existing already metadata.create_all(engine) # ## title:: Exercises # 1. Write a Table construct corresponding to this CREATE TABLE # statement. # # CREATE TABLE network ( # network_id INTEGER PRIMARY KEY, # name VARCHAR(100) NOT NULL, # created_at DATETIME NOT NULL, # owner_id INTEGER, # FOREIGN KEY owner_id REFERENCES user(id) # ) # # 2. Then emit metadata.create_all(), which will # emit CREATE TABLE for this table (it will skip # those that already exist). # # The necessary types are imported here: # ## title:: Reflection # 'reflection' refers to loading Table objects based on # reading from an existing database. metadata2 = MetaData() user_reflected = Table('user', metadata2, autoload=True, autoload_with=engine) print(user_reflected.c) # Information about a database at a more specific level is available # using the Inspector object. from sqlalchemy import inspect inspector = inspect(engine) # the inspector provides things like table names: inspector.get_table_names() # column information inspector.get_columns('address') # constraints inspector.get_foreign_keys('address') # ## title:: Exercises # # 1. Using 'metadata2', reflect the "network" table in the same way # we just did 'user', then display the columns (or bonus, display # just the column names) # # 2. Using "inspector", print a list of all table names that # include a column called "story_id" #
6f9f419ae12a8c9b10322db218e032352ea06c96
saurabh-kadian/Euler
/solutions/pe117.py
964
3.734375
4
red = 2;green = 3;blue = 4;black = 1;units = 50;fact = [];number = 1 fact.append(1) for i in range(1,units+1): number = number*i fact.append(number) red = int(units/red) green = int(units/green) blue = int(units/blue) ways = 0 for redWalle in range(0,red+1): for greenWalle in range(0,green+1): if (2*redWalle)+(3*greenWalle) > units: continue for blueWalle in range(0,blue+1): if (2*redWalle)+(3*greenWalle)+(4*blueWalle) > units: continue blackWalle = units-(2*redWalle)-(3*greenWalle)-(4*blueWalle) num = fact[blackWalle+redWalle+greenWalle+blueWalle] num /= fact[blackWalle] num /= fact[redWalle] num /= fact[blueWalle] num /= fact[greenWalle] ways += num print("Black : " + str(blackWalle) + " Red : " + str(redWalle) + " Green : " + str(greenWalle) + " Blue : " + str(blueWalle) ) print(ways)
3df1e0a941d170fe9b7d86fde15fef49ed8bc835
emilianoNM/Tecnicas3
/Reposiciones/Cuevas Cuauhtle Luis Fernando/Reposicion 07_09_2018/PalabraRepetida.py
411
4.03125
4
#Programa para identificar si existe una palabra repetida def PalabraRepetida(str1): temp = set() for Palabra in str1.split(): if Palabra in temp: return Palabra; else: temp.add(Palabra) return 'No hay palabra repetida' print(PalabraRepetida("ab ca bc ab")) print(PalabraRepetida("ab ca bc ab ca ab bc")) print(PalabraRepetida("ab ca bc ca ab bc")) print(PalabraRepetida("ab ca bc"))
329f7a3ba10789f2d3b0a7693e5ac59ec32eb98e
Shred13/Temporal-Difference-Learning
/main.py
1,695
3.78125
4
""" Date: October 25th 2020 Authors: Shreyansh Anand, Anne Liu CISC 453/474 Assignment 2 """ from part_1_of_assignment import Grid from part_2_of_assignment import algorithm_with_anchor, algorithm_without_anchor, rock_paper_scissors_unanchored, rock_paper_scissors_with_anchor def main(): # testing of the Grid and Policy Design grid_with_5_75 = Grid(5, 0.75) print("Grid 5x5 with 0.75 Discount") grid_with_5_75.grid_iterations() grid_with_5_75.draw_policy() grid_with_7_75 = Grid(7, 0.75) print("Grid 7x7 with 0.75 Discount") grid_with_7_75.grid_iterations() grid_with_7_75.draw_policy() grid_with_5_85 = Grid(5, 0.85) print("Grid 5x5 with 0.85 Discount") grid_with_5_85.grid_iterations() grid_with_5_85.draw_policy() grid_with_7_85 = Grid(7, 0.85) print("Grid 7x7 with 0.85 Discount") grid_with_7_85.grid_iterations() grid_with_7_85.draw_policy() print("PRISONERS") algorithm_without_anchor([0.5, 0.5], [0.5, 0.5], [[5, 0], [10, 1]], [[5, 10], [0, 1]], 300000, "Prisoners Dilemma") print("\n\n\nPennies without anchor") algorithm_without_anchor([0.2, 0.8],[0.2, 0.8], [[1, -1], [-1, 1]], [[-1, 1], [1, -1]], 200000, "Pennies without " "anchor") print("\n\n\nPennies with anchor") algorithm_with_anchor([0.2, 0.8], [[1, -1], [-1, 1]], [[-1, 1], [1, -1]], 5000000, "Pennies with anchor") print("\n\n\nRock paper scissors with anchor") rock_paper_scissors_with_anchor() print("\n\n\nRock paper scissors without anchor") rock_paper_scissors_unanchored() if __name__ == '__main__': main()
45d09f467967816fef7bd42c55a17ee9ef53e38b
sabapathy1234/P.saba
/saba97.py
90
3.609375
4
s1=input() p=[] for i in s1: if(i.isnumeric()): p.append(i) print(''.join(p))
db59754a3c9b26b721f5b017b0756eb84f086314
David92p/Python-workbook
/function/Exercise95.py
969
4.15625
4
#Capitalize It def capitalize(string): string = string.lower() my_list = list(string) new_string = "" if my_list[0] == my_list[0].lower(): my_list[0] = my_list[0].upper() for i in range(len(my_list)): if my_list[i] is not my_list[len(my_list)-1] and (my_list[i] == "." or my_list[i] == "?" or my_list[i] == "!"): if my_list[i+1] == " ": my_list[i+2] = my_list[i+2].upper() else: my_list[i+1].upper() if my_list[i] == "i": if my_list[i-1] == " " and my_list[i+1] == " ": my_list[i] = "I" elif my_list[i-1] == " " and my_list[i+1] == "'" or my_list[i+1] == "?" or my_list[i+1] == "!" or my_list[i+1] == ".": my_list[i] = "I" new_string = new_string.join(my_list) print(new_string) def main(): string = input("Enter your string ") capitalize(string) if __name__== "__main__": main()
9d83099cb8c9b4aadae928fa4a10cd6c3ef71529
ideaqiwang/leetcode
/DynamicProgramming/131_PalindromePartitioning.py
1,121
3.90625
4
''' 131. Palindrome Partitioning Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward. Example 1: Input: s = "aab" Output: [["a","a","b"],["aa","b"]] Example 2: Input: s = "a" Output: [["a"]] ''' class Solution: def partition(self, s: str) -> List[List[str]]: return self.dfs(s, {}) def dfs(self, s, memo): if not s: return [] if s in memo: return memo[s] partitions = [] for i in range(1, len(s)+1): prefix = s[:i] if not self.isPalindrome(prefix): continue subPartitions = self.dfs(s[i:], memo) for partition in subPartitions: partitions.append([prefix] + partition) if self.isPalindrome(s): partitions.append([s]) memo[s] = partitions return partitions def isPalindrome(self, s): return s == s[::-1]
2930412fd06374f64570f98f3258b8ad7b97827f
alstndhffla/PythonAlgorithm_Practice
/basic/right_triangle.py
357
3.703125
4
# 오른쪽 직각 이등변 삼각형 * 로 출력. n = int(input('짧은 변의 길이를 입력:')) # i 는 0부터 시작됨 for i in range(n): # 행 루프 for _ in range(n - i - 1): # 열 루프(공백 출력) print(' ', end='') for _ in range(i + 1): print('*', end='') # 열 루프(* 출력) print()
752b9e78d32a5b30bec8a698b56414a1ecc7353a
archu2020/python-2
/old/test2.py
173
3.71875
4
import time print("start") start_time = time.time() temp = 0 for i in range(10000000): temp += i print(temp) end_time = time.time() print(end_time - start_time)
b554bad6bea78b85325ea4a30f7b367166440653
ryanmp/project_euler
/p019.py
1,093
4.125
4
''' You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' from datetime import date, timedelta # let's just use datetime... def main(): start_dt = date(1901, 1, 1) end_dt = date(2001, 1, 1) sundays = 0 for single_date in daterange(start_dt, end_dt): if single_date.weekday() == 6: sundays += 1 return sundays def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r)
2e859087119d3251b6ce4c3739c6c5d4649505b8
litojasonaprilio/CP1404-Practicals
/prac_02/random_numbers.py
481
3.578125
4
import random print(random.randint(5, 20)) # line 1 print(random.randrange(3, 10, 2)) # line 2 print(random.uniform(2.5, 5.5)) # line 3 # 1 The smallest number in line 1 that I could have seen is 5 and the largest is 19 # 2 The smallest number in line 1 that I could have seen is 3 and the largest is 9 # 2 Line 2 could not have produced 4 # 3 The smallest number in line 1 that I could have seen is 2.50... (the last digit will not be 0) and the largest is 5.49...
7e04c4efda0eabc3480a4fc629199a6a35d5f811
dajosco/Trivia-Lumma
/Trivia_Game.py
6,430
3.609375
4
############################################################################################################## # LUMMA - TRIVIA # # Author: Daniel J. Scokin # Version: 1.00 # Date: May-2015 # Description of the Game: # - There are 2 teams # - A question is presented to both teams at the same time along with three different answers to choose from. # - A person in each team has to push one of the three push buttons, where each one belongs to an answer. # - If no answer is received in a lapse of 30sec. no points will be accredited to the team. # - Each team is credited with: # - 10 points per correct answer # - 5 extra points to the first to answer # - Wins the team with more points # ############################################################################################################# __author__ = 'dajosco' import random import os # Number of questions to be ask during the game Game_Questions = 3 # Each element contains the correct answer to each one of the questions in numerical order Question_Answer = [1, 1, 2, 3, 2, 1, 3, 1, 1, 2, 2, 3, 1, 2, 3] # Flag to avoid repeating questions Question_executed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ###################################################################################### # Choose Qustion # Randomly selectects a question and verifies that has not bein asked in the same game def Choose_Question(): current_question = 0 loop_count = 0 while True: current_question = random.randrange(0, len(Question_Answer)) loop_count += 1 if Question_executed[current_question] == 0: break if loop_count > (Game_Questions + 1): print("Something went wrong! Stuck inside subrutine: %s %d times" % ('Choose_Question', loop_count)) break Question_executed[current_question] = 1 return current_question ###################################################################################### # Initialize Question Table # Sets all the question executed flags to 0 def Initialize_Qestion_table(): for x in range(0, len(Question_Answer)): Question_executed[x] = 0 ###################################################################################### # Main # Main subrutine def main(): Team1_Score = 0 Team2_Score = 0 current_question = -1 # Stores the question being asked QuienJuega=0 #### for Simulation Team2_Table = {'q': 1, 'w': 2, 'e': 3} Initialize_Qestion_table() # clears all the flags print ("\033c") print ("\n \n \n Playing: Video 0: Invitacion a jugar equipo Rojo / Azul \n") QuienJuega = raw_input ("[A]zul o [R]ojo : ") if QuienJuega == 'A': print ("Playing: Video 1: invitacion a jugar Equipo Rojo - Tenemos a Azul \n") else: print ("Playing: Video 2: invitacion a jugar Equipo Azul - Tenemos a Rojo \n") QuienJuega = raw_input("[A]zul o [R]") print ("\nPlaying: Video 2b: VIDEO REGLAS... \n") # Ask 3 questions for x in range(1, Game_Questions + 1): current_question = Choose_Question() print("-----------------------------------------------------------\n" "Playing: Video %d\n" "Pregunta #%d codigo %d" % (x+8,x, current_question + 1)) #### TODO: replace simulation by actual inputs #### For Simulation, will be replaced with pushbuttons Teams_Answers = "" while len(Teams_Answers) < 2: Teams_Answers = raw_input("\nTeam 1 answers with (1,2,3)\nTeam 2 answers with (Q,W,E)\n") First_Answer = Teams_Answers[0] Second_Answer = Teams_Answers[1] # Findout who replayed first if First_Answer.isdigit(): First_Team_to_Answer = 1 Team1_Answer = int(First_Answer) Team2_Answer = Team2_Table[Second_Answer] else: First_Team_to_Answer = 2 Team1_Answer = int(Second_Answer) Team2_Answer = Team2_Table[First_Answer] #### End Simulation ###TODO: Real Inputs # There would be 2 groups of 3 inputs each # The code should detect the first input set on each group # and to take it as the desired answer for that team # - Identify which input on each group was activated first # - Identify which group was activated first # - Debouce # - If between the group no input is detected in 30sec, signal timeout. # - Once an option is pressed in a group it won't take in consideration the rest # initialize round scores Team1_Round_Score = 0 Team2_Round_Score = 0 # Calculate the scores for Team1 if Team1_Answer == Question_Answer[current_question]: Team1_Round_Score = 10 if First_Team_to_Answer == 1: Team1_Round_Score += 5 # Calculate the scores for Team2 if Team2_Answer == Question_Answer[current_question]: Team2_Round_Score = 10 if First_Team_to_Answer == 2: Team2_Round_Score += 5 # Set the winner if Team1_Round_Score > Team2_Round_Score: Round_Winner = 1 elif Team1_Round_Score < Team2_Round_Score: Round_Winner = 2 else: Round_Winner = 0 # Accumulate the total scores Team1_Score += Team1_Round_Score Team2_Score += Team2_Round_Score # Present the correct answer print('\Pregunta #%d Code %d - correct Answer: %d' % ( x, current_question + 1, Question_Answer[current_question])) # Present who was the winner if Round_Winner > 0: print("\nPlaying: Video %d: Equipo %d wins this round" % (Round_Winner+6,Round_Winner)) else: print("\nPlaying: Video 6: Respondieron ambos incorrectamente") # Present partial scores print('\nTeam 1 Score=%d points\nTeam 2 Score=%d points\n' % (Team1_Score, Team2_Score)) # End of the Game # Present the winner of the Game and the points print("=============================================================") if Team1_Score > Team2_Score: print(' TEAM 1 is the Winner!!! with %d over %d' % (Team1_Score, Team2_Score)) elif Team1_Score < Team2_Score: print(" TEAM 2 is the Winner!!! with %d over %d" % (Team2_Score, Team1_Score)) else: print(" It's a Tie!!! : Team 1 = %d points and Team 2 = %d points" % (Team1_Score, Team2_Score)) print("=============================================================") # Show the question tables print("\n") print(Question_Answer) print(Question_executed) if __name__ == "__main__": main()
4165dee9b5a061a15e258bbcec882f11c186ec97
Swapnil-ingle/Python-projects
/anagram.py
291
3.90625
4
import sys text=input('Enter your text:').lower() flag=True count=-1 for i in range(0,len(text)): if text[i]==text[count]: flag=True count-=1 else: flag=False print('Not Anagram!') sys.exit() if flag==True: print('String is Anagram')
06393ba19b49536562d5ea882915e7cb4839f26d
gracomot/Basic-Python-For-College-Students
/Lectures/Lesson 2/Reading Input From the Keyboard/input_demo2.py
286
4.21875
4
# Get the user's name, age and income name = input('What is your name? ') age = float(input('How old are you? ')) earning = float(input('What is your monthly earning? ')) # Display the data print('Name:',name) print('In five years, I will be :',age+5) print('Monthly Earning:',earning)
5c3a9e02080c7470deae8ff7b392316b5452b32a
junbock/pre-education
/quiz/pre_python_11.py
250
3.75
4
"""11. 최대공약수를 구하는 함수를 구현하시오 예시 <입력> print(gcd(12,6)) <출력> 6 """ def gcd(x, y): for i in range(min(x,y), 0, -1): if x%i == 0 and y%i == 0: return i return -1 print(gcd(12,6))
a68233d178692b71528c2c1dff4efecbcb5104b2
ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck
/problems/AE38.py
405
3.828125
4
# Invert Binary Tree # O(n) # n = numberOfNodes(tree) def invertBinaryTree(tree): if tree != None: temp = tree.left tree.left = tree.right tree.right = temp invertBinaryTree(tree.left) invertBinaryTree(tree.right) # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None
7c68dbdda1582cccc88f47634417f1a4abdb8914
Varadkar45/LetsUpgrade
/Python AUG 21/Assignment 2/ass2.py
326
3.6875
4
a = list(input("Enter a string: ")) for n, i in enumerate(a): if i not in a[:n] : print(f"{i} - {a.count(i)}" , end=",") print("") print("<--------------------------------------------------------->") st = input("Enter a Word: ") li = list(set(st)) for i in li: print(f"{i} - {st.count(i)}", end=",")
5578ff26e4b37e5974c914e60404f9a092b4ed20
aidanrfraser/CompSci106
/CountSinglesTiming.py
2,478
3.96875
4
from cisc106 import assertEqual def is_next_to(index, alist): """ Finds if a number is next to itself """ if not index == 0 and alist[index - 1] == alist[index]: return True elif not index >= len(alist) - 1 and alist[index + 1] == alist[index]: return True else: return False assertEqual(is_next_to(1, [1, 2, 3]), False) assertEqual(is_next_to(1, [1, 1, 5]), True) assertEqual(is_next_to(1, [2, 2, 1]), True) def count_singlesA(key, alist): """ Counts numbers if they're not next to themselves with a range """ result = 0 for x in range(len(alist)): if alist[x] == key: if not is_next_to(x, alist): result += 1 return result assertEqual(count_singlesA(1, [1]), 1) assertEqual(count_singlesA(2, []), 0) assertEqual(count_singlesA(1, [1, 1]), 0) def count_singlesB(key, alist): """ Counts the appearances of key in alist if key is not next to itself using a state variable """ num = 0 result = 0 for element in alist: if num == 0 and element == key: result += 1 num = 1 elif num == 1 and element == key: result -= 1 num += 1 elif num > 1 and element == key: num += 1 elif element == key: num = 1 else: num = 0 return result assertEqual(count_singlesB(1, [1]), 1) assertEqual(count_singlesB(2, []), 0) assertEqual(count_singlesB(1, [1, 1]), 0) import timeit from matplotlib import pyplot import random key = random.randint(1, 1000) plotlist = list(range(1, 1001)) random.shuffle(plotlist) plotlist = plotlist[:(len(plotlist) // 2)] plotlist += [(500 * key)] random.shuffle(plotlist) range1 = range(100, 1001, 100) dependent = [] for num in range1: the_list = plotlist[:num] elapsed = timeit.timeit('count_singlesA(key, the_list)', number = 100, globals = globals()) dependent = dependent + [elapsed] pyplot.plot(range1, dependent, 'r', label = 'For Loop (A)') dependent = [] for num in range1: the_list = plotlist[:num] elapsed = timeit.timeit('count_singlesB(key, the_list)', number = 100, globals = globals()) dependent = dependent + [elapsed] pyplot.plot(range1, dependent, 'b', label = 'State Variable (B)') pyplot.title("Count Singles Timings") pyplot.ylabel("Time in Seconds") pyplot.xlabel("List Size") pyplot.legend() pyplot.savefig("lab07_10.png") pyplot.show()
b33cb711633e8d64b5f66d62214923cf2aebe8c1
Kakoytobarista/games-and-bots-on-python
/ping-pong.py
3,027
3.828125
4
import turtle from random import choice, randint window = turtle.Screen() window.title("Ping-Pong") window.setup(width=1.0, height=1.0) window.bgcolor("black") window.tracer(2) border = turtle.Turtle() border.speed(0) border.color('green') border.begin_fill() border.goto(-500, 300) border.goto(500, 300) border.goto(500, -300) border.goto(-500, -300) border.goto(-500, 300) border.end_fill() border.goto(0, 300) border.color('white') border.setheading(270) for i in range(25): if i % 2 == 0: border.forward(24) else: border.up() border.forward(24) border.down() border.hideturtle() rocket_a = turtle.Turtle() rocket_a.color('white') rocket_a.speed(1) rocket_a.shape('square') rocket_a.shapesize(stretch_len=1, stretch_wid=5) rocket_a.penup() rocket_a.goto(-450, 0) rocket_b = turtle.Turtle() rocket_b.speed(1) rocket_b.shape("square") rocket_b.color("white") rocket_b.shapesize(stretch_wid=5, stretch_len=1) rocket_b.penup() rocket_b.goto(450, 0) FONT = ('Arrial', 50) score_a = 0 s1 = turtle.Turtle(visible=False) s1.color('white') s1.penup() s1.setposition(-200, 300) s1.write(score_a, font=FONT) score_b = 0 s2 = turtle.Turtle(visible=False) s2.color('white') s2.penup() s2.setposition(200, 300) s2.write(score_a, font=FONT) def move_up(): y = rocket_a.ycor() + 30 if y > 250: y = 250 rocket_a.sety(y) def move_down(): y = rocket_a.ycor() - 30 if y < -250: y = -250 rocket_a.sety(y) def move_up_b(): y = rocket_b.ycor() + 30 if y > 250: y = 250 rocket_b.sety(y) def move_down_b(): y = rocket_b.ycor() - 30 if y < -250: y = -250 rocket_b.sety(y) ball = turtle.Turtle() ball.shape('circle') ball.speed(1) ball.color('red') ball.dx = 2 ball.dy = -2 ball.penup() window.listen() window.onkeypress(move_up, "w") window.onkeypress(move_down, "s") window.onkeypress(move_up_b, "Up") window.onkeypress(move_down_b, "Down") while True: window.update() ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) if ball.ycor() >= 290: ball.dy = -ball.dy if ball.ycor() <= -290: ball.dy = -ball.dy if ball.xcor() >= 490: score_b += 1 s2.clear() s2.write(score_b, font=FONT) ball.goto(0, randint(-150, 150)) ball.dx = choice([-4, -3, -2, 2, 3, 4]) ball.dy = choice([-4, -3, -2, 2, 3, 4]) if ball.xcor() <= -490: score_a += 1 s1.clear() s1.write(score_a, font=FONT) ball.goto(0, randint(-150, 150)) ball.dx = choice([-4, -3, -2, 2, 3, 4]) ball.dy = choice([-4, -3, -2, 2, 3, 4]) if rocket_b.ycor() - 50 <= ball.ycor() <= rocket_b.ycor() + 50 \ and rocket_b.xcor() - 5 <= ball.xcor() <= rocket_b.xcor() + 5: ball.dx = -ball.dx if rocket_a.ycor() - 50 <= ball.ycor() <= rocket_a.ycor() + 50 \ and rocket_a.xcor() - 5 <= ball.xcor() <= rocket_a.xcor() + 5: ball.dx = -ball.dx window.mainloop()
a43bad6c7124ca1c07beddfeff72b969d127c1bb
piotr-ek7/Learning_projects
/Jetbrains/tictactoe.py
8,073
3.796875
4
import random import math """ Tic-Tac_Toe game Menu: start user user or start level_ai level_ai (level_ai: easy medium hard) or start user level_ai (eg. start user medium) or start level_ai user or exit Matrix input: (1,3) (2,3) (3,3) (1,2) (2,2) (2,3) (1,1) (2,1) (3,1) """ def draw_game(array_to_draw): print("---------") for cell in range(len(array_to_draw)): print("|", " ".join(array_to_draw[cell]), "|") print("---------") def matrix_all_combinations(basic_matrix): diagonal_main = [basic_matrix[cell][cell] for cell in range(len(basic_matrix[0]))] diagnonal_anti = [basic_matrix[cell][2-cell] for cell in range(len(basic_matrix[0]))] matrix_vertical = [[row[cell] for row in basic_matrix] for cell in range(len(basic_matrix[0]))] return basic_matrix + matrix_vertical + [diagonal_main] + [diagnonal_anti] def convert_cells(outer_list, inner_list_id): if outer_list <= 3: col_pos = inner_list_id row_pos = 4 - outer_list else: row_pos = 4 - inner_list_id if 3 < outer_list < 7: col_pos = outer_list - 3 else: col_pos = inner_list_id if outer_list == 7 else row_pos return col_pos, row_pos def winning_combinations(matrix_to_check, number_xo=3): totalo = 0 totalx = 0 sublist_num = 0 row_id = None col_id = None for sublist in matrix_to_check: subx = sublist.count("X") subo = sublist.count("O") if number_xo == 2: # medium level sublist_num += 1 id_null = sublist.index(" ") + 1 if sublist.count(" ") > 0 else 0 col_id = convert_cells(sublist_num, id_null)[0] row_id = convert_cells(sublist_num, id_null)[1] if subx == number_xo and (subx + subo == number_xo): totalx = 25 break elif subo == number_xo and (subx + subo == number_xo): totalo = 25 break else: totalx += subx totalo += subo return totalx, totalo, row_id, col_id def find_best_move(matrix, mark): # hard level marks = ['X', 'O'] marks.remove(mark) opponent_mark = marks[0] best_move = -math.inf move_i = 0 move_j = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == " ": matrix[i][j] = mark score = mini_max(matrix, 0, False, mark, opponent_mark) matrix[i][j] = " " if score > best_move: best_move = score move_i = i move_j = j return convert_cells(move_i + 1, move_j + 1) def mini_max(matrix, depth, is_max, mark, opponent_mark): # hard level if mark == "X": score = winning_combinations(matrix_all_combinations(matrix))[0] score_opponent = -winning_combinations(matrix_all_combinations(matrix))[1] else: score = winning_combinations(matrix_all_combinations(matrix))[1] score_opponent = -winning_combinations(matrix_all_combinations(matrix))[0] if score == 25: return score if score_opponent == -25: return score_opponent if score + score_opponent == 24: return 0 if is_max: best_score = -math.inf for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == " ": matrix[i][j] = mark best_score = max(best_score, mini_max(matrix, depth + 1, False, mark, opponent_mark)) matrix[i][j] = " " return best_score else: best_score = math.inf for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == " ": matrix[i][j] = opponent_mark best_score = min(best_score, mini_max(matrix, depth + 1, True, mark, opponent_mark)) matrix[i][j] = " " return best_score def game_implementation(matrix, col, row, who_play): matrix_transposed = [[row[cell] for row in reversed(matrix)] for cell in range(len(matrix[0]))] count_x = [cell for row in matrix_transposed for cell in row].count("X") count_o = [cell for row in matrix_transposed for cell in row].count("O") if count_x <= count_o: x_or_o = "X" else: x_or_o = "O" if who_play in ["easy", "medium", "hard"]: print('Making move level "{}"'.format(who_play)) if who_play == "medium" and (winning_combinations(matrix_all_combinations(matrix), 2)[0] == 25 or winning_combinations(matrix_all_combinations(matrix), 2)[1] == 25): col = winning_combinations(matrix_all_combinations(matrix), 2)[3] row = winning_combinations(matrix_all_combinations(matrix), 2)[2] elif who_play == "hard": if count_x != 0: col = find_best_move(matrix, x_or_o)[0] row = find_best_move(matrix, x_or_o)[1] else: while matrix_transposed[col - 1][row - 1] != " ": col = random.randint(1, 3) row = random.randint(1, 3) if matrix_transposed[int(col) - 1][int(row) - 1] == " ": matrix_transposed[int(col) - 1][int(row) - 1] = x_or_o matrix_reverted = [[row[cell] for row in matrix_transposed] for cell in range(len(matrix_transposed[0]))] matrix_to_draw = [matrix_reverted[2], matrix_reverted[1], matrix_reverted[0]] draw_game(matrix_to_draw) matrix_final = matrix_all_combinations(matrix_to_draw) if winning_combinations(matrix_final)[0] == 25: print("X wins") elif winning_combinations(matrix_final)[1] == 25: print("O wins") elif winning_combinations(matrix_final)[0] + winning_combinations(matrix_final)[1] < 24: # 9 horizontal cells + 9 vertical cells+ 6 cells on digonals return matrix_to_draw else: print("Draw") return False else: print("This cell is occupied! Choose another one!") return matrix while True: input_command = input("Input command: ").split() if (input_command[0] == "start" and input_command[1] in ["user", "easy", "medium", "hard"] and input_command[2] in ["user", "easy", "medium", "hard"] and len(input_command) == 3): initial_cells = list("_________".replace("_", " ")) cells_matrix = [initial_cells[i: i + 3] for i in range(0, len(initial_cells), 3)] if input_command[0] == "start": draw_game(cells_matrix) start_game = True else: start_game = False while start_game: for player in input_command[1:]: try: if player == "user" and cells_matrix is not False: cor1, cor2 = tuple(map(int, input("Enter the coordinates: ").split(" "))) else: cor1 = random.randint(1, 3) cor2 = random.randint(1, 3) if cor1 not in [1, 2, 3] or cor2 not in [1, 2, 3]: print("Coordinates should be from 1 to 3!") else: try: cells_matrix = game_implementation(cells_matrix, cor1, cor2, player) if cells_matrix is False: start_game = False except: continue except: print("You should enter numbers!") elif input_command[0].lower() == "exit": break else: print("Bad parameters!")
7cf9e5e807938cb35826f219c0df929411cca576
medesiv/ds_algo
/trees/bfs/max_width_bt.py
840
3.578125
4
#Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if root is None: return 0 q, result = [], [] q.append([root,1]) while len(q)>0: first = None last = None for _ in range(len(q)): (node,id) = q.pop(0) if node.left is not None: q.append([node.left, 2*id]) if node.right is not None: q.append([node.right, 2*id+1]) last = id if first is None: first = id result.append(last-first+1) return max(result)
eef6f23fb557a7d6a5484154fba55bb4487a78be
IlyaAleksandrov/Algorithms-and-Data-Structures
/1 Algorithms toolbox/1.2 Introduction/Tasks/fibonacci_huge/1.1 fibonacci.py
306
4.09375
4
# Task. Given an integer 𝑛, find the 𝑛th Fibonacci number 𝐹𝑛 def get_fibonacci(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current a = int(input()) print(get_fibonacci(a))
5a516722a12ef6671da82c7d7325bbb9a427f815
pearl0304/Python
/Python_Ch03/Q3_1.py
365
3.828125
4
weight=int(input("짐의 무게는 얼마입니까? : ")) if weight <10 : print("수수료가 없습니다") else : print("수수료는 10,000원입니다") weight=int(input("짐의 무게는 얼마입니까? : ")) if weight <10 : print("수수료가 없습니다") else : price=(weight//10)*10000 print("수수료는 %d원입니다"%(price))
faff0d5ace29c27576cecf845e8b0a28b1b74d68
shnoble59/sharegithub
/data_utils.py
2,571
4.3125
4
"""Utility functions for wrangling data.""" __author__ = "730136744" from csv import DictReader def read_csv_rows(csv_file: str) -> list[dict[str, str]]: """Read a CSV file's contents into a list of rows.""" rows: list[dict[str, str]] = [] file_handle = open(csv_file, "r", encoding="utf8") csv_reader = DictReader(file_handle) # 0.1) Complete the implementation of this function here. # add each row of data to our table for row in csv_reader: rows.append(row) # when we are done reading/ working with a file, close it! file_handle.close() print(rows) return rows def column_values(table: list[dict[str, str]], column: str) -> list[str]: """Produce a list[str] of all values in a single column whose name is the second parameter.""" column_build: list[str] = [] for row in table: column_build.append(str(row[column])) return column_build def columnar(table: list[dict[str, str]]) -> dict[str, list[str]]: """Transform a table represented as a list of rows into one represented as a dictionary of columns.""" new_table: dict[str, list[str]] = {} column_names = table[0].keys() for key in column_names: take = key new_table[f"{take}"] = list(column_values(table, take)) return new_table def head(data: dict[str, list[str]], num: int) -> dict[str, list[str]]: """Produce a new column-based table with only the first N rows of data for each column.""" dict_build: dict[str, list[str]] = {} for column in data: first_n: list[str] = [] x = 0 while x < num and x < len(data[column]): first_n.append(data[column][x]) x += 1 dict_build[column] = first_n return dict_build def select(data: dict[str, list[str]], copy: list[str]) -> dict[str, list[str]]: """Produce a new column-based table with only a specific subset of the original columns.""" chosen_dict: dict[str, list[str]] = {} for item in copy: for column in data: if column == item: chosen_dict[column] = data[column] return chosen_dict def count(values: list[str]) -> dict[str, int]: """Produce a dict where each key is a unique value in the given list and each value associated is the count.""" dict_build: dict[str, int] = {} for item in values: dict_build[item] = 0 for item in values: if item in dict_build: dict_build[item] = dict_build[item] + 1 else: dict_build[item] = 1 return dict_build
e89a79c08c851cb336f3ce9e17fe6b986f6c5125
htunctepe/8.hafta_odevler-Fonksiyonlar
/Week8Homeworks-Functions.py
9,317
4.28125
4
# ---------------------------------8. HAFTA ODEVLER - FONKSIYONLAR--------------------------------- # -------------1. ODEV - Asal Sayi mi?------------- def isPrimeNumber(number): isTrue = True # Only numbers greater than 1 can be prime numbers if number > 1: while isTrue: # See if the number is divisible by any other number than 1 and itself for i in range(2, number//2+1): if number % i == 0: print("\n{} is not a prime number.".format(number)) isTrue = False break elif i == 15: isTrue = False # If this else block is executed, that means any condition above is not met # so the number is a prime number else: print("\n","\u2605" * 3 + "{} is a prime number!".format(number) + "\u2605" * 3, sep='') isTrue = True break else: print("\n{} is not a prime number.".format(number)) isTrue = False return isTrue # -------------2. ODEV - Sayinin Tam Bolenlerini Bulma------------- def findDivisors(number): divisors = [] for i in range(2, number//2+1): if number % i == 0: divisors.append(i) divisors.append(number) print('\nAll divisors of {} are: {}'.format(number, ', '.join(map(str, divisors))), end='') return divisors # -------------3. ODEV - Mukemmel Sayi Bulma------------- def isPerfect(): print( "\nPerfect number, a positive integer that is equal to the sum of its " "proper divisors (all it's divisors excluding itself). " "\nFollowing are perfect numbers from 1-1000:\n") for number in range(1,1000): divisors = [] for i in range(1, number // 2 + 1): if number % i == 0: divisors.append(i) divisors.append(number) sumOfDivisors = 0 for i in divisors: sumOfDivisors += i if sumOfDivisors == 2*number: print("\n","\u2605" * 3 + " {} is a perfect number! ".format(number) + "\u2605" * 3, sep='') # else: # print("\n", "{} is not a perfect number!".format(number), sep='') # -------------4. ODEV - Iki Sayinin OBEB'ini Bulma------------- # This function is written to be used for finding EBOB and EKOK def isPrime(number): isTrue = True if number > 1: while isTrue: # See if the number is divisible by any other number than 1 and itself for i in range(2, number // 2 + 1): if number % i == 0: isTrue = False break elif i == 15: isTrue = False else: isTrue = True break else: isTrue = False return isTrue def EBOB(number1, number2): list1 = findDivisors(number1) list2 = findDivisors(number2) intList = list(set(list1) & set(list2)) intList = [i for i in intList if isPrime(i)] ebob = 1 print("\nCommon prime divisors of {} and {} are : ".format(number1, number2), ', '.join(map(str, intList))) for i in intList: ebob *= i # print('\nThe greatest common divisor of {} and {} is {}'.format(number1, number2, ebob)) # print('intersection: ', intList) print("So the EBOB of {} and {} is: ".format(number1, number2), ebob) return ebob # -------------5. ODEV - Iki Sayinin EKOK'unu Bulma------------- def EKOK(number1, number2): if number1 > number2: ekok = number1 else: ekok = number2 while (True): if ((ekok % number1 == 0) and (ekok % number2 == 0)): break ekok += 1 print("\nEKOK of {} and {} is : {} ".format(number1, number2, ekok)) return ekok # -------------6. ODEV - Sayinin Okunusunu Bulma------------- def readNumbers(number): try: onesPron = ['', 'bir', 'iki', 'uc', 'dort', 'bes', 'alti', 'yedi', 'sekiz', 'dokuz'] tensPron = ['On', 'Yirmi', 'Otuz', 'Kirk', 'Elli', 'Altmis', 'Yetmis', 'Seksen', 'Doksan'] if number // 10 == 0: raise IndexError else: tenPron = tensPron[number // 10 - 1] onePron = onesPron[number % 10] print('\n{} ---------->'.format(number), tenPron, onePron) except IndexError: print('\nYou must enter a two digit number!') # -------------7. ODEV - Sayinin Okunusunu Bulma------------- import math def specialTriangle(): triangleList=[] for a in range(1,101): for b in range(1,101): for c in range(1,101): if c**2==(a**2+b**2): sublist=[a,b,c] triangleList.append(sublist) # Following for loop is just to print every 10 items in the list in a new line # Otherwise the print doesn't fit in the screen print('\n') for i in range(len(triangleList) // 10 + 1): print(*triangleList[i * 10:(i + 1) * 10], "\n", sep='; ') return triangleList # -------------8. ODEV - Sayinin Faktoriyelini Bulma------------- def factorial(number): factor = 1 for i in range(1, number+1): factor *=i print('\n{}! = {}'.format(number, factor)) return factor # -------------9. ODEV - Buyuk - Kucuk Harf Sayisini Bulma------------- def CountUpperLower(): text = input("\nPlease type a string to be processed: ") upperLetters = 0 lowerLetters = 0 for i in text: if i.isupper() == True: upperLetters += 1 elif i.islower() == True: lowerLetters += 1 print("Count of capital letters: ", upperLetters) print("Count of small letters: ", lowerLetters) # -------------10. ODEV - Kelimeleri Alfabetik Siralama------------- def orderWords(): text = input("\nPlease type words seperated only by hyphen (-) ekleyerek birden fazla kelime yaziniz:\n") wordList = [] wordList = text.split("-") wordList.sort() return print(*wordList, sep="-") # -------------11. ODEV - Bir Listedeki Ozgun Elemanlari Ayirarak Listeleme------------- def listUnique(): itemList = input("\nMake a list by leaving spaces (e.g. 1 2 3 3 4 5 5) between list elements: ") itemList = list(itemList.split(" ")) uniqueList = [] for i in itemList: if i not in uniqueList: uniqueList.append(i) print("Your original list\t: {}\nList of Unique Items: {}".format(itemList,uniqueList)) return uniqueList # -------------12. ODEV - Tersten Aynimi-Degilmi Bulma------------- # isReverseSame() and isReverseSame2() returns only True or False as they are now # However, you can uncomment the print statements within if else blocks to get a more # user friendly, easy to understand feedback. def isReverseSame(): # This function is case insensitive. So a = A userInput = input("\nEnter a text to check if it's the same from reverse: ") textLength = len(userInput) reverse = '' for i in range(textLength): reverse += userInput[textLength - 1 - i] # Sample entry: ey edip adanada pide ye if userInput.lower() != reverse.lower(): # print('"{}" is read from reverse as:\n"{}" so is NOT the same!'.format(userInput.lower(), reverse.lower())) return False else: # print('"{}" is read from reverse as:\n"{}" so is the same!'.format(userInput.lower(), reverse.lower())) return True # Below is the same function as above but written slightly differently def isReverseSame2(): userInput = input("\nEnter a text to check if it's the same from reverse: ") reverse = userInput[::-1] if userInput.lower() != reverse.lower(): # print('"{}" is read from reverse as:\n"{}" so is NOT the same!'.format(userInput.lower(), reverse.lower())) return False else: # print('"{}" is read from reverse as:\n"{}" so is the same!'.format(userInput.lower(), reverse.lower())) return True # _____________________________________________________________________________ # | To run any of the functions, just remove the preceding comment character # | # | and replace x, y where applicable with the desired input or uncomment | # | the lines where input is asked (lines 212-214) to ask the user for a single| # | input or two inputs. | # |_____________________________________________________________________________| # x = int(input("\nEnter a two digit number: ")) # x = int(input("\nEnter the first number: ")) # y = int(input("\nEnter the second number: ")) # isPrimeNumber(x) # Question 1 # findDivisors(x) # Question 2 # isPerfect() # Question 3 # EBOB(x,y) # Question 4 # EKOK(x,y) # Question 5 # readNumbers(x) # Question 6 # specialTriangle() # Question 7 # factorial(x) # Question 8 # CountUpperLower() # Question 9 # orderWords() # Question 10 # listUnique() # Question 11 # isReverseSame() # Question 11 ----> Uncomment this line and print statements inside the function # isReverseSame2() # Question 11 ----> Uncomment this line and print statements inside the function # print(isReverseSame()) # Question 11 ----> Uncomment this line just to get a True or False # print(isReverseSame2()) # Question 11 ----> Uncomment this line just to get a True or False
f61616a4797d5b32f79123b0a0e9f417c3928f0d
aedillo15/RolePlayingGame
/modules/Wizard.py
2,686
3.8125
4
'This document is a Wizard module implements the data and logic associated with the first role (Wizard)' class Wizard: #These member variables (attributes) here display the statistics of the Warrior class # Constructor for Warrior class when called user defines the name create name and assign stats accordingly def __init__ (self, Name): self.Name = Name self.Strength = -2 self.Vitality = 0 self.Intelligence = 2 self.HealthPoints = 100 self.Health = 100 self.ItemBackpack = [] #The vitalityHealth method results in health goes down accordingly to the attribute of Vitality def VitalityHealth(self, Vitality): TotalHealth = self.Health if(Vitality == 1): TotalHealth = self.Health + 25 elif(Vitality == 2): TotalHealth = self.Health + 50 elif(Vitality == -1): TotalHealth = self.Health - 25 elif(Vitality == -2): TotalHealth = self.Health - 50 else: print('No changes to health') return TotalHealth #The criticalLoss() method results in the stat change when the Warrior loses the challenge critically rolling a number between 2-3 def criticalLoss(self): self.Intelligence = self.Intelligence - 1 self.HealthPoints = self.Health - 50 self.Vitality = self.Vitality - 1 self.Health = self.VitalityHealth(self.Vitality) ToString = 'With your critical loss, attributes have gone down strength is now: ' + str(self.Strength) + ' vitality is now: ' + str(self.Vitality) + ' resulting in total Health now is: ' + str(self.HealthPoints)+ '/' + str(self.Health) return ToString #The criticalWin() method results in the stat change when the Warrior wins the challenge critically rolling a number between 11-12 def criticalWin(self): self.Intelligence = self.Intelligence + 1 self.HealthPoints = self.Health + 50 self.Vitality = self.Vitality + 1 self.Health = self.VitalityHealth(self.Vitality) ToString = 'With your critical win, attributes have gone up strength is now: ' + str(self.Intelligence) + ' vitality is now: ' + str(self.Vitality) + ' resulting in total Health now is: ' + str(self.HealthPoints)+ '/' + str(self.Health) return ToString def Stats(self): ToString = '\n' + 'Name: ' + self.Name + '\n' +'Class: ' + 'Wizard' + '\n' + 'Strength: ' + str(self.Strength) + '\n' + 'Vitality: ' + str(self.Vitality) + '\n' + 'Intelligence: ' + str(self.Intelligence) + '\n' + 'Total Health: ' + str(self.HealthPoints) + '/' + str(self.Health) + '\n' return ToString
71af0e8b3c2b4126e2f12adfae05459253d8d979
leitao-bcc/gympass-backend-test-2018
/race/log_utils.py
305
3.625
4
""" functions to support log parser """ def split_log_line(line): """ Clears and divides a log line :param line: string :return: list of string """ line = line.replace('\t', ' ') line = line.replace('\n', ' ') return [item for item in line.split() if item and item != '–']
9b592df342aa458c25bc55870d80b8837a45d3b8
trhn94/pythonexamples
/tekcift.py
211
4.03125
4
def f(a): if a%2==0: return True else: return False a= int(input("bir sayı giriniz:")) sonuc = f(a) if sonuc == True: print("bu sayı çifttir.") else: print("Bu sayı tektir.")
243715f62d8fd3c231819b038c310ca7ef77e23a
boini-ramesh408/Datastructures_programs
/QueueDemo.py
1,588
4.03125
4
class Node: def __init__(self, data): # It creates the node with data and address fields self.data = data self.next = None class Queue: def __init__(self): self.head = None def addFront(self, data): if self.head is None: node = Node(data) self.head = node print("node inserted") return node = Node(data) node.nref = self.start_node self.head.pref = new_node self.start_node = new_node # def addFront(self,data): # #print(data) # node=Node(data) # if self.head is None: # head=node # else: # temp=self.head # while temp.next is not None: # temp=temp.next # temp.next=node def addRear(self,data): global dec temp=self.head if self.head==None: dec=Node(data) self.head=dec while temp.next is not None: temp=temp.next deque=Node(data) temp.next=deque def removeFront(self,rempve): prev= self.head head= self.head.next return prev.data def renoveRear(self): xx=None temp=self.head prev=temp while temp.next is not None: prev=temp temp=temp.next xx=temp.next prev.next=None return xx def display(self): temp = self.head while temp is not None: print(temp.data) temp =temp.next
41664092d5b2c3396bb29a2f99bc333dd9ff5c01
mohitj2401/python
/uses of tkinker/1.py
418
3.53125
4
from tkinter import * window=Tk() def PrintValue(): print(uservar.get()) # uservar=StringVar() # uservar.trace("w",lambda name,index,mode:PrintValue() labelUser=Label(window,text="Username : ") labelPass=Label(window,text="Password : ") labelUser.grid(row=0,sticky=W) labelPass.grid(row=2,sticky=W) eUser= Entry(window) eUser.grid(row=0,column=1) ePass=Entry(window) ePass.grid(row=2,column=1) window.mainloop()
4f96bef46d27eddedb19e13f11d1ae7c28626009
Cica013/Exercicios-Python-CursoEmVideo
/Pacote_Python/Ex_python_CEV/exe080.py
523
4.0625
4
# Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na posição # correta de inserção ( sem usar o sort()). No final mostre a lista ordenada na tela. lista = [] n = 0 for c in range(0, 5): num = int(input('Digite um valor: ')) if c == 0 or num > lista[-1]: lista.append(num) else: pos = 0 while True: if num <= lista[pos]: lista.insert(pos, num) break pos += 1 print(lista)
6c3ed3f0a849e08106e7cb47082ec1de506606d9
jincurry/LeetCode_python
/226_invert_binary_tree.py
1,339
4.25
4
# Invert a binary tree. # # 4 # / \ # 2 7 # / \ / \ # 1 3 6 9 # to # # 4 # / \ # 7 2 # / \ / \ # 9 6 3 1 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root is not None: nodes = [] nodes.append(root) while nodes: node = nodes.pop() node.left, node.right = node.right, node.left if node.left is not None: nodes.append(node.left) if node.right is not None: nodes.append(node.right) return root if __name__ == '__main__': solution = Solution() root = TreeNode(4) a = TreeNode(2) b = TreeNode(7) c = TreeNode(1) d = TreeNode(3) e = TreeNode(6) f = TreeNode(9) root.left = a root.right = b a.left = c a.right = d b.left = e b.right = f answer = solution.invertTree(root) print(answer.val, answer.left.val, answer.right.val) print(answer.left.left.val, answer.left.right.val) print(answer.right.left.val, answer.right.right.val)
ee35106f20720133daf4a5efd6d33f18403d3218
seadog0331/LeetCode-Note
/2021-01-13/selectionSort.py
206
3.640625
4
def selectionSort(nums): n = len(nums) for i in range(n): for j in range(i, n): if nums[i] > nums[j]: nums[i],nums[j] = nums[j],nums[i] return nums
7f0287bca953d9a9c93c7904c6134f2cd18cac69
margonjo/Functions
/1.3.py
374
4
4
#Marc Gonzalez #4/12/14 #1.3 def numbers(): num1 = int(input("please enter a number: ")) num2 = int(input("please enter another number: ")) return num1, num2 def calculate(num1, num2): if num1> num2 : print(num2, num1) else: print(num1, num2) def sort(): num1, num2 = numbers() calculate(num1, num2) sort()
06b9ccb9215d6f4a588a6a46b253a438742ced67
wait17/data_structure
/10.8/05.数组优化.py
1,317
3.90625
4
# 自动添加函数??? class Array: def __init__(self, capacity): self.array = [None] * capacity self.size = 0 def insert(self, index, element): if index < 0: raise IndexError("索引越界") if index >= len(self.array) or self.size >= len(self.array): # 后半部分不理解 size从什么开始 self.addcapacity() for i in range(self.size - 1, index - 1, -1): # 代码逻辑问题, 并画图加深理解 self.array[i + 1] = self.array[i] self.array[index] = element self.size += 1 def remove(self,index): if index < 0 or index > self.size: # 虽然理论上可以隔空插入,但是不符合常理 raise IndexError("数组越界") for i in range(index,self.size): self.array[i] = self.array[i + 1] self.size -= 1 def addcapacity(self): new_array = [None] * len(self.array) * 2 for i in range(self.size): new_array[i] = self.array[i] self.array = new_array def output(self): for i in range(self.size): print(self.array[i]) if __name__ == '__main__': a = Array(5) a.insert(0, 1) a.insert(1,2) a.insert(2,3) a.insert(3,4) a.remove(1) print(a.array) print(a.size)
8b8d6da0d5f8220420ecef24c8a40a6db50dc39f
nhkim-eyenix/hamster_roboid
/examples/turtle/example31.py
565
3.65625
4
# Advanced Multiple Color Pattern Detector # author: Kwang-Hyun Park (akaii@kw.ac.kr) from roboid import * turtle1 = Turtle() turtle2 = Turtle() # user-defined function def check_backward(robot): return robot.is_color_pattern("purple", "red") # wait until the color pattern is (purple, red) wait_until(check_backward, turtle1) turtle1.sound("beep") # beep turtle1.move_backward() # move backward # wait until the color pattern is (purple, red) wait_until(check_backward, turtle2) turtle2.sound("beep") # beep turtle2.move_backward() # move backward
a6154387460a2dea60eccf65d06b63e94a35ea4e
freialobo/Labs
/Intro to Programming/Homework/Freia_Lobo_Homework_6.3.py
182
4.0625
4
#Freia Lobo - fll220@nyu.edu - Homework #6 Problem #1 number = int (input ("Enter a number to factorize ")) for i in range (1, number+1): if number%i == 0: print (i)
c7e41dcd8a5f3e7b26bedf148f1f1ab87ff341ba
techtronics/protoplasm-6
/HW2/IntermediateCode.py
22,168
3.578125
4
from ASMCode import * from Graph import UndirectedGraph class ThreeAddress(object): def __init__(self, dest=None, arg1=None, arg2=None, op=None): """A new three address object: dest = arg1 [op] [arg2] Have the form: dest = arg1 dest = op arg1 dest = arg1 op arg2 Arguments: Keyword Arguments: dest - destination variable arg1 - first argument arg2 - second argument op - operator """ self.dest = dest self.arg1 = arg1 self.arg2 = arg2 self.op = op self.variables = { 'in': set(), 'out': set(), 'used': set(), 'defined': set() } if dest is not None: self.variables['defined'].add(dest) # TODO: make this nicer if arg1 is not None and not str(arg1).isdigit(): self.variables['used'].add(arg1) if arg2 is not None and not str(arg2).isdigit(): self.variables['used'].add(arg2) # Load and store use memory addresses and not variables if op == 'load': self.variables['defined'] = set([self.dest]) self.variables['used'] = set() elif op == 'store': self.variables['used'] = set([self.arg1]) self.variables['defined'] = set() def rename_dest(self, dest): """Rename destination variable. ONLY FOR THIS STATEMENT Updates defined set Arguments: dest - new name for destination """ self.variables['defined'].remove(self.dest) if dest is not None: self.variables['defined'].add(dest) self.dest = dest if self.op == 'load': self.variables['defined'] = set([self.dest]) self.variables['used'] = set() elif self.op == 'store': self.variables['used'] = set([self.arg1]) self.variables['defined'] = set() def rename_arg1(self, arg1): """Rename arg1 variable. ONLY FOR THIS STATEMENT Updates used set Arguments: arg1 - new name for arg1 """ if self.arg1 in self.variables['used']: self.variables['used'].remove(self.arg1) if isinstance(arg1, str): self.variables['used'].add(arg1) self.arg1 = arg1 if self.op == 'load': self.variables['defined'] = set([self.dest]) self.variables['used'] = set() elif self.op == 'store': self.variables['used'] = set([self.arg1]) self.variables['defined'] = set() def rename_arg2(self, arg2): """Rename arg2 variable. ONLY FOR THIS STATEMENT Updates used set Arguments: arg2 - new name for arg2 """ if self.arg2 in self.variables['used']: self.variables['used'].remove(self.arg2) if isinstance(arg2, str): self.variables['used'].add(arg2) self.arg2 = arg2 def update_variable_sets(self, next_ta=None): """Update in and out sets. Keyword Arguments: next_ta - the three address after this one (used to update out set) if None given, then Out not updated (good for last statement) Return: boolean of whether something was changed or not """ changed = False if next_ta: # Out(n) = In(n + 1) changed, self.variables['out'] = ( not(self.variables['out'] == next_ta.variables['in']), next_ta.variables['in']) # In(n) = Used(n) U (Out(n) - Defined(n)) new_in = self.variables['used'].union( self.variables['out'].difference(self.variables['defined'])) changed, self.variables['in'] = ( (changed or not(self.variables['in'] == new_in)), new_in) return changed def rename_variables_to_registers(self, variable_map): """Rename variables to registers. DOES NOT UPDATE LIVELINESS Arguments: variable_map - dict of name : register """ if self.dest: self.dest = variable_map[self.dest] if self.arg1 is not None and isinstance(self.arg1, str): self.arg1 = variable_map[self.arg1] if self.arg2 is not None and isinstance(self.arg2, str): self.arg2 = variable_map[self.arg2] def is_binary_op(self): return self.dest is not None and self.arg1 is not None and self.arg2 is not None and self.op is not None def is_assignment(self): return self.dest is not None and self.arg1 is not None and self.arg2 is None and self.op is None def is_unary_op(self): return self.dest is not None and self.arg1 is not None and self.arg2 is None and self.op in ['-'] def __str__(self): if self.dest and self.arg1 is not None and self.arg2 is not None and self.op: return '%s = %s %s %s' % (self.dest, self.arg1, self.op, self.arg2) elif self.dest and self.arg1 is not None and self.op: return '%s = %s %s' % (self.dest, self.op, self.arg1) elif self.dest and self.arg1 is not None and self.op: return '%s = %s %s' % (self.dest, self.op, self.arg1) elif self.dest and self.arg1 is not None: return '%s = %s' % (self.dest, self.arg1) elif self.dest and self.op: return '%s = %s' % (self.dest, self.op) elif self.arg1 is not None and self.op: return '%s %s' % (self.op, self.arg1) class ThreeAddressContext(object): TEMP_REGS = { '$t0': '#FF7400', '$t1': '#009999', '$t2': '#FF7373', '$t3': '#BF7130', '$t4': '#A60000', '$t5': '#008500', '$t6': '#00CC00', '$t7': '#D2006B', '$t8': '#574DD8', '$t9': '#B7F200' } ALL_TEMP_REGS = set(TEMP_REGS.keys()) def __init__(self): """Keeps track of the ASTNode to address context translation """ self.instructions = [] self.variables = [] self.counter = 0 self.liveliness_graph = UndirectedGraph() self.variable_usage = {} def add_instruction(self, ins): """Add a ThreeAddress to the instruction list Arguments: ins - ThreeAddress """ self.instructions.append(ins) def new_var(self): """Create a new temporary variable. Autoincremented. """ name = '@%s' % self.counter self.counter += 1 return name def new_label(self): """Create a new label name Autoincremented. """ name = 'label_%s' % self.counter self.counter += 1 return name def add_var(self, var): """Add a variable to the stack Arguments: var - variable """ self.variables.append(var) def pop_var(self): """Remove a variable from the stack Return: top variable form stack """ return self.variables.pop() def gencode(self): """Converts the list of ThreeAddress objects to ASMInstruction Objects, Returns AsmInstructionContext """ asm = AsmInstructionContext() for i in self.instructions: asm.add_threeaddress(i) return asm def registerize(self, flatten_temp=False, ssa=False, propagate_variables=False, propagate_constants=False, eliminate_dead_code=False): """Perform optimization procedures and translate variables to use registers. Keyword Arguments: flatten_temp - look @ThreeAddressContext.flatten_temporary_assignments ssa - look @ThreeAddressContext.update_ssa """ if flatten_temp: self.flatten_temporary_assignments() if propagate_variables: self.propagate_variables() if propagate_constants: self.propagate_constants() if ssa: self.update_ssa() if eliminate_dead_code: self.eliminate_dead_code() self.mipsify() # Keep looping until we allocated # will loop multiple times if not enough registers and we spill allocated = False while not allocated: self.update_liveliness() allocated = self.allocate_registers() # Remove self assignments self.eliminate_self_assignment() def flatten_temporary_assignments(self): """Loop through all instructions and flatten temp assignments like so: @1 = @0 * 2 --> a = @0 * 2 a = @1 Assumptions: any variable of the form @x where x is a number, will NOT be used after it is assigned to a variable. """ i = 1 # While loop, because we pop stuff while i < len(self.instructions): ins = self.instructions[i] prev_ins = self.instructions[i - 1] # Look for current assignment == previous destination # and previous destination is a temp var: @... if(ins.is_assignment() and prev_ins.dest == ins.arg1 and prev_ins.dest[0] == '@'): prev_ins.rename_dest(ins.dest) self.instructions.pop(i) else: i += 1 def propagate_variables(self): """Propagate variables and remove self assignments: a = 1; b = a; --> a = a; --> NOP b = b; --> a = a; --> NOP print(b); --> print(a); """ # Array of: (int, a,b) # from int onwards, change a to b changes = [] for i in xrange(len(self.instructions) - 1, -1, -1): ins = self.instructions[i] # If we're doing: a = b then from here on, we can change # all a's to b's if ins.is_assignment() and isinstance(ins.arg1, str): changes.insert(0, (i, ins.dest, ins.arg1)) # Rename everything using limits for i in xrange(len(self.instructions) - 1, -1, -1): ins = self.instructions[i] # Rename from bottom up for c in xrange(len(changes) - 1, -1, -1): line, orig, new = changes[c] if i >= line: if ins.arg1 == orig: ins.rename_arg1(new) if ins.arg2 == orig: ins.rename_arg2(new) if ins.dest == orig: ins.rename_dest(new) # Remove if it becomes self-referencing if ins.is_assignment() and ins.dest == ins.arg1: self.instructions.pop(i) def propagate_constants(self): """Solve constants: ie a = 2 + 3; --> a = 5; b = 4 * a; --> b = 20; print(b); --> print(20); """ values = {} ops = { '-': lambda x, y: x - y, '+': lambda x, y: x + y, '*': lambda x, y: x * y, '/': lambda x, y: x / y, '%': lambda x, y: x % y } for i in self.instructions: # Replace arg1 if its defined if i.arg1 in values: i.rename_arg1(values[i.arg1]) # Replace arg2 if its defined if i.arg2 in values: i.rename_arg2(values[i.arg2]) # If its a binary op and both are ints, we can calculate now # Changes it to an assignment statement if i.is_binary_op() and isinstance(i.arg1, int) and \ isinstance(i.arg2, int): result = ops[i.op](i.arg1, i.arg2) i.rename_arg1(result) i.rename_arg2(None) i.op = None # If its an assignment and the source is an int # we can save it for future lookup if i.is_assignment() and isinstance(i.arg1, int): values[i.dest] = i.arg1 def update_ssa(self): """Translate three address code to use Static Single Assignment variables. """ vc = {} for i in self.instructions: # If its been declared before and updated, use updated # TODO: clean this up if isinstance(i.arg1, str) and i.arg1 in vc and vc[i.arg1] != 0: i.rename_arg1('%s%s' % (i.arg1, vc[i.arg1])) if isinstance(i.arg2, str) and i.arg2 in vc and vc[i.arg2] != 0: i.rename_arg2('%s%s' % (i.arg2, vc[i.arg2])) # If i.dest is not None and its been declared before, update it if i.dest and i.dest in vc: vc[i.dest] += 1 i.rename_dest('%s%s' % (i.dest, vc[i.dest])) # Otherwise, first time, so use 0 elif i.dest: vc[i.dest] = 0 def eliminate_dead_code(self): """Eliminate unused variables and self assignments """ used = set() add_only_variables = lambda x: used.add(x) if isinstance(x, str) else None # Move bottom up for i in xrange(len(self.instructions) - 1, -1, -1): ins = self.instructions[i] # If the result is not used below us...then remove it if (ins.is_assignment() or ins.is_binary_op() or ins.is_unary_op()) \ and ins.dest not in used: self.instructions.pop(i) # If its used, but its self referencing...then remove it elif ins.is_assignment() and ins.dest == ins.arg1: self.instructions.pop(i) # Otherwise add both arguments (filters to only strings) else: add_only_variables(ins.arg1) add_only_variables(ins.arg2) def mipsify(self): """Convert from generic three address to mips three address compatible Some operations only accept registers: such as =*/%, while others, like +, cannot add two numbers > 16 bits each. This function splits up such instructions into multiple register assignments and adidtion. addi is currently not implemented """ i = 0 while i < len(self.instructions): ins = self.instructions[i] # Replace with registers if either is an int if ins.is_binary_op() and ins.op in ('/', '*', '%', '-', '+'): if isinstance(ins.arg1, int): a = self.new_var() self.instructions.insert(i, ThreeAddress(dest=a, arg1=ins.arg1)) ins.rename_arg1(a) i += 1 if isinstance(ins.arg2, int): a = self.new_var() self.instructions.insert(i, ThreeAddress(dest=a, arg1=ins.arg2)) ins.rename_arg2(a) i += 1 i += 1 def eliminate_self_assignment(self): """After assigning registers, some assignments might be of the form: b = a; --> $t0 = $t0; This function removes such assignments. NOTE: propagate variables and constants ALREADY tries to do this before registers are assigned!! """ i = 0 while i < len(self.instructions): ins = self.instructions[i] if ins.is_assignment() and ins.dest == ins.arg1: self.instructions.pop(i) else: i += 1 def update_liveliness(self): """Loop through all instructions and update their in and out sets. Calculate how many times a variable is used. """ if len(self.instructions) == 0: return for ins in self.instructions: ins.variables['out'] = set() ins.variables['int'] = set() # Keep looping while one of the sets has changed changed = True while changed: changed = False # The last one doesn't have a next changed = changed or self.instructions[-1].update_variable_sets() # Bottom up, update in's and out's, using next statement for i in xrange(len(self.instructions) - 2, -1, -1): changed = changed or self.instructions[i].update_variable_sets( next_ta=self.instructions[i + 1]) # Now build up a graph of which variables need to be alive at the # same time self.liveliness_graph = UndirectedGraph() for ta in self.instructions: # Add defined variables - will be single nodes if not conflicting for i in ta.variables['defined']: self.liveliness_graph.add_node(i) # All the in variables that conflict with each other for i in ta.variables['in']: self.liveliness_graph.add_node(i) for j in ta.variables['in']: if i != j: self.liveliness_graph.add_edge(i, j) # Calculate how many times each variable is used self.variable_usage = {} for ins in self.instructions: for v in ins.variables['used']: if v not in self.variable_usage: self.variable_usage[v] = 1 else: self.variable_usage[v] += 1 def allocate_registers(self): """Allocate registers by coloring in a graph of liveliness """ var_map = {} stack = [] # Build up graph graph = self.liveliness_graph # Loop through all nodes while len(graph.nodes()) > 0: # Get the smallest degree node node = graph.smallest_degree_node() # If its less than amount of registers: we're okay if graph.degree(node) < len(ThreeAddressContext.TEMP_REGS): # node, set of edges stack.append((node, graph.remove_node(node))) # Else we need to look through and find a good candidate else: # Find the node which has the # highest degree - amount of times used node = max(graph.nodes(), key=lambda x: graph.degree(x) - self.variable_usage[x]) stack.append((node, graph.remove_node(node))) # Now add back the nodes while len(stack) != 0: # Remove a node, edges from stack node, edges = stack.pop() graph.add_edges(node, edges) # Get all neighbhor colors neighbor_regs = set([graph.color(n) for n in edges]) # Calculate all possible colors possible_regs = ThreeAddressContext.ALL_TEMP_REGS.difference( neighbor_regs) # If we don't have something to color with, then spill # return false, and wait to be called again if len(possible_regs) == 0: self.spill_variable(node) return False # Get one reg = possible_regs.pop() # Set the color graph.colorize(node, reg) # Now replace with graph colors with actual colors # and store variable to register mapping for node in graph.nodes(): var_map[node] = graph.color(node) graph.colorize(node, ThreeAddressContext.TEMP_REGS[graph.color(node)]) # Rename all variables for ta in self.instructions: if ta.op == 'load': ta.rename_dest(var_map[ta.dest]) elif ta.op == 'store': ta.rename_arg1(var_map[ta.arg1]) else: ta.rename_variables_to_registers(var_map) return True def spill_variable(self, var): """Spill a variable, and store it to a memory location Arguments: var - variable to be spilled """ i = 0 first_assign = True new_var = var label = self.new_label() while i < len(self.instructions): ins = self.instructions[i] if ins.dest == var and first_assign: self.instructions.insert(i + 1, ThreeAddress( dest=label, arg1=new_var, op='store')) first_assign = False i += 2 continue # If we're writing to the variable if ins.is_assignment() and ins.dest == var: new_var = self.new_var() ins.rename_dest(new_var) if ins.arg1 == var: ins.rename_arg1(new_var) # Insert a store after this statement self.instructions.insert(i + 1, ThreeAddress( dest=label, arg1=new_var, op='store')) i += 2 continue # If the spill variable is used, restore before, rename # and store afterwards if var in ins.variables['used']: new_var = self.new_var() self.instructions.insert(i, ThreeAddress( dest=new_var, arg1=label, op='load')) if ins.arg1 == var: ins.rename_arg1(new_var) if ins.arg2 == var: ins.rename_arg2(new_var) if ins.dest == var: ins.rename_dest(new_var) self.instructions.insert(i + 2, ThreeAddress( dest=label, arg1=new_var, op='store')) i += 1 i += 2 continue i += 1 # print "#" * 80 # print 'spill: %s' % var # for x in self.instructions: # print x, x.variables['out'] # print "#" * 80 # self.update_liveliness() # print "#" * 80 # print 'spill: %s' % var # for x in self.instructions: # print x, x.variables['out'] # print "#" * 80 # sys.exit(1) def __str__(self): s = '' for x in self.instructions: s += '%s\n' % (x) return s
9241917a3ebc7c1635b32a74ccfe61d03f44307a
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc075/A/4913495.py
158
3.609375
4
a, b, c = [int(item) for item in input().split()] if a == b: print(c) elif b == c: print(a) elif a == c: print(b) else: print("wrong")
03ff54dde478803373469bb891de406597ea0772
Surajtalwar/python-tasks
/day1.py
3,481
4.15625
4
# Day 1: Basic constructs like data structure and loops[for and while] #### Task 1 STRING & INT #### print("####### String Length #######") s = 'my string' #Let's try to find the length of string result = len(s) print(result) #9 print("####### INT Iteration #######") a = 10 # Let's try to print the numbers from 1 to 10 for i in range(1,a+1): print(i, end=' ') print(end='\n') ####### Task 2 LOOP ####### print("####### LOOP #######") l = [1,2,3,4] for i in l: print(i, end=' ') print(end='\n') ##### Generate table to 2,3,4 and 5 ###### print("####### TABLE #######") table = [2,3,4,5] for i in range(1,11): for j in table: print(j, "*",i, "=", i*j, " ", end=' ') print(end='\n') ######## Gnerate ODD and EVEN numbers ######### print("####### FOR LOOP #######", end = '\n') even=[] odd=[] for i in range(1,21): if(i%2==0): even.append(i) else: odd.append(i) print("Even:", even) print("Odd:", odd) print("####### WHILE LOOP #######", end = '\n') even=[] odd=[] i = 1 while(i<21): if(i%2==0): even.append(i) else: odd.append(i) i+=1 print("Even:", even) print("Odd:", odd) ########## FizzBuzz ######### for i in range(1,101): if ((i%3 == 0 and i%5 == 0)): print("FizzBuzz") elif(i%3 == 0): print("Fizz") elif(i%5 == 0): print("Buzz") else: print(i) ############### Difference between two array and when to use which on ############ # list = [1,2,3,4] # In this first list we are running loop on the list & it is printing values # for i in list: ##### # print(i) ######### # & # list = [1,2,3,4] # In this list we printing the values on the basis of their index # i = 0 ### We can use this logic when we need to print via index value # for i in range(len(list)): ## # print(list[i]) ###### ################## ANSWERS #################### ####### String Length ####### # 9 ####### INT Iteration ####### # 1 2 3 4 5 6 7 8 9 10 ####### LOOP ####### # 1 2 3 4 ####### TABLE ####### # 2 * 1 = 2 3 * 1 = 3 4 * 1 = 4 5 * 1 = 5 # 2 * 2 = 4 3 * 2 = 6 4 * 2 = 8 5 * 2 = 10 # 2 * 3 = 6 3 * 3 = 9 4 * 3 = 12 5 * 3 = 15 # 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16 5 * 4 = 20 # 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 # 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 # 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 # 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 # 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 # 2 * 10 = 20 3 * 10 = 30 4 * 10 = 40 5 * 10 = 50 ####### FOR LOOP ####### # Even: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # Odd: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] ####### WHILE LOOP ####### # Even: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # Odd: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] # 1 # 2 # Fizz # 4 # Buzz # Fizz # 7 # 8 # Fizz # Buzz # 11 # Fizz # 13 # 14 # FizzBuzz # 16 # 17 # Fizz # 19 # Buzz # Fizz # 22 # 23 # Fizz # Buzz # 26 # Fizz # 28 # 29 # FizzBuzz # 31 # 32 # Fizz # 34 # Buzz # Fizz # 37 # 38 # Fizz # Buzz # 41 # Fizz # 43 # 44 # FizzBuzz # 46 # 47 # Fizz # 49 # Buzz # Fizz # 52 # 53 # Fizz # Buzz # 56 # Fizz # 58 # 59 # FizzBuzz # 61 # 62 # Fizz # 64 # Buzz # Fizz # 67 # 68 # Fizz # Buzz # 71 # Fizz # 73 # 74 # FizzBuzz # 76 # 77 # Fizz # 79 # Buzz # Fizz # 82 # 83 # Fizz # Buzz # 86 # Fizz # 88 # 89 # FizzBuzz # 91 # 92 # Fizz # 94 # Buzz # Fizz # 97 # 98 # Fizz # Buzz
9e46d9bd42beda3a7abf8c9532288f30506f4ffa
marcelochavez-ec/Python-Algoritmos_y_programacion
/5.7.2.Factores_primos.py
1,889
4.34375
4
#!/usr/bin/env python #-*-coding:utf-8-*- """ Este soft recibe un numero entero y lo descompone en sus factores primos: Resuelve el punto 5.7.2. del libro Algoritmos y Programacion capitulo 5 pagina 65 """ lista=[] def primo(num1): """ Determina si un numero es primo requiere como parametro un entero retorna el numero si es primo o falso en caso contrario """ for x in range (1,num1): if (num1%x==0 and x!=num1 and x!=1): return False return num1 def lista_primos(num2): """ Esta funcion crea una lista de numeros primos entre 1 y un numero entero PARAMETRO: un numero entero RETORNA: Una lista con numeros primos """ for x in range(2,num2): if primo(x)!=False: lista.append(x) return lista def divisible(lista,num3): """ Dada una lista de numeros esta funcion encuentra si un numero z es divisible por alguno de la lista_primos """ for numero in lista: if num3%numero==0: factores.append(numero) return factores def factores_x(lista, numero, factores_finales): """ Esta funcion permite realizar el calculo de los factores primos de un numero PARAMETROS: requiere de dos listas vacias y el numero a calcular RETORNA: Una lista con los factores del numero """ divisibles=[] print "++++++++++++++++++++++++" print "Sus factores primos son: " print "++++++++++++++++++++++++" while True: salida1=primo(numero) if salida1!=False: factores_finales.append(salida1) break else: lista_primos(numero) #Trae una lista con los numeros primos entre 1 y el NUMERO divisibles=divisible(lista, numero) #trae una lista con los primos divisores del NUMERO factores_finales.append(divisibles[len(divisibles)-1]) numero=numero/divisibles[len(divisibles)-1] return factores_finales factores_finales=[1] lista=[] factores=[] numero=input("Ingrese un numero: ") print factores_x(lista, numero, factores_finales)
07ce930ef00ee1a1784dc4187f0d7c9af1a5e86e
artfin/classical-trajectories
/monte-carlo/integration-examples/toy-example.py
888
3.609375
4
import math import random # out function to integrate def f(x): return math.sin(x) # define any xmin-xmax interval xmin = 0.0 xmax = 2.0 * math.pi # fin ymin-ymax numSteps = 1000 ymin = f(xmin) ymax = ymin for i in xrange(numSteps): x = xmin + (xmax - xmin) * float(i) / numSteps y = f(x) if y < ymin: ymin = y if y > ymax: ymax = y print 'ymin: {0}; ymax: {1}'.format(ymin, ymax) # Monte Carlo rectArea = (xmax - xmin) * (ymax - ymin) numPoints = 100000000 ctr = 0 for j in xrange(numPoints): x = xmin + (xmax - xmin) * random.random() y = ymin + (ymax - ymin) * random.random() if math.fabs(y) <= math.fabs(f(x)): if f(x) > 0 and y > 0 and y <= f(x): ctr += 1 # area over x-axis is positive if f(x) < 0 and y <0 and y >= f(x): ctr -= 1 # area under x-axis is negative fnArea = rectArea * float(ctr) / numPoints print 'Numerical integration = ' + str(fnArea)
72ad6e2d1ce29039d5873a0a01908fae26944a56
CyberRoFlo/Python
/simplePortScanner.py
360
3.53125
4
import socket print("Please enter an IP Address to scan.") target = input("> ") print("*" * 40) print("* Scanning: " + target + " *") print("*" * 40) for port in range(1, 1025): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((target, port)) if result == 0: print("Port: " + str(port) + " Open") s.close()
52698bdc6947a95902f405fa23332e24deb7ef20
flaviaalexandra11/lectii-python
/ex-prog/if-cmd/comparator.py
294
4
4
################### Comparator ########################### x = int(input("Introduceti primul numar (x): ")) y = int(input("Introduceti al doilea numar (y): ")) if x > y: print("x este mai mare decat y") elif x < y: print("y este mai mare decat x") else: print("x este egal cu y")
fe1edf0b55ebf27271bc9c8228de0dada7c9b2db
shizzzerrr/gooselanguage
/crypter.py
16,325
3.59375
4
#программа для крипта \ декрипта текста по заданному словарю import clipboard import os import sys keys = 'keys.txt' #файл находится в одной папке со программой, для создания уникального можешь использовать dictwriter.py. file = open(keys, 'r') dist = file.read().splitlines() file.close() #функция шифрования методом перебора def crypt(text): textreturn = '' length = len(text) for letter in range(length): if text[letter].isalpha(): if text[letter] == 'a': textreturn += dist[0] if text[letter] == 'b': textreturn += dist[1] if text[letter] == 'c': textreturn += dist[2] if text[letter] == 'd': textreturn += dist[3] if text[letter] == 'e': textreturn += dist[4] if text[letter] == 'f': textreturn += dist[5] if text[letter] == 'g': textreturn += dist[6] if text[letter] == 'h': textreturn += dist[7] if text[letter] == 'i': textreturn += dist[8] if text[letter] == 'j': textreturn += dist[9] if text[letter] == 'k': textreturn += dist[10] if text[letter] == 'l': textreturn += dist[11] if text[letter] == 'm': textreturn += dist[12] if text[letter] == 'n': textreturn += dist[13] if text[letter] == 'o': textreturn += dist[14] if text[letter] == 'p': textreturn += dist[15] if text[letter] == 'q': textreturn += dist[16] if text[letter] == 'r': textreturn += dist[17] if text[letter] == 's': textreturn += dist[18] if text[letter] == 't': textreturn += dist[19] if text[letter] == 'u': textreturn += dist[20] if text[letter] == 'v': textreturn += dist[21] if text[letter] == 'w': textreturn += dist[22] if text[letter] == 'x': textreturn += dist[23] if text[letter] == 'y': textreturn += dist[24] if text[letter] == 'z': textreturn += dist[25] if text[letter] == 'A': textreturn += dist[26] if text[letter] == 'B': textreturn += dist[27] if text[letter] == 'C': textreturn += dist[28] if text[letter] == 'D': textreturn += dist[29] if text[letter] == 'E': textreturn += dist[30] if text[letter] == 'F': textreturn += dist[31] if text[letter] == 'G': textreturn += dist[32] if text[letter] == 'H': textreturn += dist[33] if text[letter] == 'I': textreturn += dist[34] if text[letter] == 'J': textreturn += dist[35] if text[letter] == 'K': textreturn += dist[36] if text[letter] == 'L': textreturn += dist[37] if text[letter] == 'M': textreturn += dist[38] if text[letter] == 'N': textreturn += dist[39] if text[letter] == 'O': textreturn += dist[40] if text[letter] == 'P': textreturn += dist[41] if text[letter] == 'Q': textreturn += dist[42] if text[letter] == 'R': textreturn += dist[43] if text[letter] == 'S': textreturn += dist[44] if text[letter] == 'T': textreturn += dist[45] if text[letter] == 'U': textreturn += dist[46] if text[letter] == 'V': textreturn += dist[47] if text[letter] == 'W': textreturn += dist[48] if text[letter] == 'X': textreturn += dist[49] if text[letter] == 'Y': textreturn += dist[50] if text[letter] == 'Z': textreturn += dist[51] if text[letter] == 'а': textreturn += dist[52] if text[letter] == 'б': textreturn += dist[53] if text[letter] == 'в': textreturn += dist[54] if text[letter] == 'г': textreturn += dist[55] if text[letter] == 'д': textreturn += dist[56] if text[letter] == 'е': textreturn += dist[57] if text[letter] == 'ё': textreturn += dist[58] if text[letter] == 'ж': textreturn += dist[59] if text[letter] == 'з': textreturn += dist[60] if text[letter] == 'и': textreturn += dist[61] if text[letter] == 'й': textreturn += dist[62] if text[letter] == 'к': textreturn += dist[63] if text[letter] == 'л': textreturn += dist[64] if text[letter] == 'м': textreturn += dist[65] if text[letter] == 'н': textreturn += dist[66] if text[letter] == 'о': textreturn += dist[67] if text[letter] == 'п': textreturn += dist[68] if text[letter] == 'р': textreturn += dist[69] if text[letter] == 'с': textreturn += dist[70] if text[letter] == 'т': textreturn += dist[71] if text[letter] == 'у': textreturn += dist[72] if text[letter] == 'ф': textreturn += dist[73] if text[letter] == 'х': textreturn += dist[74] if text[letter] == 'ц': textreturn += dist[75] if text[letter] == 'ч': textreturn += dist[76] if text[letter] == 'ш': textreturn += dist[77] if text[letter] == 'щ': textreturn += dist[78] if text[letter] == 'ъ': textreturn += dist[79] if text[letter] == 'ы': textreturn += dist[80] if text[letter] == 'ь': textreturn += dist[81] if text[letter] == 'э': textreturn += dist[82] if text[letter] == 'ю': textreturn += dist[83] if text[letter] == 'я': textreturn += dist[84] if text[letter] == 'А': textreturn += dist[85] if text[letter] == 'Б': textreturn += dist[86] if text[letter] == 'В': textreturn += dist[87] if text[letter] == 'Г': textreturn += dist[88] if text[letter] == 'Д': textreturn += dist[89] if text[letter] == 'Е': textreturn += dist[90] if text[letter] == 'Ё': textreturn += dist[91] if text[letter] == 'Ж': textreturn += dist[92] if text[letter] == 'З': textreturn += dist[93] if text[letter] == 'И': textreturn += dist[94] if text[letter] == 'Й': textreturn += dist[95] if text[letter] == 'К': textreturn += dist[96] if text[letter] == 'Л': textreturn += dist[97] if text[letter] == 'М': textreturn += dist[98] if text[letter] == 'Н': textreturn += dist[99] if text[letter] == 'О': textreturn += dist[100] if text[letter] == 'П': textreturn += dist[101] if text[letter] == 'Р': textreturn += dist[102] if text[letter] == 'С': textreturn += dist[103] if text[letter] == 'Т': textreturn += dist[104] if text[letter] == 'У': textreturn += dist[105] if text[letter] == 'Ф': textreturn += dist[106] if text[letter] == 'Х': textreturn += dist[107] if text[letter] == 'Ц': textreturn += dist[108] if text[letter] == 'Ч': textreturn += dist[109] if text[letter] == 'Ш': textreturn += dist[110] if text[letter] == 'Щ': textreturn += dist[111] if text[letter] == 'Ъ': textreturn += dist[112] if text[letter] == 'Ы': textreturn += dist[113] if text[letter] == 'Ь': textreturn += dist[114] if text[letter] == 'Э': textreturn += dist[115] if text[letter] == 'Ю': textreturn += dist[116] if text[letter] == 'Я': textreturn += dist[117] else: textreturn += text[letter] return textreturn #функция дешифрования методом перебора def decrypt(text): textreturn = '' length = len(text) cycle = 0 while cycle < length: if text[cycle].isalpha(): key = text[cycle] + text[cycle + 1] + text[cycle + 2] + text[cycle + 3] if key == dist[0]: textreturn += 'a' if key == dist[1]: textreturn += 'b' if key == dist[2]: textreturn += 'c' if key == dist[3]: textreturn += 'd' if key == dist[4]: textreturn += 'e' if key == dist[5]: textreturn += 'f' if key == dist[6]: textreturn += 'g' if key == dist[7]: textreturn += 'h' if key == dist[8]: textreturn += 'i' if key == dist[9]: textreturn += 'j' if key == dist[10]: textreturn += 'k' if key == dist[11]: textreturn += 'l' if key == dist[12]: textreturn += 'm' if key == dist[13]: textreturn += 'n' if key == dist[14]: textreturn += 'o' if key == dist[15]: textreturn += 'p' if key == dist[16]: textreturn += 'q' if key == dist[17]: textreturn += 'r' if key == dist[18]: textreturn += 's' if key == dist[19]: textreturn += 't' if key == dist[20]: textreturn += 'u' if key == dist[21]: textreturn += 'v' if key == dist[22]: textreturn += 'w' if key == dist[23]: textreturn += 'x' if key == dist[24]: textreturn += 'y' if key == dist[25]: textreturn += 'z' if key == dist[26]: textreturn += 'A' if key == dist[27]: textreturn += 'B' if key == dist[28]: textreturn += 'C' if key == dist[29]: textreturn += 'D' if key == dist[30]: textreturn += 'E' if key == dist[31]: textreturn += 'F' if key == dist[32]: textreturn += 'G' if key == dist[33]: textreturn += 'H' if key == dist[34]: textreturn += 'I' if key == dist[35]: textreturn += 'J' if key == dist[36]: textreturn += 'K' if key == dist[37]: textreturn += 'L' if key == dist[38]: textreturn += 'M' if key == dist[39]: textreturn += 'N' if key == dist[40]: textreturn += 'O' if key == dist[41]: textreturn += 'P' if key == dist[42]: textreturn += 'Q' if key == dist[43]: textreturn += 'R' if key == dist[44]: textreturn += 'S' if key == dist[45]: textreturn += 'T' if key == dist[46]: textreturn += 'U' if key == dist[47]: textreturn += 'V' if key == dist[48]: textreturn += 'W' if key == dist[49]: textreturn += 'X' if key == dist[50]: textreturn += 'Y' if key == dist[51]: textreturn += 'Z' if key == dist[52]: textreturn += 'а' if key == dist[53]: textreturn += 'б' if key == dist[54]: textreturn += 'в' if key == dist[55]: textreturn += 'г' if key == dist[56]: textreturn += 'д' if key == dist[57]: textreturn += 'е' if key == dist[58]: textreturn += 'ё' if key == dist[59]: textreturn += 'ж' if key == dist[60]: textreturn += 'з' if key == dist[61]: textreturn += 'и' if key == dist[62]: textreturn += 'й' if key == dist[63]: textreturn += 'к' if key == dist[64]: textreturn += 'л' if key == dist[65]: textreturn += 'м' if key == dist[66]: textreturn += 'н' if key == dist[67]: textreturn += 'о' if key == dist[68]: textreturn += 'п' if key == dist[69]: textreturn += 'р' if key == dist[70]: textreturn += 'с' if key == dist[71]: textreturn += 'т' if key == dist[72]: textreturn += 'у' if key == dist[73]: textreturn += 'ф' if key == dist[74]: textreturn += 'х' if key == dist[75]: textreturn += 'ц' if key == dist[76]: textreturn += 'ч' if key == dist[77]: textreturn += 'ш' if key == dist[78]: textreturn += 'щ' if key == dist[79]: textreturn += 'ъ' if key == dist[80]: textreturn += 'ы' if key == dist[81]: textreturn += 'ь' if key == dist[82]: textreturn += 'э' if key == dist[83]: textreturn += 'ю' if key == dist[84]: textreturn += 'я' if key == dist[85]: textreturn += 'А' if key == dist[86]: textreturn += 'Б' if key == dist[87]: textreturn += 'В' if key == dist[88]: textreturn += 'Г' if key == dist[89]: textreturn += 'Д' if key == dist[90]: textreturn += 'Е' if key == dist[91]: textreturn += 'Ё' if key == dist[92]: textreturn += 'Ж' if key == dist[93]: textreturn += 'З' if key == dist[94]: textreturn += 'И' if key == dist[95]: textreturn += 'Й' if key == dist[96]: textreturn += 'К' if key == dist[97]: textreturn += 'Л' if key == dist[98]: textreturn += 'М' if key == dist[99]: textreturn += 'Н' if key == dist[100]: textreturn += 'О' if key == dist[101]: textreturn += 'П' if key == dist[102]: textreturn += 'Р' if key == dist[103]: textreturn += 'С' if key == dist[104]: textreturn += 'Т' if key == dist[105]: textreturn += 'У' if key == dist[106]: textreturn += 'Ф' if key == dist[107]: textreturn += 'Х' if key == dist[108]: textreturn += 'Ц' if key == dist[109]: textreturn += 'Ч' if key == dist[110]: textreturn += 'Ш' if key == dist[111]: textreturn += 'Щ' if key == dist[112]: textreturn += 'Ъ' if key == dist[113]: textreturn += 'Ы' if key == dist[114]: textreturn += 'Ь' if key == dist[115]: textreturn += 'Э' if key == dist[116]: textreturn += 'Ю' if key == dist[117]: textreturn += 'Я' cycle += 4 else: textreturn += text[cycle] cycle += 1 return textreturn #функция тестового интерфейса меню def menu(): os.system("clear") setting1 = 1 #предустановка настройки 1 setting2 = 1 #предустановка настройки 2 print('Goose Language Crypt/Decrypt') print(' Powered by ShiZZZeRRR ') print('1) Зашифровать текст.') print('2) Дешифровать текст.') print('3) Что я умею?') print('4) Настройки.') print('5) Обновить программу.') print('6) Выход из программы.\n') choice = input('crypter > ') if choice == '1': print('Введите нужный текст.') inputtext = input('crypter > ') answer = crypt(inputtext) print( '\n' + 'Зашифрованный текст :\n' + answer ) if setting1 == 1: clipboard.copy(answer) if setting2 == 0: print('\nДля перехода в меню нажмите Enter.') input('crypter > ') if choice == '2': inputtext = input('Введите текст : ') answer = decrypt(inputtext) print() print( 'Расшифрованный текст : ' + answer ) print() print('Для копирования в буфер обмена введите в поле ниже цифру 1.') print('Для перехода в меню нажмите Enter.') if input('crypter > ') == '1': clipboard.copy(answer) if choice == '3': print('\nПривет! Я умею переводить твой текст на гусиный язык и обратно.\nДля использования выбери соответствующие функции в меню.\nПо умолчанию программа скопирует ваш текст в буфер обмена.\nДля отключения этой функции прошу перейти в настройки.\nДля перехода в меню нажмите Enter.\n') input('crypter > ') if choice == '4': os.system("clear") print(' Настройки: ') print(' 0 - выключено | 1 - включено') print('1) Копирование конечного текста в буфер обмена: ' + str(setting1)) print('2) Автоматический переход в меню после шифрования текста : ' + str(setting2) + '\n') print('Выберите номер настройки для того чтобы её изменить (или Enter для перехода в меню).\n') choice2 = input('crypter > ') if choice2 == '1': setting1 = 0 elif choice2 == '2': setting2 = 0 if choice == '5': os.system("cd && rm -rf ~/gooselanguage && git clone https://github.com/shizzzerrr/gooselanguage") if choice == '6': sys.exit() while 1 == 1: #цикличное включение меню после каждого окончания действия. menu()
8541e98facec74fee37b856df0b5e3b11b254835
ElChurco/Introprogramacion
/Grafica/Ejercicio_4.py
366
3.921875
4
numero = str(input("Ingrese un numero: ")) tam = len(numero) mitad = tam // 2 cont = 0 cont1 = -1 cont2 = 0 while cont < mitad: if numero[cont] == numero[cont1]: cont += 1 cont1 -= 1 cont2 += 1 else: cont += 1 cont1 -= 1 if cont2 == mitad: print(f"{numero} es Capicua") else: print(f"{numero} no es Capicua")
3d2623dabe94768b4851145ea7edf9ee48ce16aa
BoxedSnake/tic-tac-toe
/features/Player.py
3,482
4.0625
4
import random class Player: #class for the players def __init__(self,name): self.name=name #user display name, will be defined by the user self.piece = None self.human = False self.select= None #Variables are empty so the class can still run at startup #select is just a holder for user input def side(self,name=None,piece=None): #has a default of none to allow the program to run if piece == "X": self.piece = "O" print (f"{name} is already {piece}\n{self.name} will be {self.piece}") elif piece == "O": self.piece = "X" print (f"{name} is already {piece}\n{self.name} will be {self.piece}") #statement to default pieces if other object has already selected. while self.piece not in["X","O"]: # when the user hasn't chosen a piece this will run choice = str(input ( f"{self.name}\nPick a Token:\n[1] X\n[2] O\n")or "1").upper() if choice == "1": self.piece = "X" elif choice == "2": self.piece = "O" else: print ("Wrong option, Please try again.") #used list in the while loop so I don't have to us raise and exceptions. def cpu(self): while type(self.human) == bool: #used type and bool so it'll always run and also don't need to define another variable for loop pass. cpu1= input(f"is {self.name} a:\n[1] Human\n[2] Computer\n") if cpu1 == "1": self.human = True print (f"{self.name} is now a Human.") return elif cpu1== "2": self.human = False print (f"{self.name} is now a Computer.") return else: print ("Please select the correct choice.") def action(self,mapper): while True: if self.human is True: self.select =(input(f"{self.name}\nWhere do you want to place your {self.piece}?\n")) right_num = ['1','2','3','4','5','6','7','8','9'] #used list and string so else statement will cover int and str value while self.select not in right_num: if self.select in right_num: continue else: print ("Input value is wrong, please try again.") self.select = input ("Please choose a number betweem 1 and 9?\n") self.select = int(self.select)-1 # the -1 is needed to convert from basic to programming # convert the value input from str to int elif self.human is False: self.select = random.randint(1,9)-1 #very basic AI, could be better. if mapper[self.select] != (' '): if self.human is True: print ("Tile Occupied, Please try again.") # if the Human player picks a filled spot this will run # AI won't need this so it'll just loop the action method. else: mapper[self.select]=self.piece self.select = None #clears the user input so it's empty for next turn return
60ebd5b8564c6f1a89d2cd9cddff8fb5fb54dfb8
brandoneng000/LeetCode
/easy/1678.py
754
3.6875
4
class Solution: def interpret(self, command: str) -> str: # res = "" # index, end = 0, len(command) # while index < end: # if command[index] == 'G': # res += 'G' # else: # if command[index + 1] == ')': # res += 'o' # else: # res += 'al' # index += 2 # index += 1 # index += 1 # return res return command.replace('()', 'o').replace('(al)', 'al') def main(): sol = Solution() print(sol.interpret("G()(al)")) print(sol.interpret("G()()()()(al)")) print(sol.interpret("(al)G(al)()()G")) if __name__ == '__main__': main()
dcfe496f0fcf9958a9e8b2727ecec95070323c1b
cometicon/Jukebox
/lib/jukebox.py
4,690
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Nicolas Comte """ import time from abc import ABC, abstractmethod class Track: """Track/song representation.""" ## # @param title string. The name of the track. # @param artist string. The name of the artist(s). # @param length number. The duration of the track. def __init__(self, name, artist, length = None): self._name = name self._artist = artist self._length = length ## # @returns string. The name of the track. def getName(self): return self._name ## # @returns string. The name of the artist(s) def getArtist(self): return self._artist ## # @returns integer. The duration of the track (seconds). def getLength(self): return self._length class Playlist: """Playlist, set of tracks. It is a simple wrapper of list. If the playlist is ended it will restart by the beginnning.""" ## # @param tracks list of tracks. List that represents a collection of tracks. def __init__(self, tracks): self._current = -1 self._list = tracks ## # @returns list of tracks. def getTrackList(self): return self._list ## # @returns track. The last track returned by the playlist. def getCurrentTrack(self): return self._list[self._current] if self._current < len(self._list) else None ## # @returns track. Go to the next track and return it. If the playlist is ended, the first track will be returned. def nextTrack(self): self._current = self._current + 1 if (self._current + 1) < len(self._list) else 0 return self.getCurrentTrack() ## # @returns number. The total playlist duration. def getTotalTime(self): res = 0 for s in self._list: res += s.getLength() return res ## # @param track track. Append a track to the playlist. def addTrack(self, track): self._list.append(track) ## # @brief add tracks to the playlist. # @param tracks list of tracks. List of tracks to be inserted in the current playlist. def addTracks(self, tracks): self._list.extend(tracks) class Player(ABC): """Jukebox player class that can run playlists and play its musics.""" ## # @brief play track. Abstract method # @param track track. The track to play. @abstractmethod def play(self, track): pass # @brief run the playlist. Can be stopped with Ctrl-D action. # @param playlist playlist. The playlist to launch. # @param loop boolean. Repeat the playlist after the last song if true. def runPlaylist(self, playlist, loop = False): timeout = time.time() + playlist.getTotalTime() try: while loop or time.time() < timeout: track = playlist.nextTrack() self.play(track) except KeyboardInterrupt: print('Stopped.') class TrackPlayer(Player): """Music player specialized in Track reading.""" ## # @brief play track. Abstract method # @param track track. The track to play. def play(self, track): print("Playing: " + track.getName()) time.sleep(track.getLength()) # simulation of playing Track class Jukebox: """Jukebox class""" ## # @param library list of tracks. The collection of tracks associated to the jukebox. def __init__(self, library, player): self._library = library # collection of tracks self._playlist = Playlist([]) self._player = player ## # @brief add a track into the current playlist. # @param track track. def select(self, track): self._playlist.addTrack(track) ## # @brief set playlist in the jukebox. Will replace the previous by a new one. def setPlaylist(self, playlist): self._playlist = playlist ## # @brief get current playlist of the jukebox. def getPlaylist(self): return self._playlist ## # @brief set a new library in the jukebox. Will replace the current one. def setLibrary(self, library): self._library = library ## # @brief launch the playlist. # @param loop boolean. Repeat the playlist after the last song if true. def play(self, loop = False): self._player.runPlaylist(self._playlist, loop)
9eda009c657c6f5cc89e1eea3cb7e0297a7fffaf
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/wrtjos001/question3.py
802
4.3125
4
"""encrypt a message by converting all lowercases letters to the next character using recursion joshua wort 5 May 2014""" def encrypted(message): #base case if message=="": return message #checks if character is uppercase elif message[0]==message[0].upper(): return message[0]+ encrypted(message[1:]) #checks if character is not part of the alphabet elif not message[0].isalpha(): return message[0] + encrypyted(message[1:]) #checks if character is "z" and if so converts it to "a" elif message[0]=="z": return "a" + encrypted(message[1:]) else: return chr(ord(message[0])+1) + encrypted(message[1:]) message = input("Enter a message:\n") print("Encrypted message:\n", encrypted(message), sep="")
e7b40ba8bfd6c315ee0466fe8831a55e91748c01
Katolus/python-proving-ground
/modules/collections/Counter.py
1,103
3.984375
4
""" Demonstrates the use of Counter https://docs.python.org/3/library/collections.html#collections.Counter """ from collections import Counter cnt = Counter(["red", "blue", "red", "green", "blue", "blue"]) print("string counter -> ", cnt) cnt = Counter("sdadsdddsssaa") print("most common (2) -> ", cnt.most_common(2)) cnt = Counter([1, 2, 3, 4, 5, 5, 5, 6, 6, 6, 6, 67, 77]) # Mode calculation? print("integer counter -> ", cnt) def counter(): return Counter(a=4, b=2, c=0, d=-2) c = counter() d = Counter(a=1, b=2, c=3, d=4) c.subtract(d) print("substract c - d -> ", c) print("total of all counts -> ", sum(c.values())) c = counter() c.clear() print("reset all counts -> ", c) print("list unique elements -> ", list(counter())) print("convert to set -> ", set(Counter(a=1, c=2, b=3, d=5))) # Random order result print("convert to a regular dict -> ", dict(counter())) print("convert to a list of (elem, cnt) pairs -> ", counter().items()) n = 3 print("n least common elements -> ", counter().most_common()[:-n-1: -1]) c = counter() print("remove zero and negative counts -> ", +c)
3269f822e86b282c5de00d56319af90acf906ce7
elumo36/sample-streamlit
/example2.py
462
3.640625
4
# cordin:utf-8 import tkinter as tk def click(event): #クリックされたときにそこに描画する canvas.create_oval(event.x-20,event.y-20, event.x+20,event.y+20, fill="red", width=0) #ウィンドウを描く root = tk.Tk() root.geometry("600x400") #キャンバスを置く canvas = tk.Canvas(root, width=600, height=400, bg="white") canvas.place(x=0,y=0) #イベントを設定する canvas.bind("<Button-1>", click) root.mainloop()
38fe32f0acc415f215f4fdc48572ed7211ac2b30
python-practice-b02-927/kuleshov
/lab2/ex10.py
212
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 10 10:32:56 2019 @author: student """ from turtle import * a = 100 n = 6 shape('turtle') for i in range(n): circle(a) right(360/n)