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
4f143da7d7f56c7cb8c2723bd400768973e3aebc
jpslat1026/Mytest
/Section1/1.3/3.py
460
4.03125
4
#3.py #by John Slattery on November 15, 2018 #This script finds the weight of atoms import math def main(): print("This script will help you calculate the weight of atoms ") H = 1.00794 C = 12.0107 O = 15.9994 h = eval(input("How many Hydrogen atoms: ")) c = eval(input("How many carbon atoms: ")) o = eval(input("How many Oxygen atoms: ")) output = (H * h) + ( C *c ) + (O * o ) print("The weight is", output, "grams/mole") main()
cc990f3e021f89e067f348600d317c0f3614f048
irimina/Python_functions
/TryExceptDebugging#5.py
1,669
4.34375
4
''' Compare the following programs below ''' # program 1 without try and except #Function to calculate discount and tax amount def price_calculator(price, discount): # discount_rate=discount/100 if you just let the user enter a number and not a .something discount_amount = price * discount. # change discount to discount rate if the user only enters an integer not a decimal price= price - discount_amount return price original_price = float(input("What is the total cost of the order? ")) discount = float(input("Enter discount %: ")) discounted_price = price_calculator(original_price, discount) print("The discounted price is", discounted_price) # same program #2 with try and except #Function to calculate discount and tax amount def price_calculator(price, discount): discount_rate = discount / 100 discount_amount = price * discount_rate price -= discount_amount return price #Ask the user for the price while True: try: original_price = float(input("What is the total cost of the order? ")) break except ValueError: print("Please enter a valid number") while True: try: discount = float(input("Enter discount %: ")) if discount >= 0 and discount <= 100: break else: print("Please enter a value between 0 and 100") except ValueError: print("Please enter a valid number") discounted_price = price_calculator(original_price, discount) print("The price", discounted_price) ################################################################# ################################################################# #################################################################
a79b68e004c26f9f976fa129121fc5e7c7c20d4a
PrajwalGhadi/GFG-Leet-Code-Python-Practise
/GeekForGeek Practise/Pattern_Prac2.py
227
4.0625
4
'''Date - 11-06-2021 Author - Prajwal Ghadi Aim - Programs for printing pyramid patterns in Python.''' n = int(input()) k = n - 1 for i in range(0, n): for j in range(0, i + 1): print('*', end='') print()
c1772df4ad30822a95d9b0a565e254e71ca638c6
Anil-account/python-program
/lab exe2.py
4,378
3.921875
4
# 1 to find 5 present or not # l =[1,2,3,4,5] # for i in range (len(l)): # if 5==l[1]: # print("true") # else: # print("false") # 2 to print marks result # mark1 = int(input("Enter your math mark :")) # mark2 = int(input("Enter your science mark :")) # mark3 = int(input("Enter your english mark :")) # mark4 = int(input("Enter your nepali mark :")) # total = mark1+mark2+mark3+mark4 # print("your total mark is ",total) # percentage = (total/400)*100 # print("your perecentage is ",percentage) # if percentage>70: # print("you got distinction") # elif percentage>60: # print("you got first division") # elif percentage>40: # print("you are pass") # else: # print(("study hard")) # # print("GPA = ",percentage/25) # 3 to print odd or even # n = int(input("enter a limit num : ")) # for i in range(n): # if i%2==0: # print(i, "EVEN") # else: # print(i, "ODD") # 4 to print smallest one # i = 0 # l=[] # while i<3: # a = int(input("enter a number")) # i = i+1 # l.append(a) # if l[0]<l[1] and l[0]<l[2]: # print(l[0], "is smallest") # elif l[1]<l[0] and l[1]<l[2]: # print(l[1], "is smallest") # elif l[2]<l[1] and l[2]<l[0]: # # print(l[2], "is smallest") # 5 to print true and false for intiger # a = int(input("Enter a number")) # # if a > 0: # print("True") # elif a < 0: # print("False") # else: # print("zero") # 6 to print intiger last digit # n = int(input('enter three number')) # if n<=999: # a = n//100 # b = (n-(a*100))//10 # c = (n-((a*100)+(b*10))) # # print(a) # # print(b) # print(c) # else: # print("Invalid") # 7 to print positive number and its fractional part # num = float(input("enter number")) # # integralPart = int(num) # fractionalPart = num - integralPart # print("positive part is ", integralPart # print("fraction part is ", fractionalPart) # 8 to add sum of number # num = int(input('enter a number')) # def sum_digits(n): # s = 0 # while n: # s += n % 10 # n //= 10 # return s # # print("sum of digit is", sum_digits(num)) # 9 to find leap year or not # year = 2001 # if (year % 4) == 0: # if (year % 400) == 0: # print(str(year) +" is a leap year") # else: # print(str(year) +" is not a leap year") # # else: # print(str(year) + " is not a leap year") # 10 if value are equal sum will be zero # a = int(input("enter a number : ")) # b = int(input("enter a number : ")) # c = int(input("enter a number : ")) # if a==b or a==c: # print("sum is equal to '0'") # elif b==a or b==c: # print("sum is zero") # elif c==a or c==b: # print("sum is zero") # else: # print("sum is", a+b+c) # 11 to find square root # number = 10 # print(number**3) # 12 to find x # x = 5 # x += 3 # print(x) # 13 to print apple # to print apple > apple # print('Apple' > 'apple') # # 14 to print float # print(float(1)) # 15 to find output of a,b,c,d # a =int(input("enter value for a :")) # b =int(input("enter value for b :")) # c = int(input("enter value for c :")) # d =int(input("enter value for d :")) # if a == b: # print("a and b are equal") # else: # print("a and b are not equal") # if a != d: # print("a and d is not equal") # else: # print("a and d is equal") # if b == d: # print("b and d are equal") # else: # print("b and d are not equal") # if a != c: # print("a is not equal to c") # else: # print("a is equal to c") # if b > a: # print("b is greater than a") # else: # print("b is not greater than a") # if a < d: # print("d is greater than a") # else: # print("d is not greater than a") # if b-a == c-b: # print("b-a==c-b") # else: # print("b-a==c-b is not equal") # if b >= d: # print("b is greater or equal to d") # else: # print("b is not greater nor equal to d") # a += c # print("a+c =", a) # b /= d # print("b/d=", d) # --------------------------------------------------------------------------------------------------------------------- # print individual number. # a=("Anil") # b = a.replace('',' ') # print(b) # # for i in range(len(b)): # print(b[i]) # to print factorial part # n = int(input("enter a number")) # a = 1 # for i in range (1,n+1): # a = a*i # print(a)
7f17d15b0a2b3b1035983528196510a8da88d0b5
raineynw/25-TkinterAndMQTT
/src/m3_robot_as_mqtt_receiver.py
1,508
3.53125
4
""" Using a Brickman (robot) as the receiver of messages. """ # Same as m2_fake_robot_as_mqtt_sender, # but have the robot really do the action. # Implement just FORWARD at speeds X and Y is enough. import tkinter from tkinter import ttk import mqtt_remote_method_calls as com import time def main(): root = tkinter.Tk() frame = ttk.Frame(root, padding=10) frame.grid() # ------------------------------------------------------------------------- # This example puts the widgets in a 3-column, 2-row grid # with some of the grid-places empty. Here are the WIDGETS: # ------------------------------------------------------------------------- label = ttk.Label(frame, text="movement") entry_box = ttk.Entry(frame) entry_box2 = ttk.Entry(frame) button1 = ttk.Button(frame, text="forward") button1['command'] = (lambda: send_it(entry_box,entry_box2)) # ------------------------------------------------------------------------- # Here is the use of GRID with rows and columns: # ------------------------------------------------------------------------- label.grid(row=0, column=0) entry_box.grid(row=1, column=0) entry_box2.grid(row=1,column=1) button1.grid(row=0, column=1) root.mainloop() def send_it(x,y): mqtt_client = com.MqttClient() mqtt_client.connect('Kirk', 'Preston') time.sleep(1) # Time to allow the MQTT setup. mqtt_client.send_message('handle_forward',[x.get(),y.get()]) print() main()
f9ba449c88b528d2f9faa0d1050ccdb2e822ced6
rangera-manoj/IMDB-Movie-Review-Sentiment-Analysis
/clean_function.py
585
3.515625
4
def clean_text(texts): import re import nltk from nltk.corpus import stopwords nltk.download('stopwords') from nltk.stem import SnowballStemmer stop_words = stopwords.words('english') stemmer = SnowballStemmer('english') clean_review = [] for i in range(len(texts)): review = re.sub('[^a-zA-Z]', ' ', texts.iloc[i]) review = review.lower().split() review = [stemmer.stem(word) for word in review if not word in stop_words] review = " ". join(review) clean_review.append(review) return clean_review
98fd8ea6474f1df8529eaa3d12ec3d5543308214
vivekworks/learning-to-code
/4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 1/exercise417.py
1,567
3.640625
4
""" Purpose : Perform all the sections under 4.1.7 Author : Vivek T S Date : 29/10/2018 DCS, Python introduction """ def section1a(): """ Description: Print even integers from 2 to 100 Parameters: None Return value: None """ for even in range(2, 100, 2): print(even) def section2b(): """ Description: Print odd integers from 1 to 100 Parameters: None Return value: None """ for odd in range(1, 100, 2): print(odd) def section3c(): """ Description: Print integers from 1 to 100 in descending order Parameters: None Return value: None """ for desc in range(100, 0, -1): print(desc) def section4d(): """ Description: Print values 7, 11, 15, 19 Parameters: None Return value: None """ for value in range(7, 20, 4): print(value) def section5e(): """ Description: Print values 2, 1, 0, -1, -2 Parameters: None Return value: None """ for value in range(2, -3, -1): print(value) def section6f(): """ Description: Print values -7, -11, -15, -19 Parameters: None Return value: None """ for value in range(-7, -20, -4): print(value) def main(): """ Description: Perform all the sections under 4.1.7 Parameters: None Return value: None """ print('Section 1a') section1a() print('Section 2b') section2b() print('Section 3c') section3c() print('Section 4d') section4d() print('Section 5e') section5e() print('Section 6f') section6f() main() #Main Function Call
7320f1de5f6a04875d056e65cb499248b357f84b
sgiann/sleeplight
/flash_led_blink_thread_class.py
884
3.84375
4
import threading import time #param list #name : Give as name the colour of the LED to be handled. #pin_number - The pin number that the LED is hooked at. #dtime_mins - Give the desired time in minutes that you want the led to blink for. class LEDThreadStill(threading.Thread): def __init__(self, name, pin_number, dtime_mins) threading.Thread._init__(self) self.name = name self.pin_number = pin_number self.dtime_mins = dtime_mins #the main funciton f this class #will blink the LED on for dtime mins. def run(self): print "Thread start. Name:", self.name, " - blink. time:" ,datetime.datetime.now.time() #blink while true if time.time()>timeout: break #end of while print "Thread end. Name:", self.name, " time:" ,datetime.datetime.now.time()
c942a89886a06b9fd38c1ccce5c1d2f33d2bb496
clefego/python-codes
/lista5.py
217
3.625
4
teste = list() teste.append('Cleyton') teste.append(40) turma = list() turma.append(teste[:]) teste[0] = 'Lianne' teste[1] = 22 turma.append(teste[:]) print(turma) print(turma[0]) print(turma[0][0]) print(turma[0][1])
a7f85a8a4ed7affe287449bd085c7bd10509149f
IrisDyr/demo
/Week 1/H1 Exercise 1.py
813
4.1875
4
def adding(x,y): #sum return x + y def substracting(x,y): #substraction return x - y def divide(x,y): #division return x / y def multiplication(x, y): #multiplication return x * y num1 = int(input("Input the first number ")) #inputing values num2 = int(input("Input the second number ")) acti = int(input("What would you like to do? 1.Add 2.Substract 3.Divide 4. Multiplication ")) # choosing what to do with the numbers inputed if acti == 1: #telling the calculator which function to execute print(num1,"+",num2,"=", adding(num1,num2)) elif acti == 2: print(num1,"-",num2,"=", substracting(num1,num2)) elif acti == 3: print(num1,"/",num2,"=", divide(num1,num2)) else: print(num1,"*",num2,"=", multiplication(num1,num2))
9cc746277adbc8f47323a39f386d3966eaa5ea73
spnarkdnark/i_be_learnin
/algorithm_file.py
1,786
3.84375
4
import math import random #insertionsort array1 = [1,5,3,7,9,5,6,9,23,5,57,83,100] def get_array(size): return [random.randint(1,101) for i in range(0,size)] def insertion_sort(array): for i in range(1,len(array)): for j in range(i-1,-1,-1): if array[j] > array[j+1]: array[j],array[j+1] = array[j+1],array[j] else: break print(array) def optomized_insertion_sort(array): for i in range(1,len(array)): curnum = array[i] for j in range(i-1,-1,-1): if array[j] > curnum: array[j+1] = array[j] array[j] = curnum else: array[j+1] = curnum break print(array) def textbook_insertion(array): for j in range(1,len(array)): curnum = array[j] i = j-1 while i>=0 and array[i] > curnum: array[i+1] = array[i] i -= 1 array[i+1] = curnum print(array) def bottomsort(t): for j in range(len(t) - 1, -1, -1): currow = t[j] for i in range(0, len(currow) - 1): m = max(currow[i], currow[i + 1]) t[j - 1][i] = t[j - 1][i] + m return currow def linearsearch(A,v): for i in range(0,len(A)): if A[i] == v: return i+1 break return 0 graph = {} graph['start'] = {} graph['start']['a'] = 6 graph['start']['b'] = 2 graph['a'] = {} graph['a']['fin'] = 1 graph['b'] = {} graph['b']['a'] = 3 graph['b']['fin'] = 5 graph['fin'] = {} print(graph) infinity = float("inf") costs = {} costs["a"] = 6 costs["b"] = 2 costs["fin"] = infinity parents = {} parents['a'] = 'start' parents['b'] = 'start' parents['fin'] = None print(parents) processed = []
347a62ca6b2709120f8b7dbd7555f6b1c4ad34ad
vanimirafra/python
/decotaror.py
267
3.71875
4
def decorator(func): def inner(*args,**kwargs): return 10 * func(*args, **kwargs) return inner @decorator def adder(x,y,z): return x + y + z x=int(input("enter number")) y=int(input("enter number")) z=int(input("enter number")) print(adder(x,y,z))
1eadf7c4a817267735a6647b319dd8e9bf14a83c
vztpv/Python-Study
/Chapter4/py011.py
416
3.703125
4
# 4 - 2 Problem 1, 2, 3, 4 input1 = int(input("first number")) input2 = int(input("second number")) total = input1 + input2 print("sum is {}".format(total)) str = input("numbers") numbers = str.split(',') print(numbers) sum = 0 for x in numbers: sum += int(x) print(sum) print("you", "need", "python") num = int(input("number ")) for i in range(1,10): print(num * i, end=' ')
727a32830e17711c132ee0724af6222e6045792e
malgorzata-kozera/Web-Crawler
/web_crawler.py
3,152
3.515625
4
import requests from bs4 import BeautifulSoup as bs from requests.exceptions import InvalidSchema, ConnectionError,MissingSchema import sys def site_map(enter_url): ''' Function takes as an argument site base url path (including 'http://') and returns mapping of that domain as a Python dictionary: key: URL * value: dictionary with: ** site title (HTML `<title>` tag) ** links - set of all target URLs within the domain on the page but without anchor links ''' print('New site map is being created, it may takes a while, if it is a big website, please wait') # if given url end with '/' strips it (it prevent double "//"). if enter_url.endswith('/'): enter_url = enter_url.strip('/') dictionary = {} url_to_do = {enter_url} while url_to_do: url_base = enter_url url = url_to_do.pop() if url not in dictionary.keys(): # takes content of the website try: r = requests.get(url) content = r.content soup = bs(content, 'html.parser') # empty set with all links from the website links = set() # searches for title title = soup.find_all('title')[0] title_text = title.text # searches for all links inside this website # adding base url to the link name when there is not # takes only url of the domain (excluding external links) for item in soup.find_all('a', href=True): single_link = item['href'] if url_base in single_link: links.add(single_link) url_to_do.add(single_link) elif single_link.startswith('/'): link_ad_base_url = "".join([url_base, single_link]) links.add(link_ad_base_url) url_to_do.add(link_ad_base_url) # creates a dictionary which is a map of the domain, with new keys and values dictionary[url] = {'title': title_text, 'links': links} except InvalidSchema as e: print(e, file=sys.stderr) print("Check once again whether you entered correct domain url (it should include 'http://').") exit() except ConnectionError as e: print(e, file=sys.stderr) print("Failed to establish a new connection. Check once again whether you enter correct domain url.") exit() except MissingSchema as e: print(e, file=sys.stderr) print("Map can't be created. Check once again whether you entered correct domain url (it should include 'http://').") exit() return dictionary if __name__ == '__main__': enter_url = input("Please enter a URL (including 'http://'). Then You will receive a map of that domain:\n") print(site_map(enter_url))
618a9b3ee816b2c346c57f764953431406cc66c2
stravajiaxen/project-euler-solutions
/project-euler-solutions/p22/euler22.py
1,379
3.671875
4
""" Copyright Matt DeMartino (Stravajiaxen) Licensed under MIT License -- do whatever you want with this, just don't sue me! This code attempts to solve Project Euler (projecteuler.net) Problem #22 Names scores Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938x53 = 49714. What is the total of all the name scores in the file? """ import time def name_score(i, name): tot = 0 for c in name: val = ord(c) - ord('A') + 1 tot += val return (i * tot) def main(): fname = "p022_names.txt" with open(fname, 'r') as f: content = f.read() names = content.split(",") names = [name.strip('"') for name in names] names = sorted(names) tot = 0 for i, name in enumerate(names): tot += name_score(i+1, name) print(tot) if __name__ == "__main__": start_time = time.time() main() elapsed_time = time.time() - start_time print("Elapsed Time: ", elapsed_time)
91b149ac8f16f788e985b65265a479384d1e2d44
ravenusmc/trail
/merchant.py
2,644
4
4
from valid import * #I created this merchant class to help solve some problems that I was having wih the store file. #So far, it seems to help solve my problems as well as to increase my understanding of OOP. The methods #in this file may be long but they got the job done and help me solve my issue! class Merchant(): #This method introduces the player to the traveling merchant. def travelingMerchant(self, wagon, leader): print("\033c") print("{__________________________________}") print("Hello, I am the travelling Merchant.") print("Luckily you found me on your journey! I can fix you up with what you need: ") print(" - A team of oxen to pull your wagon") print(" - Clothing for both summer and winter") print(" - Plenty of food for the trip") print(" - Spare parts for your wagon") input("Press enter to continue ") #This method allows the player to buy certain items from the traveling merchant. def MerchantMain(self, wagon, leader): print("\033c") print("So, Say, what would you nice folks like?") print("You may only choose one option and I may not be back soon!") print("1. Food") print("2. Wheel") print("3. Axle") choice = int(input("What is your choice? ")) while not merchantClassValid(choice): print("That is not a valid selection!") choice = int(input("What is your choice? ")) if choice == 1: print("Food is .50 cents per pound!") amount = int(input("How much food y'all want? ")) while merchantPriceValid(amount): print("The value cannot be below 0") amount = int(input("How much food y'all want? ")) total = amount * .50 leader.money = leader.money - total wagon.food = wagon.food + amount print("Thank you for your business!") elif choice == 2: print("Wheels are 20 each!") amount = int(input("How many wheels y'all want? ")) while merchantPriceValid(amount): print("The value cannot be below 0") amount = int(input("How many wheels y'all want? ")) total = amount * 20 leader.money = leader.money - total wagon.wheel = wagon.wheel + amount print("Thank you for your business!") elif choice == 3: print("Axles are 20 each!") amount = int(input("How many axles y'all want? ")) while merchantPriceValid(amount): print("The value cannot be below 0") amount = int(input("How many axles y'all want? ")) total = amount * 20 leader.money = leader.money - total wagon.axle = wagon.axle + amount print("Thank you for your business!")
1d47ead26cde42113bc511cfa05c6a97468c0ff2
47AnasAhmed/LAB-05
/LAB5_PROGRAMMING EX01.py
670
3.921875
4
print("Anas Ahmed(18b-116-cs),CS-A") print('Lab No.5') print('Programming Ex#1') def area(): import math radius = eval(input('enter value of radius= ' )) height = eval(input('enter value for height= ')) area = (2*math.pi*radius*height) + (2*math.pi*radius**2) print('The area of the cylinder is {0:{1}f}cm\u00b2'.format(area,height)) def volume(): import math radius2= eval(input('enter value of radius for calculating volume= ')) height2= eval(input('enter value of height for calculating volume= ')) volume = (math.pi*radius2**2*height2) print("The volume of the cylinder is {0:{1}f}cm\u00b3".format(volume,height2))
8ff1dd1a0ebd849ef3272208c41bc7be546e7622
sukantanath/ds_hr
/listComprehension.py
559
3.953125
4
#You are given three integers x,y,z representing the dimensions of a cuboid along with an integer n. #Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of (i+j+k) is not equal to n. # Here, 0< i < x, 0 < j < y ,0 < k < z. Please use list comprehensions rather than multiple loops. if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) res_list = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != n ] print(res_list)
7a2c1348dab1bad21d6a53dfc0d5aee5aaf5ad6f
snickersbarr/python
/python_2.7/LPTHW/exercise9.py
504
4.1875
4
#!/usr/bin/python ### Exercise 9 ### ### Printing, Printing, Printing ### # Example of using \n for new lines days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print "Here are the days: ", days print "Here are the months: ", months # Example of how to print multiple lines in a row iwth triple double-quotes print """ There's something going on here. With the three double-quotes We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """
e9a7ce839868dc801fa4189cfae790ca003157db
rainandwind1/Leetcode
/mi_3.py
257
4.03125
4
def isPowerOfThree(n): if n == 0: print(False) if n == 1.0: print(True) return True if n%3 == 0: n = n/3 #print(n) isPowerOfThree(n) if n%3 != 0: return False print(isPowerOfThree(27))
f86a110ac1c8b2b262810bbc15cdf4550b45137b
Kumar72/PyBasics
/tictactoe.py
2,178
4.28125
4
# MILESTONE PROJECT 1: Tic Tac Toe Game # Build the Visual Representation # Get the User Input # Applying the logic for each input # Update Visual row1 = [] row2 = [] row3 = [] def play_game(): game_on = True # Welcome to the game message, Enter Player Name, Scores, etc. configure_game_options() # Initialize a blank board create_blank_board() # Create a loop with Board Display, Player Prompt while game_on: display_board() prompt_player_input() game_on = False # def configure_game_options(): mode = display_menu() if mode == 1: # 1 v Computer -- Todo: add ML to play the game (Stretch Goal) assign_x_and_o(p1_vs_comp()) elif mode == 2: # Get Player input and assign them to X or O based on assign_x_and_o(p1_vs_p2()) elif mode == 9: quit() def p1_vs_comp(): p1 = input('Enter Your Name: ') def p1_vs_p2(): p1 = input('Enter Player 1 Name: ') p2 = input('Enter Player 2 Name: ') return {p1: 'X', p2: 'O'} def assign_x_and_o(players): print(players) def display_board(): print(row1) print(row2) print(row3) def create_blank_board(): global row1, row2, row3 row1 = ['1', '2', '3'] row2 = ['4', '5', '6'] row3 = ['9', '8', '9'] def prompt_player_input(): result = int(input('Select your square: ')) def display_menu(): if row1 == row2 == row3: print('|****** Tic-Tac-Toe ******|') print('\n') print('Please select which mode you would like to participate in.') print('1. Self vs Bot (ML in Action)') print('2. Player 1 vs Player 2') else: print('What would you like to do next?') print('1. Self vs Bot (ML in Action)') print('2. New Player 1 vs Player 2 game') print('3. Play Again with no changes') print('4. Play Again but switch X and O') print('5. Select new symbols for each player') print('6. Reset Player Scores to 0') print('7. Change Player Names') print('8. All configurations at once') print('9. Quit Game') return int(input('Game Mode: ')) play_game()
5a2141f2850142672f7a6e4318fe9aa383a7f511
runzezhang/Code-NoteBook
/lintcode/0608-two-sum-ii-input-array-is-sorted.py
1,335
4.09375
4
# Description # 中文 # English # Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. # The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. # You may assume that each input would have exactly one solution. # Have you met this question in a real interview? # Example # Example 1: # Input: nums = [2, 7, 11, 15], target = 9 # Output: [1, 2] # Example 2: # Input: nums = [2,3], target = 5 # Output: [1, 2] class Solution: """ @param nums: an array of Integer @param target: target = nums[index1] + nums[index2] @return: [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, nums, target): # write your code here if nums is None or len(nums) == 0: return -1 if target is None: return -1 start = 0 end = len(nums) - 1 while start < end: if nums[start] + nums[end] == target: return [start + 1, end + 1] elif nums[start] + nums[end] < target: start += 1 else: end -= 1 return -1
498a4211105e2865d5fc812fb58b99b73c047115
Abdiramen/Euler
/python/finished/p10/problem10.py
326
3.90625
4
#!/usr/bin/env python3 from math import sqrt def primes(): prime = 1 while True: prime += 2 if all(prime % i for i in range(2, int(sqrt(prime)+1))): yield prime total = 2 for i in primes(): print(i) if i > 2000000: break total += i print("total: {}".format(total))
6f493c7353bc8e3ab89835143fc6752dfeb0ee54
savfod/d16
/agekht/7/koh.py
486
3.734375
4
import turtle import tkinter turtle.speed('fastest') def qwe(a1, a2, a3): if a1 > 0: qwe(a1 - 1, a2 / 3, a3) turtle.right(a3) qwe(a1 - 1, a2 / 3, a3) turtle.left(a3 * 2) qwe(a1 - 1, a2 / 3, a3) turtle.right(a3) qwe(a1 - 1, a2 / 3, a3) if a1 == 0: turtle.forward(a2) def rty(a1, a2): qwe(a1, a2, 60) turtle.left(120) qwe(a1, a2, 60) turtle.left(120) qwe(a1, a2, 60) turtle.backward(200) turtle.right(90) turtle.forward(50) turtle.left(90) rty(2, 400) input()
91aa63fbf1b6c39b18fad3e413a2b6bdd1bf3bfd
TheJulius/python_back_end
/python3oo2/modelo.py
2,293
3.6875
4
class Programa: def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @property # metodo get def likes(self): return self._likes def dar_likes(self): self._likes += 1 @property # metodo get def nome(self): return self._nome @nome.setter def nome(self, novo_nome): self._nome = novo_nome.title() def __str__(self): # metodo de imprimir return f"{self.nome} - {self.ano} - {self.likes} Likes" class Filme(Programa): def __init__(self, nome, ano, duracao): super().__init__(nome, ano) self.duracao = duracao def __str__(self): return f"{self.nome} - {self.ano} - {self.duracao} min- {self.likes} likes" class Serie(Programa): def __init__(self, nome, ano, temporadas): super().__init__(nome, ano) self.temporadas = temporadas def __str__(self): return f"{self.nome} - {self.ano} - {self.temporadas} temporadas - {self.likes} likes" class Playlist: def __init__(self, nome, programas): self.nome = nome self._programas = programas def __getitem__(self, item): return self._programas[item] def __len__(self): return len(self.programas) @property def listagem(self): return self._programas from modelo import Filme, Serie vingadores = Filme("vingadores - guerra infinita", 2018, 160) vingadores1 = Filme("vingadores1 - guerra infinita", 2017, 100) vingadores2 = Filme("vingadores2 - guerra infinita", 2016, 120) atlanta = Serie("atlanta", 2018, 1) atlanta1 = Serie("atlanta1", 2019, 2) atlanta2 = Serie("atlanta2", 2012, 3) vingadores.dar_likes() vingadores1.dar_likes() vingadores1.dar_likes() vingadores1.dar_likes() vingadores2.dar_likes() atlanta.dar_likes() atlanta1.dar_likes() atlanta2.dar_likes() atlanta2.dar_likes() filmes_e_series = [vingadores, vingadores1, vingadores2, atlanta, atlanta1, atlanta2] playlist_fim_de_semana = Playlist("fim_de_semana", filmes_e_series) ##Criando Objeto da classe PLAYLIST que tem todas as funcoes da classe e talz print(f"Tamanho da Playlist {len(playlist_fim_de_semana)}") for programa in playlist_fim_de_semana: print(programa)
7b33fcced160331a2fcd001a422f6a6411a99f3b
oneoffcoder/books
/sphinx/python-intro/source/code/oneoffcoder/loop/foreachzip.py
109
3.890625
4
names = ['Jack', 'John', 'Joe'] ages = [18, 19, 20] for name, age in zip(names, ages): print(name, age)
03ffdab1e4e37a38880b0ef02fc1262f7749859b
CheshireCat12/hackerrank
/ai/bot_clean_large.py
1,302
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 1 11:24:00 2019 @author: cheshirecat12 """ DIRTY_CELL = "d" def manhattan_dist(pos_bot, pos_dirt): return sum(abs(pos_b-pos_d) for pos_b, pos_d in zip(pos_bot, pos_dirt)) def next_move(pos_y, pos_x, dimx, dimy, boar): # Check if the bot is on a dirty cell if board[pos_y][pos_x] == DIRTY_CELL: return "CLEAN" dirty_cells = [(j, i) for i, row in enumerate(board) for j, cell in enumerate(row) if cell == DIRTY_CELL] bot = (pos_x, pos_y) closest_cell = (float("INF"), None) for cell in dirty_cells: current_dist = manhattan_dist(bot, cell) if current_dist < closest_cell[0]: closest_cell = (current_dist, cell) _, (cell_x, cell_y) = closest_cell if cell_y > pos_y: return "DOWN" elif cell_y < pos_y: return "UP" elif cell_x > pos_x: return "RIGHT" else: return "LEFT" # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] dim = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(dim[0])] print(next_move(pos[0], pos[1], dim[0], dim[1], board))
c6bdf025b51ccde7f462d0889f78dee44e67fc30
helenros/python2017
/two.py
537
4.125
4
#Input an array of n numbers and find separately the sum of positive numbers and negative numbers int_arr =list() totnum=input("Enter how many elements you want : ") print 'Enter the numbers in array : ' for i in range(int(totnum)): n=input("Number : ") int_arr.append(int(n)) print 'Entered Array : ', int_arr pos_sum=0; neg_sum=0; for i in int_arr: if i>0: pos_sum=pos_sum + i; else: neg_sum=neg_sum + i; print ("Sum of Positive numbers : "+str(pos_sum)) print ("Sum of Negative numbers : "+str(neg_sum))
ada12eff354cf602924f03a19a48f18b9a3278e3
MJZ-98/data_mining
/capsnet.py
35,540
3.765625
4
import keras.backend as K import tensorflow as tf from keras import initializers, layers class Length(layers.Layer): """ Compute the length of vectors. This is used to compute a Tensor that has the same shape with y_true in margin_loss. Using this layer as model's output can directly predict labels by using `y_pred = np.argmax(model.predict(x), 1)` inputs: shape=[None, num_vectors, dim_vector] output: shape=[None, num_vectors] """ def call(self, inputs, **kwargs): return K.sqrt(K.sum(K.square(inputs), -1)) def compute_output_shape(self, input_shape): return input_shape[:-1] def get_config(self): config = super(Length, self).get_config() return config class Mask(layers.Layer): """ Mask a Tensor with shape=[None, num_capsule, dim_vector] either by the capsule with max length or by an additional input mask. Except the max-length capsule (or specified capsule), all vectors are masked to zeros. Then flatten the masked Tensor. For example: ``` x = keras.layers.Input(shape=[8, 3, 2]) # batch_size=8, each sample contains 3 capsules with dim_vector=2 y = keras.layers.Input(shape=[8, 3]) # True labels. 8 samples, 3 classes, one-hot coding. out = Mask()(x) # out.shape=[8, 6] # or out2 = Mask()([x, y]) # out2.shape=[8,6]. Masked with true labels y. Of course y can also be manipulated. ``` """ def call(self, inputs, **kwargs): if type(inputs) is list: assert len(inputs) == 2 inputs, mask = inputs else: x = K.sqrt(K.sum(K.square(inputs), -1)) mask = K.one_hot(indices=K.argmax(x, 1), num_classes=x.get_shape().as_list()[1]) masked = K.batch_flatten(inputs * K.expand_dims(mask, -1)) return masked def compute_output_shape(self, input_shape): if type(input_shape[0]) is tuple: return tuple([None, input_shape[0][1] * input_shape[0][2]]) else: return tuple([None, input_shape[1] * input_shape[2]]) def get_config(self): config = super(Mask, self).get_config() return config def squash(vectors, axis=-1): """ The non-linear activation used in Capsule. It drives the length of a large vector to near 1 and small vector to 0 :param vectors: some vectors to be squashed, N-dim tensor :param axis: the axis to squash :return: a Tensor with same shape as input vectors """ s_squared_norm = K.sum(K.square(vectors), axis, keepdims=True) scale = s_squared_norm / (1 + s_squared_norm) / K.sqrt(s_squared_norm + K.epsilon()) return scale * vectors class CapsuleLayer(layers.Layer): """ The capsule layer. It is similar to Dense layer. Dense layer has `in_num` inputs, each is a scalar, the output of the neuron from the former layer, and it has `out_num` output neurons. CapsuleLayer just expand the output of the neuron from scalar to vector. So its input shape = [None, input_num_capsule, input_dim_capsule] and output shape = \ [None, num_capsule, dim_capsule]. For Dense Layer, input_dim_capsule = dim_capsule = 1. :param num_capsule: number of capsules in this layer :param dim_capsule: dimension of the output vectors of the capsules in this layer :param routings: number of iterations for the routing algorithm """ def __init__(self, num_capsule, dim_capsule,channels, routings=3, kernel_initializer='glorot_uniform', **kwargs): super(CapsuleLayer, self).__init__(**kwargs) self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.channels = channels self.kernel_initializer = initializers.get(kernel_initializer) def build(self, input_shape): assert len(input_shape) >= 3, "The input Tensor should have shape=[None, input_num_capsule, input_dim_capsule]" self.input_num_capsule = input_shape[1] self.input_dim_capsule = input_shape[2] if(self.channels!=0): assert int(self.input_num_capsule/self.channels)/(self.input_num_capsule/self.channels)==1, "error" self.W = self.add_weight(shape=[self.num_capsule, self.channels, self.dim_capsule, self.input_dim_capsule], initializer=self.kernel_initializer, name='W') self.B = self.add_weight(shape=[self.num_capsule,self.dim_capsule], initializer=self.kernel_initializer, name='B') else: self.W = self.add_weight(shape=[self.num_capsule, self.input_num_capsule, self.dim_capsule, self.input_dim_capsule], initializer=self.kernel_initializer, name='W') self.B = self.add_weight(shape=[self.num_capsule,self.dim_capsule], initializer=self.kernel_initializer, name='B') self.built = True def call(self, inputs, training=None): inputs_expand = K.expand_dims(inputs, 1) inputs_tiled = K.tile(inputs_expand, [1, self.num_capsule, 1, 1]) if(self.channels!=0): W2 = K.repeat_elements(self.W,int(self.input_num_capsule/self.channels),1) else: W2 = self.W inputs_hat = K.map_fn(lambda x: K.batch_dot(x, W2, [2, 3]) , elems=inputs_tiled) b = tf.zeros(shape=[K.shape(inputs_hat)[0], self.num_capsule, self.input_num_capsule]) assert self.routings > 0, 'The routings should be > 0.' for i in range(self.routings): c = tf.nn.softmax(b, dim=1) outputs = squash(K.batch_dot(c, inputs_hat, [2, 2])+ self.B) if i < self.routings - 1: b += K.batch_dot(outputs, inputs_hat, [2, 3]) return outputs def compute_output_shape(self, input_shape): return tuple([None, self.num_capsule, self.dim_capsule]) def PrimaryCap(inputs, dim_capsule, n_channels, kernel_size, strides, padding): """ Apply Conv2D `n_channels` times and concatenate all capsules :param inputs: 4D tensor, shape=[None, width, height, channels] :param dim_capsule: the dim of the output vector of capsule :param n_channels: the number of types of capsules :return: output tensor, shape=[None, num_capsule, dim_capsule] """ output = layers.Conv2D(filters=dim_capsule*n_channels, kernel_size=kernel_size, strides=strides, padding=padding, name='primarycap_conv2d')(inputs) outputs = layers.Reshape(target_shape=[-1, dim_capsule], name='primarycap_reshape')(output) return layers.Lambda(squash, name='primarycap_squash')(outputs) import keras.callbacks as callbacks from keras.callbacks import Callback import numpy as np import os class SnapshotModelCheckpoint(Callback): """Callback that saves the snapshot weights of the model. Saves the model weights on certain epochs (which can be considered the snapshot of the model at that epoch). Should be used with the cosine annealing learning rate schedule to save the weight just before learning rate is sharply increased. # Arguments: nb_epochs: total number of epochs that the model will be trained for. nb_snapshots: number of times the weights of the model will be saved. fn_prefix: prefix for the filename of the weights. """ def __init__(self, nb_epochs, nb_snapshots, fn_prefix='Model'): super(SnapshotModelCheckpoint, self).__init__() self.check = nb_epochs // nb_snapshots self.fn_prefix = fn_prefix def on_epoch_end(self, epoch, logs={}): if epoch != 0 and (epoch + 1) % self.check == 0: filepath = self.fn_prefix + "-%d.h5" % ((epoch + 1) // self.check) self.model.save(filepath, overwrite=True) class SnapshotCallbackBuilder: """Callback builder for snapshot ensemble training of a model. Creates a list of callbacks, which are provided when training a model so as to save the model weights at certain epochs, and then sharply increase the learning rate. """ def __init__(self, nb_epochs, nb_snapshots, init_lr, save_dir): """ Initialize a snapshot callback builder. # Arguments: nb_epochs: total number of epochs that the model will be trained for. nb_snapshots: number of times the weights of the model will be saved. init_lr: initial learning rate """ self.T = nb_epochs self.M = nb_snapshots self.alpha_zero = init_lr self.save_dir = save_dir def get_callbacks(self,log, model_prefix='Model'): """ Creates a list of callbacks that can be used during training to create a snapshot ensemble of the model. Args: model_prefix: prefix for the filename of the weights. Returns: list of 3 callbacks [ModelCheckpoint, LearningRateScheduler, SnapshotModelCheckpoint] which can be provided to the 'fit' function """ if not os.path.exists(self.save_dir+'/weights/'): os.makedirs(self.save_dir+'/weights/') callback_list = [callbacks.ModelCheckpoint(self.save_dir+"/weights/weights_{epoch:002d}.h5", monitor="val_capsnet_acc", save_best_only=True, save_weights_only=False), callbacks.LearningRateScheduler(schedule=self._cosine_anneal_schedule), SnapshotModelCheckpoint(self.T, self.M, fn_prefix=self.save_dir+'/weights/%s' % model_prefix), log] return callback_list def _cosine_anneal_schedule(self, t): cos_inner = np.pi * (t % (self.T // self.M)) # t - 1 is used when t has 1-based indexing. cos_inner /= self.T // self.M cos_out = np.cos(cos_inner) + 1 return float(self.alpha_zero / 2 * cos_out) import keras from keras import layers, models, optimizers from keras import backend as K from keras.utils import to_categorical from keras.layers import Dense, Reshape from keras.layers.core import Activation, Flatten from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import UpSampling2D, Conv2D, MaxPooling2D from keras.preprocessing.image import ImageDataGenerator from keras import callbacks from keras.utils.vis_utils import plot_model from utils import combine_images, load_emnist_balanced from PIL import Image, ImageFilter from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask from snapshot import SnapshotCallbackBuilder import os import numpy as np import tensorflow as tf import os import argparse # ---------------------- # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' K.set_image_data_format('channels_last') """ Switching the GPU to allow growth """ config = tf.ConfigProto() config.gpu_options.allow_growth=True sess = tf.Session(config=config) K.set_session(sess) def CapsNet(input_shape, n_class, routings): """ Defining the CapsNet :param input_shape: data shape, 3d, [width, height, channels] :param n_class: number of classes :param routings: number of routing iterations :return: Two Keras Models, the first one used for training, and the second one for evaluation. """ x = layers.Input(shape=input_shape) conv1 = layers.Conv2D(filters=64, kernel_size=3, strides=1, padding='valid', activation='relu', name='conv1')(x) conv2 = layers.Conv2D(filters=128, kernel_size=3, strides=1, padding='valid', activation='relu', name='conv2')(conv1) conv3 = layers.Conv2D(filters=256, kernel_size=3, strides=2, padding='valid', activation='relu', name='conv3')(conv2) primarycaps = PrimaryCap(conv3, dim_capsule=8, n_channels=32, kernel_size=9, strides=2, padding='valid') digitcaps = CapsuleLayer(num_capsule=n_class, dim_capsule=16, routings=routings,channels=32,name='digitcaps')(primarycaps) out_caps = Length(name='capsnet')(digitcaps) """ Decoder Network """ y = layers.Input(shape=(n_class,)) masked_by_y = Mask()([digitcaps, y]) masked = Mask()(digitcaps) C=input_shape[2] decoder = models.Sequential(name='decoder') decoder.add(Dense(input_dim=16*n_class, activation="relu", output_dim=7*7*32*C)) decoder.add(Reshape((7, 7, 32*C))) decoder.add(BatchNormalization(momentum=0.8)) decoder.add(layers.Deconvolution2D(32*C, 3, 3,subsample=(1, 1),border_mode='same', activation="relu")) decoder.add(layers.Deconvolution2D(16*C, 3, 3,subsample=(2, 2),border_mode='same', activation="relu")) decoder.add(layers.Deconvolution2D(8*C, 3, 3,subsample=(2, 2),border_mode='same', activation="relu")) decoder.add(layers.Deconvolution2D(4*C, 3, 3,subsample=(1, 1),border_mode='same', activation="relu")) decoder.add(layers.Deconvolution2D(1*C, 3, 3,subsample=(1, 1),border_mode='same', activation="sigmoid")) decoder.add(layers.Reshape(target_shape=input_shape, name='out_recon')) """ Models for training and evaluation (prediction) """ train_model = models.Model([x, y], [out_caps, decoder(masked_by_y)]) eval_model = models.Model(x, [out_caps, decoder(masked)]) return train_model, eval_model def margin_loss(y_true, y_pred): """ Marginal loss used for the CapsNet training :param y_true: [None, n_classes] :param y_pred: [None, num_capsule] :return: a scalar loss value. """ L = y_true * K.square(K.maximum(0., 0.9 - y_pred)) + \ 0.5 * (1 - y_true) * K.square(K.maximum(0., y_pred - 0.1)) return K.mean(K.sum(L, 1)) def train(model, data, args): """ Training a CapsuleNet :param model: the CapsuleNet model :param data: a tuple containing training and testing data, like `((x_train, y_train), (x_test, y_test))` :param args: arguments :return: The trained model """ (x_train, y_train), (x_test, y_test) = data log = callbacks.CSVLogger(args.save_dir + '/log.csv') checkpoint = callbacks.ModelCheckpoint(args.save_dir + '/weights-{epoch:02d}.h5', monitor='val_capsnet_acc', save_best_only=False, save_weights_only=True, verbose=1) lr_decay = callbacks.LearningRateScheduler(schedule=lambda epoch: args.lr * (args.lr_decay ** epoch)) model.compile(optimizer=optimizers.Adam(lr=args.lr), loss=[margin_loss, 'mse'], loss_weights=[1., args.lam_recon], metrics={'capsnet': 'accuracy'}) def train_generator(x, y, batch_size, shift_fraction=0.): train_datagen = ImageDataGenerator(width_shift_range=shift_fraction, height_shift_range=shift_fraction) generator = train_datagen.flow(x, y, batch_size=batch_size) while 1: x_batch, y_batch = generator.next() yield ([x_batch, y_batch], [y_batch, x_batch]) model.fit_generator(generator=train_generator(x_train, y_train, args.batch_size, args.shift_fraction), steps_per_epoch=int(y_train.shape[0] / args.batch_size), epochs=args.epochs, shuffle = True, validation_data=[[x_test, y_test], [y_test, x_test]], callbacks=snapshot.get_callbacks(log,model_prefix=model_prefix)) model.save_weights(args.save_dir + '/trained_model.h5') print('Trained model saved to \'%s/trained_model.h5\'' % args.save_dir) return model def test(model, data, args): """ Testing the trained CapsuleNet """ x_test, y_test = data y_pred, x_recon = model.predict(x_test, batch_size=args.batch_size*8) print('-'*30 + 'Begin: test' + '-'*30) print('Test acc:', np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1))/float(y_test.shape[0])) class dataGeneration(): def __init__(self, model,data,args,samples_to_generate = 2): """ Generating new images :param model: the pre-trained CapsNet model :param data: a tuple containing training and testing data, like `((x_train, y_train), (x_test, y_test))` :param args: arguments :param samples_to_generate: number of new training samples to generate per class """ self.model = model self.data = data self.args = args self.samples_to_generate = samples_to_generate print("-"*100) (x_train, y_train), (x_test, y_test), x_recon = self.remove_missclassifications() self.data = (x_train, y_train), (x_test, y_test) self.reconstructions = x_recon self.inst_parameter, self.global_position, self.masked_inst_parameter = self.get_inst_parameters() print("Instantiation parameters extracted.") print("-"*100) self.x_decoder_retrain,self.y_decoder_retrain = self.decoder_retraining_dataset() self.retrained_decoder = self.decoder_retraining() print("Decoder re-training completed.") print("-"*100) self.class_variance, self.class_max, self.class_min = self.get_limits() self.generated_images,self.generated_labels = self.generate_data() print("New images of the shape ",self.generated_images.shape," Generated.") print("-"*100) def save_output_image(self,samples,image_name): """ Visualizing and saving images in the .png format :param samples: images to be visualized :param image_name: name of the saved .png file """ if not os.path.exists(args.save_dir+"/images"): os.makedirs(args.save_dir+"/images") img = combine_images(samples) img = img * 255 Image.fromarray(img.astype(np.uint8)).save(args.save_dir + "/images/"+image_name+".png") print(image_name, "Image saved.") def remove_missclassifications(self): """ Removing the wrongly classified samples from the training set. We do not alter the testing set. :return: dataset with miss classified samples removed and the initial reconstructions. """ model = self.model data = self.data args = self.args (x_train, y_train), (x_test, y_test) = data y_pred, x_recon = model.predict(x_train, batch_size=args.batch_size) acc = np.sum(np.argmax(y_pred, 1) == np.argmax(y_train, 1))/y_train.shape[0] cmp = np.argmax(y_pred, 1) == np.argmax(y_train, 1) bin_cmp = np.where(cmp == 0)[0] x_train = np.delete(x_train,bin_cmp,axis=0) y_train = np.delete(y_train,bin_cmp,axis=0) x_recon = np.delete(x_recon,bin_cmp,axis=0) self.save_output_image(x_train[:100],"original training") self.save_output_image(x_recon[:100],"original reconstruction") return (x_train, y_train), (x_test, y_test), x_recon def get_inst_parameters(self): """ Extracting the instantiation parameters for the existing training set :return: instantiation parameters, corresponding labels and the masked instantiation parameters """ model = self.model data = self.data args = self.args (x_train, y_train), (x_test, y_test) = data if not os.path.exists(args.save_dir+"/check"): os.makedirs(args.save_dir+"/check") if not os.path.exists(args.save_dir+"/check/x_inst.npy"): get_digitcaps_output = K.function([model.layers[0].input],[model.get_layer("digitcaps").output]) get_capsnet_output = K.function([model.layers[0].input],[model.get_layer("capsnet").output]) if (x_train.shape[0]%args.num_cls==0): lim = int(x_train.shape[0]/args.num_cls) else: lim = int(x_train.shape[0]/args.num_cls)+1 for t in range(0,lim): if (t==int(x_train.shape[0]/args.num_cls)): mod = x_train.shape[0]%args.num_cls digitcaps_output = get_digitcaps_output([x_train[t*args.num_cls:t*args.num_cls+mod]])[0] capsnet_output = get_capsnet_output([x_train[t*args.num_cls:t*args.num_cls+mod]])[0] else: digitcaps_output = get_digitcaps_output([x_train[t*args.num_cls:(t+1)*args.num_cls]])[0] capsnet_output = get_capsnet_output([x_train[t*args.num_cls:(t+1)*args.num_cls]])[0] masked_inst = [] inst = [] where = [] for j in range(0,digitcaps_output.shape[0]): ind = capsnet_output[j].argmax() inst.append(digitcaps_output[j][ind]) where.append(ind) for z in range(0,args.num_cls): if (z==ind): continue else: digitcaps_output[j][z] = digitcaps_output[j][z].fill(0.0) masked_inst.append(digitcaps_output[j].flatten()) masked_inst = np.asarray(masked_inst) masked_inst[np.isnan(masked_inst)] = 0 inst = np.asarray(inst) where = np.asarray(where) if (t==0): x_inst = np.concatenate([inst]) pos = np.concatenate([where]) x_masked_inst = np.concatenate([masked_inst]) else: x_inst = np.concatenate([x_inst,inst]) pos = np.concatenate([pos,where]) x_masked_inst = np.concatenate([x_masked_inst,masked_inst]) np.save(args.save_dir+"/check/x_inst",x_inst) np.save(args.save_dir+"/check/pos",pos) np.save(args.save_dir+"/check/x_masked_inst",x_masked_inst) else: x_inst = np.load(args.save_dir+"/check/x_inst.npy") pos = np.load(args.save_dir+"/check/pos.npy") x_masked_inst = np.load(args.save_dir+"/check/x_masked_inst.npy") return x_inst,pos,x_masked_inst def decoder_retraining_dataset(self): """ Generating the dataset for the decoder retraining technique with unsharp masking :return: training samples and labels for decoder retraining """ model = self.model data = self.data args = self.args x_recon = self.reconstructions (x_train, y_train), (x_test, y_test) = data if not os.path.exists(args.save_dir+"/check"): os.makedirs(args.save_dir+"/check") if not os.path.exists(args.save_dir+"/check/x_decoder_retrain.npy"): for q in range(0,x_recon.shape[0]): save_img = Image.fromarray((x_recon[q]*255).reshape(28,28).astype(np.uint8)) image_more_sharp = save_img.filter(ImageFilter.UnsharpMask(radius=1, percent=1000, threshold=1)) img_arr = np.asarray(image_more_sharp) img_arr = img_arr.reshape(-1,28,28,1).astype('float32') / 255. if (q==0): x_recon_sharped = np.concatenate([img_arr]) else: x_recon_sharped = np.concatenate([x_recon_sharped,img_arr]) self.save_output_image(x_recon_sharped[:100],"sharpened reconstructions") x_decoder_retrain = self.masked_inst_parameter y_decoder_retrain = x_recon_sharped np.save(args.save_dir+"/check/x_decoder_retrain",x_decoder_retrain) np.save(args.save_dir+"/check/y_decoder_retrain",y_decoder_retrain) else: x_decoder_retrain = np.load(args.save_dir+"/check/x_decoder_retrain.npy") y_decoder_retrain = np.load(args.save_dir+"/check/y_decoder_retrain.npy") return x_decoder_retrain,y_decoder_retrain def decoder_retraining(self): """ The decoder retraining technique to give the sharpening ability to the decoder :return: the retrained decoder """ model = self.model data = self.data args = self.args x_decoder_retrain, y_decoder_retrain = self.x_decoder_retrain,self.y_decoder_retrain decoder = eval_model.get_layer('decoder') decoder_in = layers.Input(shape=(16*47,)) decoder_out = decoder(decoder_in) retrained_decoder = models.Model(decoder_in,decoder_out) if (args.verbose): retrained_decoder.summary() retrained_decoder.compile(optimizer=optimizers.Adam(lr=args.lr),loss='mse',loss_weights=[1.0]) if not os.path.exists(args.save_dir+"/retrained_decoder.h5"): retrained_decoder.fit(x_decoder_retrain, y_decoder_retrain, batch_size=args.batch_size, epochs=20) retrained_decoder.save_weights(args.save_dir + '/retrained_decoder.h5') else: retrained_decoder.load_weights(args.save_dir + '/retrained_decoder.h5') retrained_reconstructions = retrained_decoder.predict(x_decoder_retrain, batch_size=args.batch_size) self.save_output_image(retrained_reconstructions[:100],"retrained reconstructions") return retrained_decoder def get_limits(self): """ Calculating the boundaries of the instantiation parameter distributions :return: instantiation parameter indices in the descending order of variance, min and max values per class """ args = self.args x_inst = self.inst_parameter pos = self.global_position glob_min = np.amin(x_inst.transpose(),axis=1) glob_max = np.amax(x_inst.transpose(),axis=1) if not os.path.exists(args.save_dir+"/check"): os.makedirs(args.save_dir+"/check") if not os.path.exists(args.save_dir+"/check/class_cov.npy"): for cl in range(0,self.args.num_cls): tmp_glob = [] for it in range(0,x_inst.shape[0]): if (pos[it]==cl): tmp_glob.append(x_inst[it]) tmp_glob = np.asarray(tmp_glob) tmp_glob = tmp_glob.transpose() tmp_cov_max = np.flip(np.argsort(np.around(np.cov(tmp_glob),5).diagonal()),axis=0) tmp_min = np.amin(tmp_glob,axis=1) tmp_max = np.amax(tmp_glob,axis=1) if (cl==0): class_cov = np.vstack([tmp_cov_max]) class_min = np.vstack([tmp_min]) class_max = np.vstack([tmp_max]) else: class_cov = np.vstack([class_cov,tmp_cov_max]) class_min = np.vstack([class_min,tmp_min]) class_max = np.vstack([class_max,tmp_max]) np.save(args.save_dir+"/check/class_cov",class_cov) np.save(args.save_dir+"/check/class_min",class_min) np.save(args.save_dir+"/check/class_max",class_max) else: class_cov = np.load(args.save_dir+"/check/class_cov.npy") class_min = np.load(args.save_dir+"/check/class_min.npy") class_max = np.load(args.save_dir+"/check/class_max.npy") return class_cov,class_max,class_min def generate_data(self): """ Generating new images and samples with the data generation technique :return: the newly generated images and labels """ data = self.data args = self.args (x_train, y_train), (x_test, y_test) = data x_masked_inst = self.masked_inst_parameter pos = self.global_position retrained_decoder = self.retrained_decoder class_cov = self.class_variance class_max = self.class_max class_min = self.class_min samples_to_generate = self.samples_to_generate generated_images = np.empty([0,x_train.shape[1],x_train.shape[2],x_train.shape[3]]) generated_images_with_ori = np.empty([0,x_train.shape[1],x_train.shape[2],x_train.shape[3]]) generated_labels = np.empty([0]) for cl in range(0,args.num_cls): count = 0 for it in range(0,x_masked_inst.shape[0]): if (count==samples_to_generate): break if (pos[it]==cl): count = count + 1 generated_images_with_ori = np.concatenate([generated_images_with_ori,x_train[it].reshape(1,x_train.shape[1],x_train.shape[2],x_train.shape[3])]) noise_vec = x_masked_inst[it][x_masked_inst[it].nonzero()] for inst in range(int(class_cov.shape[1]/2)): ind = np.where(class_cov[cl]==inst)[0][0] noise = np.random.uniform(class_min[cl][ind],class_max[cl][ind]) noise_vec[ind] = noise x_masked_inst[it][x_masked_inst[it].nonzero()] = noise_vec new_image = retrained_decoder.predict(x_masked_inst[it].reshape(1,args.num_cls*class_cov.shape[1])) generated_images = np.concatenate([generated_images,new_image]) generated_labels = np.concatenate([generated_labels,np.asarray([cl])]) generated_images_with_ori = np.concatenate([generated_images_with_ori,new_image]) self.save_output_image(generated_images,"generated_images") self.save_output_image(generated_images_with_ori,"generated_images with originals") generated_labels = keras.utils.to_categorical(generated_labels, num_classes=args.num_cls) if not os.path.exists(args.save_dir+"/generated_data"): os.makedirs(args.save_dir+"/generated_data") np.save(args.save_dir+"/generated_data/generated_images",generated_images) np.save(args.save_dir+"/generated_data/generated_label",generated_labels) return generated_images,generated_labels if __name__ == "__main__": """ Setting the hyper-parameters """ parser = argparse.ArgumentParser(description="TextCaps") parser.add_argument('--epochs', default=60, type=int) parser.add_argument('--verbose', default=False, type=bool) parser.add_argument('--cnt', default=200, type=int) parser.add_argument('-n','--num_cls', default=47, type=int, help="Iterations") parser.add_argument('--batch_size', default=32, type=int) parser.add_argument('--samples_to_generate', default=10, type=int) parser.add_argument('--lr', default=0.001, type=float, help="Initial learning rate") parser.add_argument('--lr_decay', default=0.9, type=float, help="The value multiplied by lr at each epoch. Set a larger value for larger epochs") parser.add_argument('--lam_recon', default=0.392, type=float, help="The coefficient for the loss of decoder") parser.add_argument('-r', '--routings', default=3, type=int, help="Number of iterations used in routing algorithm. should > 0") parser.add_argument('--shift_fraction', default=0.1, type=float, help="Fraction of pixels to shift at most in each direction.") parser.add_argument('--save_dir', default='./emnist_bal_200') parser.add_argument('-dg', '--data_generate', action='store_true', help="Generate new data with pre-trained model") parser.add_argument('-w', '--weights', default=None, help="The path of the saved weights. Should be specified when testing") args = parser.parse_args() print(args) if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) (x_train, y_train), (x_test, y_test) = load_emnist_balanced(args.cnt) #(x_train, y_train), (x_test, y_test) = load_my_data(args.cnt) # (x_train, y_train), (x_test, y_test) = load_li_data() print('-------------/n-------------/n-----',(x_train),len(x_test)) model, eval_model = CapsNet(input_shape=x_train.shape[1:], n_class=len(np.unique(np.argmax(y_train, 1))), routings=args.routings) if (args.verbose): model.summary() """ Snap shot training :param M: number of snapshots :param nb_epoch: number of epochs :param alpha_zero: initial learning rate """ M = 3 nb_epoch = T = args.epochs alpha_zero = 0.01 model_prefix = 'Model_' snapshot = SnapshotCallbackBuilder(T, M, alpha_zero,args.save_dir) if args.weights is not None: model.load_weights(args.weights) if not args.data_generate: train(model=model, data=((x_train, y_train), (x_test, y_test)), args=args) test(model=eval_model, data=(x_test, y_test), args=args) else: if args.weights is None: print('No weights are provided. You need to train a model first.') else: data_generator = dataGeneration(model=eval_model, data=((x_train, y_train), (x_test, y_test)), args=args, samples_to_generate = args.samples_to_generate) import numpy as np import math def combine_images(generated_images, height=None, width=None): num = generated_images.shape[0] if width is None and height is None: width = int(math.sqrt(num)) height = int(math.ceil(float(num)/width)) elif width is not None and height is None: # height not given height = int(math.ceil(float(num)/width)) elif height is not None and width is None: # width not given width = int(math.ceil(float(num)/height)) shape = generated_images.shape[1:3] image = np.zeros((height*shape[0], width*shape[1]), dtype=generated_images.dtype) for index, img in enumerate(generated_images): i = int(index/width) j = index % width image[i*shape[0]:(i+1)*shape[0], j*shape[1]:(j+1)*shape[1]] = \ img[:, :, 0] return image def load_emnist_balanced(cnt): from scipy import io as spio from keras.utils import to_categorical import numpy as np emnist = spio.loadmat("data/matlab/emnist-balanced.mat") print(emnist['dataset']) classes = 47 cnt = cnt lim_train = cnt*classes x_train = emnist["dataset"][0][0][0][0][0][0] x_train = x_train.astype(np.float32) y_train = emnist["dataset"][0][0][0][0][0][1] x_test = emnist["dataset"][0][0][1][0][0][0] x_test = x_test.astype(np.float32) y_test = emnist["dataset"][0][0][1][0][0][1] x_train = x_train.reshape(x_train.shape[0], 28, 28, 1, order="A").astype('float32') / 255. x_test = x_test.reshape(x_test.shape[0], 28, 28, 1, order="A").astype('float32') / 255. y_train = (y_train.astype('float32')) y_test = to_categorical(y_test.astype('float32')) #Append equal number of training samples from each class to x_train and y_train x_tr = [] y_tr = [] count = [0] * classes for i in range(0,x_train.shape[0]): if (sum(count)==classes*cnt): break name = (y_train[i]) if (count[int(name)]>=cnt): continue count[int(name)] = count[int(name)]+1 x_tr.append(x_train[i]) y_tr.append(name) x_tr = np.asarray(x_tr) y_tr = np.asarray(y_tr) y_tr = to_categorical(y_tr.astype('float32')) print(x_tr.shape,y_tr.shape,x_test.shape,y_test.shape) return (x_tr, y_tr), (x_test, y_test)
98a08b41ef7c7c4f50a09e60371a143d60b7ff9e
chendingyan/My-Leetcode
/Basics/codes/KMP.py
917
3.546875
4
def gen_pnext(substring): """ 构造临时数组pnext """ index, m = 0, len(substring) pnext = [0]*m i = 1 while i < m: if (substring[i] == substring[index]): pnext[i] = index + 1 index += 1 i += 1 elif (index!=0): index = pnext[index-1] else: pnext[i] = 0 i += 1 return pnext def kmp(string, substring): pnext = gen_pnext(substring) m = len(substring) n = len(string) i , j = 0,0 while i<n and j < m: if string[i] == substring[j]: i+=1 j+=1 elif j!= 0: j = pnext[j-1] else: i+=1 if j == m: return i-j else: return -1 if __name__ == '__main__': string = 'abcxabcdabcdabcy' substring = 'abcdabcy' print(kmp(string, substring)) # print(gen_pnext(substring))
75cfddd299526fa438eff331f8189b60e9cbe86f
zverinec/interlos-web
/public/download/years/2022/reseni/megaBludisko-solution.py
4,555
3.5625
4
from collections import deque from heapq import heappush, heappop DR = [-1, 0, 1, 0] DC = [0, -1, 0, 1] class Vertex: def __init__(self): self.dist = None self.next = [] def bfs(maze, si, sj): if maze[si][sj] == "#": return None r = len(maze) c = len(maze[0]) dist = [[None] * c for i in range(r)] dist[si][sj] = 0 q = deque() q.append((si, sj)) while q: i, j = q.popleft() for dr, dc in zip(DR, DC): i2, j2 = i + dr, j + dc if 0 <= i2 < r and 0 <= j2 < c and maze[i2][j2] != "#" and dist[i2][j2] == None: dist[i2][j2] = dist[i][j] + 1 q.append((i2, j2)) return dist def dijkstra(graph, start): pq = [(0, start)] while pq: dist, v = heappop(pq) if graph[v].dist is not None: continue print(v, "|", dist) graph[v].dist = dist for s, d in graph[v].next: if graph[s].dist is None: heappush(pq, (dist + d, s)) def addEdge(graph, v1, v2, dist, checkCoordinate): if checkCoordinate(*v1) and checkCoordinate(*v2) and dist is not None: graph.setdefault(v1, Vertex()).next.append((v2, dist)) graph.setdefault(v2, Vertex()).next.append((v1, dist)) def main(filename): with open(filename) as f: r, c, m, n = [int(x) for x in f.readline().split()] maze = [line.strip() + line[0] for line in f] maze.append(maze[0]) assert len(maze) == r + 1 for row in maze: assert len(row) == c + 1 distleft = [bfs(maze, i, 0) for i in range(r + 1)] for elem in distleft: if elem is not None: assert len(elem) == r + 1 assert len(elem[0]) == c + 1 distup = [bfs(maze, 0, j) for j in range(c + 1)] for elem in distup: if elem is not None: assert len(elem) == r + 1 assert len(elem[0]) == c + 1 distright = [bfs(maze, i, c) for i in range(r + 1)] for elem in distright: if elem is not None: assert len(elem) == r + 1 assert len(elem[0]) == c + 1 graph = {(0, 0): Vertex(), (r * m - 1, c * n - 1): Vertex()} goodRows = [i for i in range(r + 1) if maze[i][c] != "#"] goodCols = [j for j in range(c + 1) if maze[r][j] != "#"] def check(i, j): return 0 <= i < r * m and 0 <= j < c * n for i in range(r, r * m, r): for j in range(c * n): if distup[j % c] is not None: #z hornej na pravu stranu for i2 in goodRows: addEdge(graph, (i, j), (i2 + i, j // c * c + c), distup[j % c][i2][c], check) #z hornej na dolnu stranu for j2 in goodCols: addEdge(graph, (i, j), (i + r, j // c * c + j2), distup[j % c][r][j2], check) for j in range(c, c * n, c): for i in range(r * m): if distleft[i % r] is not None: #z lavej na dolnu stranu for j2 in goodCols: addEdge(graph, (i, j), (i // r * r + r, j2 + j), distleft[i % r][r][j2], check) #z lavej na hornu stranu addEdge(graph, (i, j), (i // r * r, j2 + j), distleft[i % r][0][j2], check) #z lavej na pravu stranu for i2 in goodRows: addEdge(graph, (i, j), (i // r * r + i2, j + c), distleft[i % r][i2][c], check) if distright[i % r] is not None: #z pravej na dolnu stranu for j2 in goodCols: addEdge(graph, (i, j), (i // r * r + r, j2 + j - c), distright[i % r][r][j2], check) #zo startu doprava for i in range(r + 1): if maze[i][c] != "#": addEdge(graph, (0, 0), (i, c), distup[0][i][c], check) #zo startu dole for j in range(c + 1): if maze[r][j] != "#": addEdge(graph, (0, 0), (r, j), distup[0][r][j], check) #do ciela zlava for i in range(r * m - r, r * m): if maze[i % r][0] != "#": addEdge(graph, (i, c * n - c), (r * m - 1, c * n - 1), distleft[i % r][r - 1][c - 1], check) #do ciela zhora for j in range(c * n - c, c * n): if maze[0][j % c] != "#": addEdge(graph, (r * m - r, j), (r * m - 1, c * n - 1), distup[j % c][r - 1][c - 1], check) dijkstra(graph, (0, 0)) return graph[(r * m - 1, c * n - 1)].dist if __name__ == "__main__": filename = "megamaze.txt" print(main(filename))
eb358a28fd77385b302ac37403b1e5dd53f89c31
behike56/learning-python3
/string_formatting/string_tow_formating.py
4,851
3.703125
4
# -*- coding: utf-8 -*- """\ PythonができるStringの事。中巻:format()の章 Pythonの基本を学習するためのソースコード Author: Hideo Tsujisaki """ import datetime """\ インデックスを指定するフォーマット方法 """ # インデックス指定1 formated_str1 = "安全性能:{0}、運動性能:{1}、燃費性能:{2}".format("A", "B", "C") # インデックス指定2 formated_str2 = "安全性能:{0}、運動性能:{1}、燃費性能:{2}".format("C", "A", "B") # インデックス指定3 formated_str3 = "安全性能:{2}、運動性能:{1}、燃費性能:{1}".format("C", "A", "B") # インデックス指定しない1 formated_str3 = "安全性能:{}、運動性能:{}、燃費性能:{}".format("A", "B", "C") # インデックス指定しない2 formated_str4 = "安全性能:{}、運動性能:{}、燃費性能:{}".format("A", "C", "B") # 同じものを何回指定してもOK1 formated_str5 = "{0}{0}{0}{1}{1}{1}{2}{2}{2}".format("A", "C", "B") # シーケンスをアンパック formated_str6 = "安全性能:{2}、運動性能:{1}、燃費性能:{0}".format(*"ACB") listed_str = ["A", "B", "C"] formated_str7 = "安全性能:{2}、運動性能:{0}、燃費性能:{1}".format(*listed_str) # 同じものを何回指定してもOK2 formated_str8 = "{0}{0}{0}{1}{1}{1}{2}{2}{2}".format(*listed_str) # キーと値をメソッドに渡す car_score1 = "総合得点::レガシィB4:{legacy}_レヴォーグ:{levorg}_WRX S4:{wrx_s4}" formated_str9 = car_score1.format(legacy="987", levorg="986", wrx_s4="985") # 辞書を渡してアンパック dict_score = {"legacy": "987", "levorg": "986", "wrx_s4": "985"} car_score2 = "総合得点::レガシィB4:{legacy}_レヴォーグ:{levorg}_WRX S4:{wrx_s4}" formated_str10 = car_score2.format(**dict_score) # 引数の属性へのアクセス(複素数のモジュール、cmathを使ってみる) # cmathの属性である、realとimagを呼び出せる cmath_num = 8 - 8j formated_str11 = "複素数::{0}_実部:{0.real}_虚部{0.imag}".format(cmath_num) # 引数の要素へのアクセス list_fruits = ["apple", "mango", "ichigo", "banana", "mikan", "satsumaimo"] formated_str12 = "赤い果物:{0[1]}、黄色い果物:{0[4]}".format(list_fruits) # 変換フラグを使う。!sはstr()、!rはrepr()、!aはascii() henkan_flg = "str(){!s}, repr(){!r}, ascii(){!a}" formated_str13 = henkan_flg.format(1234, "1,234", "2345円") # 文字よせ、<>^が寄せの指定、後ろの数字は文字数 formated_str14 = "{:<50}".format("左寄せ") formated_str15 = "{:>50}".format("右寄せ") formated_str16 = "{:^50}".format("中央寄せ") # 寄せの指定の前の記号で残りの文字を埋める formated_str17 = "{:@^50}".format("中央寄せ") # 数値ように符号の表示を指定できる。(マイナスは外せない。) formated_str18 = "{:+f}; {:+f}".format(10, -20) formated_str19 = "{:f}; {:f}".format(10, -20) formated_str20 = "{:-f}; {:-f}".format(10, -20) # 2進数、8進数、10進数、16進数 formated_str21 = "2進数:{0:b}, 8進数:{0:o}, 10進数:{0:d}, 16進数:{0:x}".format(2501) formated_str22 = "2進数:{0:b}, 8進数:{0:o}, 10進数:{0:d}, 16進数:{0:x}".format(1010) # プレフィックス付きにする formated_str23 = "2進数:{0:#b}, 8進数:{0:#o}, 10進数:{0:d}, 16進数:{0:#x}".format(2501) # カンマ付き formated_str24 = "{:,}".format(25012501) # パーセント付き、小数点の桁数も指定 formated_str25 = "{:.3%}".format(100 / 3) # 年月日時分秒 date = datetime.datetime(2054, 11, 11, 12, 20, 55) formated_str26 = "{:%Y-%m-%d %H:%M:%S}".format(date) name = "Kazundo Gouda" # Python3.6以降 format()が不要 formated_str27 = f"My name is{name}" # Python3.8以降 format()が不要、変数名=変数の中身という形で出力 formated_str28 = f"My name is{name=}" """ 実行 """ print("***インデックスを指定するフォーマット方法***") print(formated_str1) print(formated_str2) print(formated_str3) print(formated_str4) print(formated_str5) print(formated_str6) print(formated_str7) print(formated_str8) print() print("***キーを指定するフォーマット方法***") print(formated_str9) print(formated_str10) print(formated_str11) print(formated_str12) print(formated_str13) print(formated_str14) print(formated_str15) print(formated_str16) print(formated_str17) print() print("***数値型の表現方法***") print(formated_str18) print(formated_str19) print(formated_str20) print(formated_str21) print(formated_str22) print(formated_str23) print(formated_str24) print(formated_str25) print() print("***日付型の表現方法***") print(formated_str26) print() print("***割と新しい書き方***") print(formated_str27) print(formated_str28)
c875aeeab3784397d8bb693edb92bf153cb897a3
dhruvmojila/sem-5
/pds/practical-2/p2_8.py
316
3.828125
4
a = ['d','h','r','u','v'] print("join method:", ''.join(a)) b = ','.join(a) print("split method:", b.split(',')) d = { 'neharika':{'birthday':'Jun 1'}, 'soham':{'birthday':'june 30'}, 'preyas':{'birthday':'July 7'}, 'divyam':{'birthday':'may 5'} } name = input("enter name:") print("birthday:", d[name])
dbfed2e4d728e2c9561f27f4d785ec0293586b77
chintu0019/DCU-CA146-2021
/CA146-test/markers/func_sum_range.py/test-1/func_sum_range.py
271
3.53125
4
import func_bsearch def sum_range(a, low, high): total = 0 i = func_bsearch.bsearch(a, low) while i < len(a) and a[i] < high: total += a[i] i = i + 1 return total if __name__ == "__main__": a = [1,2,4,4,5,5,6,7,8] print sum_range(a,3,7)
d4612f4d18582dfa9aafea4d8fc3ce668170764b
Izmno/Kalah
/kalah.py
4,125
3.625
4
class Kalah: def __init__(self, houses, seeds): self._houses = houses # half the size of the board, i.e. number of houses and the store # for each player self._halfsize = houses + 1 # full size of the board self._fullsize = 2 * self._halfsize # board: array of length fullsize # positions 0 mod halfsize are stores -> initialized to 0 # other positions are houses -> initialized to number of starting seeds self.board = [ 0 if self.isStore(index) else seeds for index in range(self._fullsize) ] # nextPlayer: integer mod 2 representing player to make next move self.nextPlayer = 0 # gameEnded: boolean indicating whether the game has ended self.gameEnded = False def startIndex(self, player): return (player % 2) * self._halfsize def storeIndex(self, player): return (((player + 1) % 2) * self._halfsize - 1 ) % self._fullsize def houseIndex(self, house, player): return (player % 2) * self._halfsize + (house % self._houses) def isStore(self, index): return index % self._halfsize == self._halfsize - 1 def components(self, index): house = index % (self._halfsize) player = index // (self._halfsize) % 2 seeds = self.board[index % (self._fullsize)] isStore = self.isStore(index) return (house, player, seeds, isStore) def getPlayerSlice(self, player, includeStore = False): endIndex = self.storeIndex(player) + 1 if includeStore else self.storeIndex(player) return self.board[self.houseIndex(0, player): endIndex] def seedsInHouses(self, player, includeStore = False): return sum(self.getPlayerSlice(player, includeStore)) def gameShouldEnd(self): return self.seedsInHouses(0) == 0 or self.seedsInHouses(1) == 0 def empty(self, house, player): seeds = self.board[self.houseIndex(house, player)] self.board[self.houseIndex(house, player)] = 0 return seeds def moveToStore(self, house, player, includeOpponent = True ): seeds = self.empty(house, player) if includeOpponent: seeds += self.empty(- house - 1, player + 1) self.board[self.storeIndex(player)] += seeds def finish(self): self.board = [self.seedsInHouses(index // self._halfsize, True) if self.isStore(index) else 0 for index in range(self._fullsize)] self.gameEnded = True def winningPlayer(self): p0 = self.board[self.storeIndex(0)] p1 = self.board[self.storeIndex(1)] if p0 > p1: return 0 if p1 > p0: return 1 return None def move(self, house): player = self.nextPlayer seeds = self.empty(house, player) if house == 0: print(seeds) if seeds == 0: # if the selected house was empty # end the move without changing player return False index = self.houseIndex(house, player) while seeds > 0: # loop around the board while we have seeds left index += 1 if index != self.storeIndex(player + 1): # Unless index points to the store of the opposing player # drop a seed seeds -= 1 self.board[index % self._fullsize] += 1 # get info on ending index house, iplayer, seeds, isStore = self.components(index) if iplayer == player and not isStore and seeds == 1: # if move ends on an empty house of the current player # move seeds to store self.moveToStore(house, player) if not ( iplayer == player and isStore ): # if move does not end on store of current player # change the current player self.nextPlayer = (player + 1) % 2 if self.gameShouldEnd(): # if any player has no seeds in houses # end the game self.finish() return True
545d6ef8257aa5a7acaa0443b8e48f96008e7073
NCavaliere1991/Spotify-Playlist
/main.py
1,420
3.5
4
from bs4 import BeautifulSoup import requests import spotipy from spotipy.oauth2 import SpotifyOAuth from pprint import pprint BILLBOARD_URL = "https://www.billboard.com/charts/hot-100/" CLIENT_ID = "ab85b014d9fe44bbac9a6dd8a2601deb" CLIENT_SECRET = "c3ebe9cfa7954b57b4989116dcec51be" date = input("Which year would you like to travel back to? Type the date in this format YYYY-MM-DD: ") response = requests.get(f"https://www.billboard.com/charts/hot-100/{date}") top_hundred = response.text soup = BeautifulSoup(top_hundred, "html.parser") songs = soup.find_all(name="span", class_="chart-element__information__song") song_list = [song.getText() for song in songs] sp = spotipy.Spotify( auth_manager=SpotifyOAuth( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://example.com", scope="playlist-modify-private", ) ) user_id = sp.current_user()['id'] song_uris = [] year = date.split("-")[0] for song in song_list: result = sp.search(q=f"track: {song} year: {year}", type="track") try: uri = result["tracks"]["items"][0]["uri"] song_uris.append(uri) except IndexError: print(f"{song} does not exist in spotify. Song skipped.") new_playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False) sp.user_playlist_add_tracks(user=user_id, playlist_id=new_playlist['id'], tracks=song_uris)
42b5e12eb7195ebdc40206fea4d2d5a98d0d212e
rivcah/100daysofPython
/lists.py
1,107
3.609375
4
##Use lista.getlist(t, path) in order to create a .csv file with names and ##ID numbers. class lista: def getid(): import random as r n = [] for i in range(5): n.append(str(r.randint(0,9))) ID = '' for i in range(len(n)): ID += n[i] return(ID) def getname(): first = input("First name: ") last = input("Last name: ") name = first+' '+last return(name) def register(t): i = 1 names = [] identity = [] while i <= t: names.append(lista.getname()) identity.append(lista.getid()) i += 1 return(names, identity) def getlist(t, path): import csv names, identity = lista.register(t) rows = zip(names, identity) with open(path, 'w+') as file: f = csv.writer(file) f.writerow(("Name", "ID")) for row in rows: f.writerow(row) file.close()
2bb80eca9e1ea7dc5742973b822d68e6ae88ff31
baayso/learn-python3
/function/def_func.py
3,125
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math # 空函数 def nop(): pass def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny n = my_abs(-20) print(n) x, y = move(100, 100, 60, math.pi / 6) print(x, y) # TypeError: bad operand type: # my_abs('123') print() # 位置参数(普通参数) # 默认参数 def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s print(power(5)) print(power(5, 2)) print() # 默认参数不要指向不变对象 def add_end(L=[]): L.append('END') return L # 将上面的函数修改一下 def add_end2(L=None): if L is None: L = [] L.append('END') return L print(add_end()) print(add_end()) print() print(add_end2()) print(add_end2()) print() # 可变参数,参数前面加了一个*号 # 可变参数在函数调用时自动组装为一个tuple def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc()) print(calc(1, 2)) print(calc(*[1, 2, 3])) print() # 关键字参数 # 关键字参数允许传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict def person(name, age, **kw): if 'city' in kw: # 有city参数 pass if 'job' in kw: # 有job参数 pass print('name:', name, 'age:', age, 'other:', kw) person('Michael', 30) person('Bob', 35, city='Beijing') person('Adam', 45, gender='M', job='Engineer') extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, city=extra['city'], job=extra['job']) person('Jack', 24, **extra) print() # 命名关键字参数 # 如果要限制关键字参数的名字,就可以用命名关键字参数 # 命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数 def person(name, age, *, city, job): print(name, age, city, job) person('Jack', 24, city='Beijing', job='Engineer') # 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了 def person(name, age, *args, city='Beijing', job): print(name, age, args, city, job) person('Jack', 24, *[1, 2, 3], job='Engineer') print() # 参数组合 # 参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数 def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) f1(1, 2) f1(1, 2, c=3) f1(1, 2, 3, 'a', 'b') f1(1, 2, 3, 'a', 'b', x=99) f2(1, 2, d=99, ext=None) print() # 对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的 f1(*(1, 2, 3, 4), **{'d': 99, 'x': '#'}) f2(*(1, 2, 3), **{'d': 88, 'x': '#'})
b96d9d3b2fa30f2c2ff4472fec1f25859c09d25c
big-Bong/AlgoAndDs
/PythonPractice/CTCI/4_4_CheckBalanced.py
732
3.875
4
class Tree: def __init__(self,num): self.val = num self.left = None self.right = None def checkBalanced(root): if(not root): return False val = calculateHeight(root) if(val == -1): return False return True def calculateHeight(root): if(not root): return 0 l_height = calculateHeight(root.left) r_height = calculateHeight(root.right) if(l_height == -1 or r_height == -1): return -1 diff_val = abs(l_height - r_height) if(diff_val > 1): return -1 return 1+max(l_height,r_height) root = Tree(1) root.left = Tree(2) root.right = Tree(3) root.left.left = Tree(4) root.left.right = Tree(5) #root.right.left = Tree(6) root.right.right = Tree(7) root.left.left.left = Tree(0) print(checkBalanced(root))
7bf254ecb7d5403c6470a4520b04cb12e80ceae7
Priya2410/Competetive_Programming
/Codechef/Beginner-Problems/FLOW004.py
172
3.6875
4
# cook your dish here test=int(input()) for i in range(0,test): n=input(); length=len(n); num=int(n); sum=num%10+int(num/pow(10,length-1)); print(sum);
0d8d1c23ee883c8ecb465b1ea25b9b2bf60bf01f
blueicy/Python-achieve
/00 pylec/01 StartPython/hw_5_2.py
358
4.1875
4
numscore = -1 score = input("Score:") try: numscore = float(score) except : "Input is not a number" if numscore > 1.0 : print("Score is out of range") elif numscore >= 0.9: print("A") elif numscore >= 0.8: print("B") elif numscore >= 0.7: print("C") elif numscore >= 0.6: print("D") elif numscore >= 0.0: print("F") else: print("Not vaild")
7260c27e17c2decc78c8f6c3cd09b021a3ecf7b6
rajagoah/Python-Importing-From-Web
/ImportingFromWebExercise8.py
520
3.625
4
import requests from bs4 import BeautifulSoup #storing url in variable url = 'https://www.python.org/~guido/' #packaging, sending and receiving the response r = requests.get(url) #html_doc storing the html in text html_doc = r.text #converting to beauitfulsoup object soup = BeautifulSoup(html_doc) #finding all the tags 'a' to idenitfy the urls in hyperlinks a_tags = soup.find_all('a') #enumerating over the a_tags variable to extract the links within the href tag for link in a_tags: print(link.get('href'))
88c865c43050ebd588de03d6771d64acac481584
ladezai/markov-model
/Markov/markov.py
8,832
3.921875
4
import numpy as np from math import isclose class StationaryMarkovChain(): """ It provides an implementation of stationary finite Markov chain `(l, P)` over the set of labels `S` (or nodes of the Markov chain). The following implementation emphasises that a Markov chain represents the evolution of a distribution over time, via a stocastic process determined by `P`. Therefore from an iterable point of view the class is only its distribution, i.e. of type``dict[str,float]``. And ``__next__`` method is replaced by ``evaluate_next``. In such a way that allows to easily simulate a path over itself via for-loops. See ``../examples/word_generator.py`` or ``../examples/wordplay_test.py``. Use pickle for serialization since no JSON serialization has been implemented yet. Example ------- We represent a trivial markov chain via the following graph: ._0.5_ .__1__ | | | | '--> a ----0.5---> b <--' then the set S = {'a', 'b'} and the stocastic matrix P is the following P = [[0.5,0.5],[0, 1]] In terms of the implementation below the set S represents the keys of the initial distribution, while P is the iteration_matrix. Since no initial distribution is given in our example we could consider the Dirac distribution which is 1 in 'a' and 0 in 'b', therefore initial_distribution = {'a' : 1.0, 'b': 0.0}. Attributes ---------- iteration_matrix : numpy.array A stocastic matrix which represents links between each node in the Markov Chain's state. current_distr : dict[str,float] A dictionary that provides an initial distribution for the MarkovChain. Where keys are used as label for each node of the Markov Chain's state. Methods -------- set_distr : dict[str,float] -> bool -> None Assigns a new value to current_distr. Checks whether the new value is also a distribution. set_to_dirac_distr : str -> None Assigns `1` to the key value given and `0` to all other values of the distribution. distribution : dict[str,float] Returns the current value of the Markov's chain distribution. evaluate_next : int -> None Evaluates the development of the distribution after `n` steps. normalize : None Normalizes rows of the iteration_matrix. It's useful in case of some floating point errors. """ iteration_matrix = np.array([[]]) current_distr = dict() def __init__(self, iteration_matrix:np.array, initial_distribution:dict[str, float]): """ Parameters ---------- iteration_matrix : numpy.array The Markov Chain's stocastic matrix, it has to be a square matrix with normalized rows. initial_distribution : dict[str, float] A dictionary which provides an initial distribution. Note that it must have same length as the rows/columns of the iteration_matrix. Raises ------ ValueError If initial_distribution and iterations_matrix aren't of same length. """ if iteration_matrix.shape[0] != iteration_matrix.shape[1]: raise ValueError("Iteration matrix must be a square-matrix") if len(initial_distribution) != iteration_matrix.shape[0]: raise ValueError(("Initial distribution and iteration matrix does" + "not have same size.")) self.iteration_matrix = iteration_matrix self.current_distr = initial_distribution ########################################################################### ################## Get, set and update distribution ####################### ########################################################################### def set_distr(self, distr:dict[str,float], checks : bool = False): """ Sets the current distribution of the Markov Chain. Parameters ---------- distr : dict[str, float] A dictionary which provides a distribution. Note that it must have same length as the rows/columns of the iteration_matrix. checks : bool It provides a way to check whether the distr parameter is a distribution (default is False). Raises ------ ValueError If initial_distribution and iterations_matrix aren't of same length. ValueError If distr is not normalized. """ if checks: M = sum(list(distr.values())) if not isclose(M,1,abs_tol=0.0001): raise ValueError("Dictionary given is not a distribution.") if len(self) != len(distr): raise ValueError("Distributions have different length.") self.current_distr = distr return None def set_to_dirac_distr(self, node : str) -> None: """ Sets to a Dirac distribution centered in the node given. Parameters: ----------- node: str A String that represents a label of the Markov Chain. It serves as a key in current_distr's dictionary. Raises: --------- KeyError If node is not a key in current_distr. """ distr = {k:0 for k in self.current_distr} distr[node] = 1 self.set_distr(distr, checks=False) return None def distribution(self) -> dict[str,float]: """ Gives a view of current_distr. Returns: -------- dict[str,float] """ return self.current_distr ########################################################################### ############################# Simulation ################################## ########################################################################### def evaluate_next(self, n : int = 1, checks : bool = False) -> None: """ Evaluates the distribution after n-steps in-place. In mathematical terms it evalues l * P^n, where l is the initial_distr, and P the iteration_matrix. Parameters: ------------ n : int Represents the number of steps to evaluate on the Markov chain. Therefore it has to be non-negative (default value is 1). checks: bool If checks is True, it checks whether the current_distr is still a distribution at the end of the simulation, and if a negative number of step is inputed (default value is False). Raises: -------- ValueError If n is negative and check is True. ValueError If the simulation generates an invalid distribution. """ if checks: if n < 0: raise ValueError("Can't simulate a negative number of steps") distr = self.distribution() for i in range(n): values = np.array(list(distr.values())) new_values = self.iteration_matrix.T.dot(values) distr = {key:new_values[j] for j,key in enumerate(self.current_distr)} self.set_distr(distr,checks=checks) return None def normalize(self) -> None: """ Normalizes by rows the iteration_matrix in-place. """ l = len(self) for i in range(l): N = sum(self.iteration_matrix[i]) self.iteration_matrix[i] /= N return None def __iter__(self): return self def __next__(self): self.evaluate_next(n=1) return self.current_distr def __del__(self): del self.current_distr del self.iteration_matrix def __len__(self): return len(self.current_distr) def __str__(self): return ("""It's a Markov chain (l, P), where P = """ + str(self.iteration_matrix) + """ l = """ + str(self.current_distr))
aadd229b33499ba43d42f7f71acc36c0ffbacdf3
Mengeroshi/python-tricks
/3.Classes-and-OOP/2.1string_conversion.py
284
4.03125
4
"""__str__ gets called when you try to convert an object to a string""" class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __str__(self): return f'a {self.color} car' my_car = Car('red', 37281) print(my_car)
2cefb9217bb6e74cc7da7948571a9d1ca9061f88
CodetoInvent/interviews
/dp/stock_iv.py
1,223
3.890625
4
# Say you have an array for which the ith element # is the price of a given stock on day i. # Design an algorithm to find the maximum profit. # You may complete at most k transactions. # Note: # You may not engage in multiple transactions at the same time. # algorithm: # i: transactions table # j: day # max( # # if we don't do any transaction # transactions[i][j-1], # # one less transaction until a day before + transaction on current day # transactions[i-1][j-1] + stocks[j] - stocks[j-1] # ) # # algorithm: # maximum of: # - not transacting (the profit from the day before) # - the max profit from one less transaction + selling on current day def max_profit(prices, k): transactions = [[0] * len(prices) for i in range(k+1)] for transaction in range(1, k+1): for day in range(1, len(prices)): not_transacting = transactions[transaction][day-1] selling_current_day = max( [ prices[day] - prices[m] + transactions[transaction-1][m] for m in range(day) ] ) transactions[transaction][day] = max( not_transacting, selling_current_day ) return transactions print max_profit([2, 3, 5, 1, 7], 3)
a75ae0872bf668529dfc7db2046aad3219505a5b
natanisaitejasswini/Python-Programs
/avg.py
95
3.625
4
a = [1, 2, 5, 10, 255, 3] sum = 0 for element in a: sum += element print 'final:', sum/len(a)
83a85a304850eb32ccea443264cacdc9e676b254
lade043/Projekttage
/user_IO.py
1,188
3.78125
4
import Formeln def user_input(): geg = {} ges = {} geginput = None gesinput = None while True: geginput = input("Welche Formelzeichen sind gegeben? Geben Sie immer nur EINS ein! \n" " Bestätigen sie Ihre Eingaben mit 'Fertig'\n") if geginput == "Fertig": for symbol in geg: geg[symbol] = float(input("Geben Sie den Wert zu " + symbol + " ein.\n")) break else: geg[geginput] = None gesinput = input("Welches Formelzeichen sind gesucht?\n") ges[gesinput] = None return [geg, ges] def user_output(liste): geg = liste[1][0] ges = liste[1][1] formel_str = liste[1][2].string formel_name = liste[1][2].name ges[list(ges.keys())[0]] = liste[0] print("\n\n\n\nDas Programm hat fertig gerechnet!") print("Dies war gegeben: ") for wert in geg: print(wert + " = " + str(geg[wert])) print("\nDas was gesucht: ") for wert1 in ges: print(wert1 + " = " + str(ges[wert1])) print("\nDiese Formel habn wir genutzt: " + formel_name) print("So sieht die Formel aus: " + str(formel_str) + "\n\n\n\n\n\n")
1d41215ee4e7f6ce498fd5d4c12c989f2cc2fc02
corrodedHash/brancher
/brancher/codegen.py
4,538
3.609375
4
"""Contains functions to generate C code""" import random from typing import List, Tuple from . import node, util class CodeGenerator: """Generates code""" def __init__(self, var_count: int, fun_count: int, indent: str = " ") -> None: self.variables: List[str] = ["var_" + str(x) for x in range(1, var_count + 1)] self.functions: List[Tuple[str, int]] = [ ("fun_" + str(x), util.log_weight_random(1, 4, 4)) for x in range(1, fun_count + 1) ] self._indent = indent def gen_stuff(self, level: int) -> str: """Generates a few lines of assignments and function calls""" result = "" for _ in range(1, util.log_weight_random(2, 10)): result += ( (level * self._indent) + gen_assignment(self.variables, self.functions) + ";\n" ) return result def gen_tree(self, tree: node.Node, level: int = 0) -> str: """Generates nested if clauses based on given tree""" def print_if_statement(which: str, level: int) -> str: """Print the keyword to the if branch""" result = self._indent * level if which == "first": result += "if (" + gen_clause(self.variables) + ")" elif which == "last": result += "else" else: result += "else if (" + gen_clause(self.variables) + ")" return result def print_if_clause( cur_node: node.Node, which: str, level: int, start: bool = False ) -> str: """Print the clause for an if statement""" result = "" if start: level -= 1 if not start: result = print_if_statement(which, level) + " {\n" result += self.gen_stuff(level + 1) if cur_node.get_children(): child_list = list(cur_node.get_children()) result += print_if_clause(child_list[0], "first", level + 1) for child in child_list[1:-1]: result += print_if_clause(child, "middle", level + 1) result += print_if_clause(child_list[-1], "last", level + 1) if not start: result += self._indent * level + "}\n" return result return print_if_clause(tree, "first", level, True) def gen_function(name: str, var_count: int, indent: str = " ") -> str: """Generates a function with given function name""" my_cg = CodeGenerator(var_count, 0, indent) parameters = my_cg.variables parameter_list = ", ".join(parameters) my_cg.variables.append("result") result = "int " + name + " (" + parameter_list + ") {\n" result += indent + "int result = " + str(random.randint(0, 200)) + ";\n" result += my_cg.gen_tree(node.create_tree(3, 2, 3, 5), level=1) result += indent + "return result;\n" result += "}\n" return result def gen_clause(variables: List[str]) -> str: """Generates a boolean statement with given variables""" var = random.choice(variables) operator = random.choice(["%", "<", ">"]) if operator == "%": return var + " " + operator + " " + str(random.randint(2, 30)) + " == 0" random_comparison_int = str(random.randint(1, 9) * (10 ** random.randint(1, 3))) return f"{var} {operator} {random_comparison_int}" def gen_term(variables: List[str]) -> str: """Generates a term using given variables""" if random.randint(1, 10) == 1: return str(random.randint(5, 200)) num_vars = util.log_weight_random(1, len(variables), 1.5) chosen_vars = random.sample(variables, num_vars) result = chosen_vars[0] for cur_var in chosen_vars[1:]: operator = random.choice(["+", "-", "*"]) result += f" {operator} {cur_var}" return result def gen_function_call(variables: List[str], functions: List[Tuple[str, int]]) -> str: """Generates a function call""" cur_fun = random.choice(functions) cur_vars = random.sample(variables, cur_fun[1]) argument_list = ", ".join(cur_vars) return cur_fun[0] + "(" + argument_list + ")" def gen_assignment(variables: List[str], functions: List[Tuple[str, int]]) -> str: """Generates assignment to random variable""" var = random.choice(variables) if functions and random.randint(1, 10) < 3: return f"{var} = {gen_function_call(variables, functions)}" return f"{var} = {gen_term(variables)}"
181108037d88a964161d7452af6dc1422be55898
navyapp/python-MCA
/CO 1/co1 leapyear(2).py
202
3.546875
4
# co1, 2 y1 = int(input("ener the current year")) y2 = int(input("enter the last year")) for i in range(y1, y2 + 1): if (i % 4 == 0 and i % 100 != 0 or i % 400 == 0): print(i) i = i + 1
71ac9387476d51503059f903bbf242b76ed974de
ruifan831/leetCodeRecord
/92_Reverse_Linked_List_II.py
703
3.875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: pre=None node=head while m>1: pre=head head=head.next m-=1 n-=1 p1=pre p2=head while n>0: nextNode = head.next head.next=pre pre=head head=nextNode n-=1 p2.next=head if p1 is not None: p1.next=pre else: node=pre return node
00339e63123de116e196fd20b8aaf96591051b0c
nsasaki128/advent_code_2020
/25_01.py
670
3.65625
4
def main(): s = 7 card = int(input()) door = int(input()) key = 20201227 card_loop = get_loop(s, key, card) door_loop = get_loop(s, key, door) print(f"card_loop: {card_loop}") print(f"door_loop: {door_loop}") ans_card = 1 for _ in range(door_loop): ans_card *= card ans_card %= key print(ans_card) ans_door = 1 for _ in range(card_loop): ans_door *= door ans_door %= key print(ans_door) def get_loop(s, key, dest): loop = 0 start = 1 while start != dest: loop += 1 start *= s start %= key return loop if __name__ == '__main__': main()
e8ee4886c905716f6b216b146b979d8a243e8ff2
op9494/Python-programs
/2reverse_str.py
112
4.125
4
def reverse(str): s ="" for ch in str: s=ch+s return s mystr =input() print(reverse(mystr))
08103978aa9f3232bbfccc6a0c902d6c46ceea7d
abhmak/Deeplearning-files
/2.Data_types.py
8,599
3.984375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 1 14:59:03 2018 @author: abhayakumar """ ############################################################################################### Strings fruit = 'orange' ########Indexing in strings letter = fruit[1] letter ########Length of the string length = len(fruit) length ###??? the last letter in the string last = fruit[length] #? last = fruit[length-1] print(last) #####################################Traversal through a string #Using While Loop index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 #Using For Loop for letter in fruit: print(letter) ####################################Slicing the strings s = 'Monty Python' s[0:5] s[6:12] fruit = 'banana' fruit[:3] #####################################Strings are Immutable greeting = 'Hello, world!' ######????? greeting[0] = 'J' #Can create a new string new_greeting = 'J' + greeting[1:] print(new_greeting) ############################################ ####Methods on strings ############################################ #Method to convert to upper case word = 'banana' new_word = word.upper() print(new_word) #Method to find the index of a letter word = 'banana' index = word.find('a') ###? print(index) print(word.find('na')) ###########The use of in operator #in is a Boolean operator check= 'a' in 'banana' print(check) check = 'seed' in 'banana' print(check) ######################################################### ############################################################################################ LISTS ######################################Creating new lists cheeses = ['Cheddar', 'Edam', 'Gouda'] numbers = [42, 123] empty = [] print(cheeses, numbers, empty) #######################################Indexing in lists is very much similar to strings ###########The in operator also works the same in lists cheeses = ['Cheddar', 'Edam', 'Gouda'] print('Edam' in cheeses) ###########Traversing in the lists is also similar to strings for cheese in cheeses: print(cheese) ########### A list can contain other lists as well new_l = ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] #########################Lists are Mutable numbers = [42, 123] numbers[1] = 5 print(numbers) ###Some operations on lists a = [1, 2, 3] b = [4, 5, 6] c = a + b #? print(c) d=a*3 #? print(d) ########## Slicing is similar to strings t = ['a', 'b', 'c', 'd', 'e', 'f'] t[1:3] t[3:] t[:3] ############################################### Methods on Lists #append by an element t1 = ['a', 'b', 'c'] t2 = ['d', 'e'] t1.append(t2) print(t1) #extend by another list t1 = ['a', 'b', 'c'] t2 = ['d', 'e'] t1.extend(t2) print(t1) #sort t = ['d', 'c', 'e', 'b', 'a'] t.sort() print(t) ############################################################################### ##########################################################################################String-List-String #Converting a string to list type s = 'spam' t = list(s) print(t) ## splitting a string at 'spaces'to a list s = 'pining for the fords' t = s.split() print(t) ## splitting a string at other 'delimiter' to a list s = 'spam-spam-spam' delimiter = '-' t = s.split(delimiter) print(t) ## Joining a list of strings to a single string t = ['pining', 'for', 'the', 'fords'] delimiter = ' ' s = delimiter.join(t) print(s) ############################################################################### ############################################################################################## Dictionaries ################Creating Dictionaries eng2sp = dict() eng2sp['one'] = 'uno' print(eng2sp) eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} print(eng2sp) ####check eng2sp['four'] eng2sp['three'] #length len(eng2sp) #in operator 'one' in eng2sp 'uno' in eng2sp #the values specifically vals = eng2sp.values() 'uno' in vals #################################################### Creating a character histogram from a long string def histogram(strng): d = dict() for ch in strng: if ch not in d: d[ch] = 1 else: d[ch] += 1 return d h = histogram('brontosaurus') print(h) ###################################################### ###################################################### Traversing through the keys in a dictionary def print_hist(h): for key in h: print(key, h[key]) print_hist(h) ##################################################################################### ################################################################################################# TUPLES #############Creating a tuple t = tuple() t t = tuple('lupins') t #### Indexing is just like lists t[0] t[1:3] ##############################################Example use-case ### Swaping values a=10 b=11 # temp = a a = b b = temp # ### Swaping values using tuple assignment a=10 b=11 # a, b = b, a # #######################Zipping of two sequences using tuples s = 'abc' t = [0, 1, 2] z=zip(s, t) print(z) print(list(z)) print(z) ###Traversing through the zipped tuple for pair in zip(s, t): print(pair) #If the sequences are not the same length, the result has the length of the shorter one z1 =zip('Anne', 'Elk') print(list(z1)) #################################################################################### #################################################################################### CLASSES and its OBJECTS ##################### Defining a class class Point: """Represents a point in 2-D space.""" ##################### print(Point) ################################# Creating an object of the class blank = Point() ####### print(blank) ################################# Assigning values to an instant using dot notation ########################## For the object instance "blank", x and y can be called as its' attributes blank.x=3.0 blank.y=4.0 ################################## ################### Passing an instance as an argument to a function def print_point(p): print('('+str(p.x)+','+str(p.y)+')') #call print_point(blank) ################################### Creating another class of type Rectangles class Rectangle: """Represents a rectangle. attributes: width, height, corner. """ #########Instantiating a Rectangle type object and assigning values to its attributes box = Rectangle() box.width = 100.0 box.height = 200.0 box.corner = Point() box.corner.x = 0.0 box.corner.y = 0.0 ##The expression box.corner.x means, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x.” ##################################### Instances as return values ###Take the Rectangle and return me the coordinates of its center def find_center(rect): p = Point() p.x = rect.corner.x + rect.width/2 p.y = rect.corner.y + rect.height/2 return p #Call center = find_center(box) print_point(center) ### Objects are mutable box.width = box.width + 50 box.height = box.height + 100 ####################### ########################################### Transforming Functions into methods #Creat a class of type Time class Time: """Represents the time of day.""" """ (hour,minute,second) as attributes""" #Define a function with object of type Time as an argument, to print the time of the day def print_time(time): print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)) #Instantiating an object of the class Time and assigning values to its attributes start = Time() start.hour = 9 start.minute = 45 start.second = 00 ## Calling the function and passing the instance "start" as an argument print_time(start) ## #####################Transforming to the use of methods ##To make print_time a method, all we have to do is move the function definition inside the class definition class Time01: def print_time(time): print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)) start = Time01() start.hour = 9 start.minute = 45 start.second = 00 ##call the function/method #010 Using the method syntax (more concise and meaningful) start.print_time() #Apply the method "print_time()" on the object "start" of type Time #"Hey start! Please print yourself"
a794eeb38de6e98aef36a69992082bf7cd6dd7bc
DChandlerP/algos_python
/fourNumSum.py
746
3.546875
4
# https://www.geeksforgeeks.org/find-four-numbers-with-sum-equal-to-given-sum/ # https://leetcode.com/problems/4sum/ def fourNumberSum(array, targetSum): array.sort() print(array) result = [] for i in range(len(array) - 3): for j in range(i + 1, len(array) - 2): k = j + 1 l = len(array) - 1 while k < l: sum = array[i] + array[j] + array[k] + array[l] if sum == targetSum: result.append([array[i], array[j], array[k], array[l]]) k += 1 l -= 1 elif sum < targetSum: k += 1 else: l -= 1 print(result) return result
e0b6dd033737a1676b7b81b526a8fa1eec445cd9
freeprogramers/Polynomial
/polynomial.py
4,546
3.640625
4
def lex(n, x, y): #checks if x > y: returns x<=y x, y are terms with coef n is no. of variables for i in range(1, n+1): if x[i]==y[i]: continue else: if x[i]>y[i]: return -1 else: return 1 return 0 class Poly(object): """Creats polynomial object and perform all polynomial related operations. n is number of inderterminants used and l is list of (n+1)-tuples where each tuple represents a term is polynomial as first entry as coeficient and remaining n entries are powers of each variables p = Poly(3, [(2, 2, 1, 0), (1, 1, 0, 1), (-1, 0, 2, 3)]) # is 2x^2y+xz-y^2z^3""" def __init__(self, n, l, order="lex"): self.num_of_vars = n self.poly = l self.num_of_terms = len(l) self.order = order self.coef = map(lambda x: x[0], self.poly) #gives list of coeficients self.mono = map(lambda x: x[1:], self.poly) #gives list of multinomials self.shape() self.sort() self.coef = map(lambda x: x[0], self.poly) self.mono = map(lambda x: x[1:], self.poly) self.LT = self.poly[0] #Note self.LT is a tuple but self.LT() is poly object self.multideg = self.mono[0] self.leading_coef = self.coef[0] def sort(self): #sort the polynomial in lex order if self.order == "lex": self.poly.sort(lambda x, y: lex(self.num_of_vars, x, y)) else: print "Sorry Under Construction" #%%%%%%%%%%%%%%%% # Remaining work: write for other orders #%%%%%%%%%%%%%%%% def shape(self): #removes term with coef 0 and merges terms with same powers l = self.poly n = self.num_of_vars m = self.num_of_terms coef = self.coef mono = self.mono i = 0 while i<m: if float(coef[i])==0.0: l.pop(i) coef.pop(i) mono.pop(i) m-=1 else: if mono[i] in mono[i+1:]: c = mono.index(mono[i], i+1) mono.pop(c) coef[i]+=coef.pop(c) l[i]=(coef[i],)+mono[i] l.pop(c) m-=1 else: i+=1 if m==0: self.poly = [(0, ) + (0,)*n] self.num_of_terms = 0 else: self.num_of_terms = m def __add__(self, other): if self.num_of_vars == other.num_of_vars: return Poly(self.num_of_vars, self.poly+other.poly) else: raise ValueError("variables dont match") def __sub__(self, other): if self.num_of_vars == other.num_of_vars: return Poly(self.num_of_vars, self.poly+map(lambda x: (-x[0],)+x[1:], other.poly)) else: raise ValueError("variables dont match") def __mul__(self, other): n = self.num_of_vars if n == other.num_of_vars: poly = [] for i in range(self.num_of_terms): for j in range(other.num_of_terms): poly.append((self.coef[i]*other.coef[j],)+ tuple(map(lambda k: self.mono[i][k]+other.mono[j][k], range(n)))) return Poly(n, poly) def change_indeter_order(self, order): """order is a n tuple with ordering o[i]>o[j] if i<j""" n = self.num_of_vars p = [] m = [] for d in self.poly: t=(d[0],) r=tuple() for i in range(n): t+=(d[1+order[i]],) r+=(d[1+order[i]],) p.append(t) m.append(r) self.poly = p self.mono = m def LeadingTerm(self): return Poly(self.num_of_vars, [self.poly[0]]) def isdivisible(self, other): #other is poly object n = self.num_of_vars if n != other.num_of_vars: print "No of Vars is not the same" return False for i in range(n): if self.multideg[i]<other.multideg[i]: return False return True def monodiv(self, other): #should only used as internal fn; other is tuple anscoef = self.leading_coef/other[0] ansdeg = tuple() for i in range(1, self.num_of_vars+1): ansdeg += (self.LT[i]-other[i],) return (anscoef,)+ansdeg #ans is tuple #Aashay Shah :15109267346
759c78d704361a2e00e63ed181d8bd52778bd89b
MichaelMcGrail1/cmpt120mcgrail
/IntroProgramming-Labs/rover.py
254
3.671875
4
# Michael McGrail # Introduction to Programming # A program calculating the time it takes to send pictures from Mars to NASA def main(): distance = (34000000) speed = (186000) time = (distance / speed) print(time) main()
216e432832008aa4acd91978d4864d8ed0f36fa1
ganga-17/programming-lab-python-
/course outcome 1/10areacircle.py
81
3.96875
4
r=int(input("enter the radius : ")) a=3.14*r*r print("area of the circle is ",a)
bd45afd45197a407bbb542179e4bbe8d86ec56d9
hellfish2/curso_plone-git
/susana/conecta.py
3,468
3.546875
4
#!/usr/bin/python #*.* coding = utf-8 *.* #Host Details host = "161.196.204.6" port = 5433 #You will need to change these to your specific connection details. user = "postgres" dbname = "prueba" passwd = "postgres" import pgdb def pgdbExample(): """See: http://www.python.org/peps/pep-0249.html""" # DB-API needs a data source name in this format. dsn = host + ':' + dbname # By default a transaction is implicitly started when the connection is # created in DB-API. Unfortunately it is not possible to stop this in the # pgdb module, other DB-API implementations do allow different behaviour. connection = pgdb.connect(dsn=dsn, user=user, password=passwd) # A cursor object (not necessarily a PostgreSQL cursor - depends on the # module implementation) is required for all database operations. cursor = connection.cursor() # Create an example table. cursor.execute("CREATE TABLE test(code SERIAL PRIMARY KEY, data TEXT);") # Put something in the table. The "code" attribute is populated but # the implicit trigger on the SERIAL type. When inserting many rows into # a table the executemany() method is a better option. cursor.execute("INSERT INTO test (data) VALUES ('Hello World!');") # Commit what we've done so far. This implicitly starts a new transaction # within the connection object. connection.commit() # Fetch all entries in our example table. cursor.execute("SELECT * FROM test;") print "There were " + str(cursor.rowcount) + " rows in the table:\n" # Pull the data into python data structures. Note that this is not the # best way to deal with very large sets of data, the fetchone() or # fetchmany() method would be better. This gives the python module the # option of using PostgreSQL cursors or similar efficiency tricks. tuples = cursor.fetchall() # Print out table data. for (code, data) in tuples: print "Code: " + str(code) + ", Data: " + str(data) # Clean up. cursor.execute("DROP TABLE test;") connection.commit() # Close database connection. cursor.close() connection.close() import pg def pgExample(): """See: http://www.postgresql.org/docs/7.3/static/pygresql.html""" # Open a connection to the database using the pg module"s DB class. db = pg.DB(dbname=dbname, host=host, user=user, passwd=passwd) print "Conectado" # Start a transaction. db.query("BEGIN;") # Create and example table. db.query("CREATE TABLE test(code SERIAL PRIMARY KEY, data TEXT);") # The DB class in the pg module has a nice method that allows us to # pass it a dictionary and have it insert it into the database. db.insert('test', {'data': 'Hello World!'}) # Commit the transaction. db.query('END;') # Start another transaction. db.query("BEGIN;") # Fetch all entries from out example table. result = db.query("SELECT * FROM test;") print "There were " + str(result.ntuples()) + " rows in the table:\n" # Pull the data into python data structures. tuples = result.getresult() # Print out table data. for (code, data) in tuples: print "Code: " + str(code) + ", Data: " + str(data) # Clean up. db.query("DROP TABLE test;") db.query('END;') db.close() #try: # conecta = pg.connect(dbname="prueba",user="postgres",passwd="posgres") #except: # print "Error" # ESTA ES UNA PRUEBA
4981e3ca9f8b88663e5edfca96ea2af7bae5d6cb
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 12 - 2D Lists and Dictionaries/097 Select row and column from 2D list.py
683
4.09375
4
#097 Select row and column from 2D List simple_list = [[2,5,8],[3,7,4],[1,6,9],[4,2,0]] rowCount = len(simple_list) - 1 row = int(input("Please enter a row number between 0 and " + str(rowCount) + ": ")) while row > rowCount: row = int(input("Invalid number. Please enter a valid row number between 0 and " + str(rowCount) + ": ")) colCount = len(simple_list[row]) - 1 col = int(input("Please enter a column number between 0 and " + str(colCount) + ": ")) while col > colCount: col = int(input("Invalid number. Please enter a valid column number between 0 and " + str(colCount) + ": ")) print("row " + str(row) + ", col " + str(col) + ": " + str(simple_list[row][col]))
b1eb295cb31c6f97ec2d21cb692e873500777a70
MilkClouds/SCSC-2019
/거듭제곱 알고리즘.py
434
3.921875
4
A=2 B=10**50 C=12345 def pow_row(a,x): ret=1 for _ in range(x): ret = ret * a % C return ret def pow_recursive(a,x): if x==0: return 1 if x%2==0: return pow_recursive(a,x//2)**2 % C return a*pow_recursive(a,x//2)**2 % C def pow(a,x): r=1 while x: if x%2: r = r*a %C x//=2 a = a*a %C return r print(pow_recursive(A,B)) print(pow(A,B))
ff753f38c37dd74917699fe2f8397a67104290e2
nischalshk/IWPython
/DataTypes/42.py
94
4.03125
4
# Write a Python program to convert a list to a tuple l = [1, 2, 3] t = tuple(l) print(t)
fff7984342227204118024328c256e23c517bcd7
HexKnight/Amine-Projects
/tictactoe.py
4,717
3.859375
4
class Board: def __init__(self): self.board = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] self.turn = "X" self.available_actions = [[i,j] for i in range(3) for j in range(3)] self.terminal = False def move(self, x, y): #x = int(input("Col number: ")) - 1 #y = int(input("Row number: ")) - 1 if not [x, y] in self.available_actions: print("Already occupied, please choose another spot!") return self.board[y][x] = self.turn self.turn = "X" if self.turn == "O" else "O" self.available_actions.remove([x, y]) def check(self): states = [ self.board[0][0] == self.board[1][0] == self.board[2][0] and not self.board[0][0] == " ", self.board[0][0] == self.board[0][1] == self.board[0][2] and not self.board[0][0] == " ", self.board[0][1] == self.board[1][1] == self.board[2][1] and not self.board[0][1] == " ", self.board[1][0] == self.board[1][1] == self.board[1][2] and not self.board[1][0] == " ", self.board[0][2] == self.board[1][2] == self.board[2][2] and not self.board[0][2] == " ", self.board[2][0] == self.board[2][1] == self.board[2][2] and not self.board[2][0] == " ", self.board[0][0] == self.board[1][1] == self.board[2][2] and not self.board[0][0] == " ", self.board[2][0] == self.board[1][1] == self.board[0][2] and not self.board[2][0] == " ", ] if states[0] or states[1] or states[2] or states[3] or states[4] or states[5] or states[6] or states[7]: return self.turn if (not " " in self.board[0]) and (not " " in self.board[1]) and (not " " in self.board[2]): return "tie" def restart(self): self.board = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] self.terminal = False self.available_actions = [[i,j] for i in range(3) for j in range(3)] def show(self): print("+-----+") print("|{0} {1} {2}|\n|{3} {4} {5}|\n|{6} {7} {8}|".format(*self.board[0], *self.board[1], *self.board[2])) print("+-----+") if __name__ == "__main__": from random import choice, random qtable = dict() prestate = None print("Welcome to TicTacToe! \n") game = Board() while True: if game.turn == "X": action = None if hash(str(game.board)) in qtable: if random() < 1/(1+qtable[hash(str(game.board))]["n"]**2): action = tuple(choice(game.available_actions)) else: for i in qtable[hash(str(game.board))]: if i == "n": continue if action == None: action = i if qtable[hash(str(game.board))][i] > qtable[hash(str(game.board))][action]: action = i qtable[hash(str(game.board))]["n"] += 1 else: state = {tuple(game.available_actions[i]):0 for i in range(len(game.available_actions))} state["n"] = 0 qtable[hash(str(game.board))] = state action = tuple(choice(game.available_actions)) prestate = hash(str(game.board)) preaction = action n = qtable[hash(str(game.board))]["n"] game.move(*action) reward = 0 if game.check() == "X": reward = 1.0 elif game.check() == "O": reward = -1.0 if hash(str(game.board)) in qtable: for i in qtable[hash(str(game.board))]: if i == "n": continue if qtable[hash(str(game.board))][i] > qtable[hash(str(game.board))][action]: action = i qtable[prestate][action] += (1/(1+n**2)) * (qtable[hash(str(game.board))][action] + reward - qtable[prestate][preaction]) qtable[prestate][action] += (1/(1+n**2)) * (reward - qtable[prestate][preaction]) else: action = choice(game.available_actions) game.move(*action) game.show() if not game.check() == None: if game.check() == "tie": print("It's a TIE!") else: print("X" if game.check() == "O" else "O", " is the Winner!") input("Press any key to restart!") game.restart() input("Press any key to exit!")
3264c4ad454b7a1ebd003efb6613896f23202a56
pk1397117/python_study01
/study01/day06/14-reduce的使用.py
1,028
3.71875
4
from functools import reduce # 导入模块的语法 # reduce 以前是一个内置函数 # 内置函数和内置类都在 builtins.py 文件里 # reduce 现在 是 functools 模块里的一个函数 scores = [100, 89, 76, 87] # reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5) print(reduce(lambda x, y: x + y, scores)) print(reduce(lambda x, y: x - y, scores)) print(reduce(lambda x, y: x * y, scores)) print(reduce(lambda x, y: x / y, scores)) students = [ {"name": "zhangsan", "age": 18, "score": 98, "height": 180}, {"name": "lisi", "age": 21, "score": 97, "height": 185}, {"name": "Jack", "age": 22, "score": 100, "height": 175}, {"name": "Tony", "age": 23, "score": 90, "height": 176}, {"name": "Henry", "age": 20, "score": 95, "height": 172} ] # 求所有学生的总年龄 print(sum(map(lambda e: e["age"], students))) print(sum([stu["age"] for stu in students])) print(reduce(lambda x, y: x + y["age"], students, 0)) # reduce(function, sequence, initial=_initial_missing)
9843f33203dcd8b0b849faa3342d9d5f3aa108a6
PankillerG/Public_Projects
/Programming/PycharmProjects/untitled/Python_Start/contest6_K.py
138
3.546875
4
n = int(input()) sumCard = 0 for i in range(1, n + 1): sumCard += i for i in range(n - 1): sumCard -= int(input()) print(sumCard)
160b4c307cf84442147080ed2d69f6dfb3bf390b
tushar8871/python
/dataStructure/calendarr.py
1,203
4.25
4
#genrate calendar without usong module #method to generate calendar def calendar(noOfDays,weekDay): #create list of week day week=["sun","mon","tue","wed","thu","fri","sat"] #create list for dates date=[' ']*(noOfDays+1) for dayDate in range(1,(noOfDays+1)): date[dayDate]=dayDate #check if weekDay is same or not for day in range(len(week)): if weekDay==week[day]: break #print days print("Su Mo Tu We Th Fr Sa") #print dates for i in range(day): print(" ",end=" ") i=1 while (i<=noOfDays): #print the dates if date[i]<10: print("",date[i],end=" ") else: print(date[i],end=" ") #if mod 7 equal to zero then go to next line if (i+day)%7==0: print(" ") i+=1 #get number of days in month and starting week day noOfDays=int(input("Enter number of days in month bw 28-31")) weekDay=input("Input the starting day of month mon,tue,wed,thu,fri,sat,sun : ") if noOfDays >= 28 and noOfDays <= 31: #pass the noOfDays,weekDay to calendar method calendar(noOfDays,weekDay) else: print("Enter correct value between 28 to 31 ! ")
f0591cf68b0c9a120ca277a31e92d934c50ae31a
brubribeiro/Python-WCC
/blackjack.py
333
3.5625
4
#Bruna Ribeiro - 21/11/2019 def blackjack(a,b,c): if a == 11 or b == 11 or c == 11: return sum((a,b,c)) - 10 elif sum((a,b,c)) > 21: print('BUST') else: return sum((a,b,c)) def blackjack1(a,b,c): soma = sum((a,b,c)) if 11 in (a,b,c): return soma - 10 elif soma > 21: print('BUST') else: return soma
671821b972a812326633041a053b6df51a321ae5
gagahpangeran/DDP1
/lab/lab_1/lab01_B_ZZ_Gagah Pangeran Rosfatiputra_1706039566_pertarungan1.py
556
3.921875
4
import turtle panjang = int(input("Masukkan panjang setiap anak tangga: ")) t = turtle.Turtle() t.pendown() #Bagian Kuning t.color('yellow') t.left(90) t.forward(panjang) t.right(90) t.forward(panjang) #Bagian Biru t.color('blue') t.left(90) t.forward(panjang) t.right(90) t.forward(panjang) #Bagian merah t.color('red') t.left(90) t.forward(panjang) t.right(90) t.forward(panjang) #Bagian hijau t.color('green') t.right(90) t.forward(3*panjang) t.right(90) t.forward(3*panjang) t.penup() turtle.exitonclick()
33d196debb6381f34cc1cd5f6988687bb3abb101
turab45/Travel-Python-to-Ml-Bootcamp
/Day 1/prime.py
250
4
4
# Muhammad Turab number = 100 i = 1 factor = 0 while number >= i: if number % i == 0: factor = factor + 1 i = i+1 if factor == 2 or factor == 1: print(number, " is a prime number") else: print(number, " is not a prime number")
bb2387f41b33e7156d3b21bd8521b1a8113a6e07
pubudu08/algorithms
/structures/binary_search_tree.py
6,820
4.25
4
class Node(object): def __init__(self, data): self.data = data self.left_child = None self.right_child = None class BinarySearchTree(object): """ TODO: Add detailed description about binary search tree operations O(logN) time complexity for search, remove and insertion It is important to construct a data structure which has a predictable complexity Facebook Keeps the keys in sorted order so that lookup and other operations can use the principle od binary search Every node can have at most two children left child smaller than the parent right child is greater than the parent why is it good? on every decision we get itd of half of the data in which we are searching o(logN) time complexity height of a tree: the # of layers it contains # of nodes 2^h-1 where h is # of layers In general h ~ O(logN) if this is true the tree is said to be balanced if it is not true tree is unbalanced, which means asymmetric which is a problem We should keep the height of the tree minimum which is h = logN if the tree is unbalanced h = logN relation is no more valid and the operation running is no more logarithmic Average Case Worst Case Space O(N) O(N) Insert O(logN) O(N) Delete O(logN) O(N) Search O(logN) O(N) """ def __init__(self): self.root = None def insert(self, data): """ We start at the root node, if the data we want to insert is greater than the root node we co th the right, if it is smaller we fot he left and so on. we discard half of the tree every time """ if not self.root: self.root = Node(data) else: self.insert_node(data, self.root) def insert_node(self, data, node): if data < node.data: # considering left sub tree if node.left_child: self.insert_node(data, node.left_child) else: node.left_child = Node(data) else: if node.right_child: self.insert_node(data, node.right_child) else: node.right_child = Node(data) def get_min_value(self): if self.root: return self.get_min(self.root) def get_min(self, root): if root.left_child: return self.get_min(root.left_child) return root.data def get_max_value(self): if self.root: return self.get_max(self.root) def get_max(self, root): if root.right_child: return self.get_max(root.right_child) return root.data def find(self, data): """ We start at the root node. if the data we want to find is greater than the root node we fo the right, if it smaller then we go to the left on every decision we discard half of the tree, so it is like binary search in a sorted array O(logN) find the smallest node, we just have to go to the left as far as possible, it will be the smallest find the largest node, we just have to go to the right as far as possible, it will be the largest """ def remove_node(self, data, node): if not node: return node if data < node.data: node.left_child = self.remove_node(data, node.left_child) elif data > node.data: node.right_child = self.remove_node(data, node.right_child) else: if not node.left_child and not node.right_child: print(" removing a leaf node") del node return None if not node.left_child: print(" removing a node with single right child node") temp_node = node.left_child del node return temp_node elif not node.right_child: print(" removing a node with single left child node") temp_node = node.right_child del node return temp_node print(" removing node with two children") temp_node = self.get_predecessor(node.left_child) node.data = temp_node.data node.left_child = self.remove_node(temp_node.data,node.left_child) return node def get_predecessor(self, node): if node.right_child: return self.get_predecessor(node.right_child) return node def remove(self, data): """ soft delete --> we do not remove the node from BST we just mark it has been removed complexity: we have to find the item itself + we have to delete it or set it to NULL ~ O(logN) find operation + O(1) deletion = O(logN) we want to get rid of node that has one child, just we need to update the reference complexity: we have to find the item itself + we have to update the reference ( set parent pointer point to it's grandchild directly ~ O(logN) find operation + O(1) update reference = O(logN) we want to get rid of a node that has two children we have two options: we look for the largest item in the left subtree (predecessor) OR the smallest item in the right subtree (successor) We look for the predecessor ans swap the two nodes, once you done set the node to null We look for the successor ans swap the two nodes, become the case 2, once you done update the node references Time complexity: O(logN) """ if self.root: self.root = self.remove_node(data, self.root) def traverse(self): if self.root: self.in_order_traversal(self.root) def in_order_traversal(self, node): """ we visit the left subtree + root + right subtree by default it will sort items in numnerically or alphebetically """ # visit left subtree recursively if node.left_child: self.in_order_traversal(node.left_child) print("%s", node.data) # print the root node # right subtree if node.right_child: self.in_order_traversal(node.right_child) def pre_order_traversal(self, node): """ we visit the root + left + right subtree """ def post_order_traversal(self, node): """ we visit the left subtree + right + root """ bst = BinarySearchTree() bst.insert(12) bst.insert(5) bst.insert(7) bst.insert(657) bst.insert(234) bst.insert(1) print("Min value", bst.get_min_value()) print("Max value", bst.get_max_value()) bst.remove(5) bst.traverse()
cb19d90bd888a67fcd12032258670b93310877ab
Vivekyadv/DP-Aditya-Verma
/Longest common subsequence/7. longest repeating subsequence.py
1,219
3.859375
4
# Given a string, print the longest repeating subsequence such that the two subsequence # don't have same string character at same position, i.e., any i’th character in the two # subsequences shouldn’t have the same index in the original string. # Example: string = 'aabebcdd' ans = 'abd', len = 3 def func(string): n = len(string) table = [[0]*(n+1) for i in range(n+1)] for i in range(1, n+1): for j in range(1, n+1): if string[i-1] == string[j-1] and i != j: table[i][j] = 1 + table[i-1][j-1] else: table[i][j] = max(table[i-1][j], table[i][j-1]) len_LRS = table[n][n] # print LRS i, j = n, n lrs = '' while i > 0 and j > 0: if string[i-1] == string[j-1] and i != j: lrs = string[i-1] + lrs i -= 1 j -= 1 else: if table[i][j-1] > table[i-1][j]: j -= 1 else: i -= 1 return lrs string = 'aabebcdd' print(func(string)) # Note: for string = 'axxxy' ans is xx # first occurence xx -> (1,2) # second occerence xx -> (2,3) # x at index 0 in xx, 1 != 2 # x at index 1 in xx, 2 != 3
ee9950a25b6788fa77b6c5cc8e0c14e7a400648d
AkshataMShetty/Platform-20
/Training/Python_module/Assignment_1/assgn7.py
381
3.578125
4
string1 = "Global" string2 = "Edge" string3 = string1 +' '+ string2 print string3 print string3.find("Edge") length = len(string3) print "length of string3" print length print string3.split() print string3.replace('a','e') string4 = " messy string " print string4.strip() print string4.rstrip() print string4.lstrip() print string1.upper() print string1.lower()
6504777c3c60cebb48a38bcf06ca9f2e7c1c4e9e
mcxu/code-sandbox
/PythonSandbox/src/misc/subarray_sort_indices.py
1,425
3.96875
4
''' Subarray Sort Indices Given array of integers, return [start,end] indices of the smallest subarray that must be sorted in order for the entire array to be sorted. Input array length >= 2. If array is already sorted return [-1,-1]. Sample input: [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19] Sample output: [3, 9] ''' class Prob: @staticmethod def subarraySort(array): aux = [] for i in range(1, len(array)): if array[i-1] > array[i]: aux.append((i,array[i])) for i in range(len(array)-2, -1, -1): if array[i] > array[i+1]: aux.append((i,array[i])) print("aux: ", aux) if not aux: return [-1,-1] maxTup = max(aux, key = lambda x: x[1]) minTup = min(aux, key = lambda x: x[1]) print("minTup: {}, maxTup: {}".format(minTup, maxTup)) minInd, maxInd = 0, len(array)-1 while array[minInd] <= minTup[1] or array[maxInd] >= maxTup[1]: if array[minInd] <= minTup[1]: minInd += 1 if array[maxInd] >= maxTup[1]: maxInd -= 1 print("minInd: {}, maxInd: {}".format(minInd, maxInd)) return [minInd, maxInd] @staticmethod def test1(): array = [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19] ans= Prob.subarraySort(array) Prob.test1()
4fd3677c8d3464e934baa4e4bb2558401e05ec12
csikosdiana/CodeEval
/Easy/clean_up_the_words.py
562
3.71875
4
data = ['(--9Hello----World...--)', 'Can 0$9 ---you~', '13What213are;11you-123+138doing7'] import string print string.ascii_lowercase print string.ascii_uppercase #import sys #test_cases = open(sys.argv[1], 'r') #data = test_cases.readlines() for test in data: l = len(test) sentence = '' for c in range(0, l): char = test[c] if ((char in string.ascii_lowercase) or (char in string.ascii_uppercase)): sentence = sentence + char else: sentence = sentence + " " sentence = " ".join(sentence.split()) print sentence.lower() #test_cases.close()
5d1d157f3b919b8692115089262b691ed155dc52
ybcc2015/PointToOffer
/stack&queue.py
1,453
4.125
4
# 1.用两个栈实现一个队列 class MyQueue(object): def __init__(self): self.stack1 = [] self.stack2 = [] # 入队 def append_tail(self, value): self.stack1.append(value) # 出队 def delete_head(self): if len(self.stack2) == 0: if len(self.stack1) != 0: while len(self.stack1) != 0: value = self.stack1.pop() self.stack2.append(value) else: raise Exception("queue is empty") head = self.stack2.pop() return head def __len__(self): return len(self.stack1) + len(self.stack2) # 两个队列实现一个栈 class MyStack(object): def __init__(self): self.que1 = MyQueue() self.que2 = MyQueue() # 入栈 def push(self, value): self.que1.append_tail(value) # 出栈 def pop(self): if len(self.que1) == 0: raise Exception("stack is empty") elif len(self.que1) == 1: value = self.que1.delete_head() else: while len(self.que1) != 1: self.que2.append_tail(self.que1.delete_head()) value = self.que1.delete_head() while len(self.que2) != 0: self.que1.append_tail(self.que2.delete_head()) return value if __name__ == '__main__': stack = MyStack()
0f345b332c92cd8999f980dae7af47f2ff8c31b6
marmara-technology/SIKAR-HA
/SIKAR-HA Control Panel/Programlar/entrykayit.py
3,510
3.671875
4
import tkinter.font from tkinter import * from tkinter import messagebox from tkinter import Menu import RPi.GPIO as GPIO import os wait=None rec=None GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) #Numbers GPIOs by physical location def SetAngle(angle): # Angle paramater will be got from user print('go') def SetAngle2(angle): # Angle paramater will be got from user print('go') def SetAngle3(angle): # Angle paramater will be got from user print('go') #MOTOR ANGLES def ServoOn(): x=int(str(angle1.get())) y=int(str(angle2.get())) if x>180 or y>180: messagebox.showerror('TEKİLLİK HATASI', 'Verilebilecek en büyük açı 180 derecedir.') return None SetAngle(x) SetAngle2(y) def kayit(): global status status=False stop=False kayit = Tk() kayit.title("Kayit Ekrani") kayit.geometry('600x200') lbl=Label(kayit,text=" Kaydedilecek Pozisyonu Giriniz") lbl.grid(column=0,row=0,columnspan=4) lbl=Label(kayit,text="Bekleme Süresini Giriniz",width='20') lbl.grid(column=10,row=0) lbl=Label(kayit,text="Tekrar Sayısını Giriniz",width='20') lbl.grid(column=100,row=0) def timereg(): global timvar global inf timvar=0 timvar=float(str(timnt.get())) timvar*=1000 if timvar>400: status=True inf='Zaman degeri kabul mü? :'+ str(status) Label(kayit,text=inf).grid(column=10,row=15) timvar=int(timvar) return True else: status=False inf2='Zaman degeri kabul mü? :' + str(status) Label(kayit,text=inf2).grid(column=10,row=15) return False def tkrreg(): global tkrvar tkrvar=int(str(tkrent.get())) inf3='Tekrar Sayisi :' + str(tkrvar) Label(kayit,text=inf3).grid(column=100,row=15) return True def register (): global regvar global regvar2 regvar=int(str(regent.get())) regvar2=int(str(regent2.get())) kayitlar='Motor1 :' +str(regvar) +' Motor2 :'+str(regvar2) Label(kayit,text=kayitlar).grid(column=0,row=15) return regvar def regOn(): if timereg()==True and tkrreg()==True: for x in range(tkrvar): SetAngle(regvar) SetAngle2(regvar2) kayit.after(timvar) SetAngle(0) SetAngle2(0) if x==tkrvar-1: messagebox.showinfo("Durum","Kayıt İşlemi Tamamlandı") else: messagebox.showerror('EKSIK PARAMETRE','Lütfen gerekli parametreleri tam olarak giriniz') Label(kayit,text='Motor1 Motor2').grid(column=0,row=10,sticky=W) regent= Entry(kayit,width=4) regent.grid(column=0,row=11,sticky=W) regent2= Entry(kayit,width=5) regent2.grid(column=0,row=11) regbtn=Button(kayit,text='Onayla',command = register,width='5') regbtn.grid(column=0,row=20,sticky=W) regOnbtn=Button(kayit,text='Başlat',font=("Arial",18),bg='yellow',fg='blue',command=regOn) regOnbtn.grid(column=10,row=180) regOnbtn.config(height=1,width=10) timnt=Entry(kayit,width=5) timnt.grid(column=10,row=11) timbtn=Button(kayit,text='Onayla',command = timereg) timbtn.grid(column=10,row=20) tkrent=Entry(kayit,width=5) tkrent.grid(column=100,row=11) tkrbtn=Button(kayit,text='Onayla',command = tkrreg) tkrbtn.grid(column=100,row=20) kayit.mainloop() kayit()
2a96172f93189733a5b57218b5fa6f7f3b87d2ed
kholann/python
/lesson3_task2.py
803
3.53125
4
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, # год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def user_data(name, surname, birth_year, city, email, phone): print(f"name: {name}, surname: {surname}, birth_year: {birth_year}, city: {city}, email: {email}, phone: {phone}") user_data(name= 'Anna', surname='Bykova', birth_year=1987, city='Saint Petersburg', email='email@yandex.ru', phone='+79153333333')
54ef88e4a8be18740c67491c0c3b8ae04128577a
Yabby1997/Baekjoon-Online-Judge
/10818.py
250
3.609375
4
numOfCases = int(input()) nums = list(map(int, input().split())) maximum = nums[0] minimum = nums[0] for each in nums: if each > maximum: maximum = each elif each < minimum: minimum = each print("%d %d"%(minimum, maximum))
bdaa840e04a13fb0efd052e5fff20e974653fc5f
gertoska/breakout
/wall.py
761
3.734375
4
import pygame from brick import Brick class Wall(pygame.sprite.Group): def __init__(self, number_of_bricks, width): pygame.sprite.Group.__init__(self) pos_x = 20 pos_y = 70 for i in range(number_of_bricks): color = 'orange' if i >= 45: color = 'yellow' brick = Brick((pos_x, pos_y), color) self.add(brick) pos_x += brick.rect.width i += 1 if i == 15 or i == 30: pos_x = 20 pos_y += brick.rect.height if i == 45: pos_x = 100 pos_y += brick.rect.height if i == 56: pos_x = 140 pos_y += brick.rect.height
8a2f8084e54e949a6f8437305e6fcfc08079ddc3
chasethewind/dndDMG
/pythonProject/my_module/my_functions.py
5,158
3.65625
4
from random import randint import string def sneak_attack(lvl): """ Determines how much damage Shadar's sneak attack does. The amount of times she gets to roll for sneak attack increases by one every two levels, from a base of 1. """ print('Is sneak attack triggered?') sneak = input() if sneak == 'yes': sneak_attack_amt = int(round(((lvl + 0.5)/2), 0)) #rounds to the zeroth place and starts level one at 1 attack #generates a random number for however many sneak atatcks Shadar has which is based on her level sneak_attack_dmg = [(randint(1, 6)) for x in range(sneak_attack_amt)] print(sneak_attack_dmg) sneak_attack_dmg = sum(sneak_attack_dmg) print(sneak_attack_dmg) return int(sneak_attack_dmg) elif sneak == 'no': return 0 def proficiency(lvl): """ Determines how much proficienct Shadar is. Proficiecny increases by one every fourth level with a base of 2. """ proficiency = int((lvl-1)/4) + 2 return proficiency def to_hit(dex, proficiency): """Takes the input dex and proficiency and calculates the to hit. Will show the roll before modifiers are added so that players can declare crit (a 1 or 20 before modifiers) since that has special ramifications. The results are told to the game master who determines if the hit landed and tells you to proceed.""" base_roll = randint(1, 20) print('before modifiers your roll is ', base_roll) base_roll_w_modifiers = int(base_roll + dex + proficiency) print('after modifiers your roll is', base_roll_w_modifiers) print ('Do you have advantage? input "yes" for advantage, "no" for disadvantage, "none" for a normal roll') adv = input() if adv == 'yes': check_for_crit = randint(1,20) print('before modifiers your score is ', check_for_crit) check_for_crit = max(base_roll, check_for_crit) print('before modifiers your max roll was a ', check_for_crit) check_for_crit_total = check_for_crit + dex + int(proficiency) print('after modifiers your adv roll is ', check_for_crit_total) elif adv == 'no': disadv = randint(1,20) print('before modifiers your score is ', disadv) disadv = min(base_roll, disadv) print('before modifiers your lowest roll was ', disadv) disadv_total = disadv + dex + proficiency print('after modifiers your disadvantage roll is ', disadv_total) elif adv == 'none': return base_roll def dual_wielding(dex, proficiency): """Determines if the character is able to hit with her off hand (aka dual wielding). The procedure is the same as the to_hit function. If the hit doesn't land then the players turn ends.""" print('Are you using dual wielding?/ do you need to hit again?') dual = input() if dual == 'yes': off_hand = randint(1, 20) print('before modifiers your off hand hits for', off_hand) off_hand = int(off_hand + dex + int(proficiency)) print ('after modifiers your off hand strikes for ', off_hand) if dual == 'no': return ('Your turn is over') def weapons(dex): """Shadar has an arsenal of different weapons with different stats. This allows the player to select the weapon they want.""" print("What weapons are you using? options are: 'rad sword', 'rapier', 'crossbow', 'curved dagger', 'nec dagger' and 'silver dagger") pick_weapon = input() if pick_weapon == 'rad sword': weapon_dmg = (randint(1, 8)) + dex return weapon_dmg elif pick_weapon == 'rapier': weapon_dmg = randint(1, 8) + dex return weapon_dmg elif pick_weapon =='crossbow': weapon_dmg = (randint(1, 6)) + dex return weapon_dmg elif pick_weapon == 'curved dagger': weapon_dmg = (randint(1, 6)) + dex + 1 #has a special damage increase return weapon_dmg elif pick_weapon == 'nec dagger': weapon_dmg = (randint(1, 6)) + dex return weapon_dmg elif pick_weapon == 'silver dagger': weapon_dmg = (randint(1, 4)) + dex + 2 #has a special damage increase return weapon_dmg else: raise NameError('Sorry you do not have this weapon in your inventory') print('with your dominant hand you deal', weapon_dmg, ' damage') def main_hand_dmg(weapons, dex): print("Did you suceed your to_hit roll?") roll_for_dmg = input() if roll_for_dmg == 'yes': weapon_dmg = weapons(dex) return weapon_dmg elif roll_for_dmg == 'no': weapon_dmg = 0 return weapon_dmg def dual_dmg(weapons, dex): """If the dual wielding attack landed then the player needs to know how much damage they deal, which is based on the weapon they use.""" print('Did your off hand attack hit?') second_attack = input() if second_attack == 'yes': off_hand_attack = weapons(dex) return off_hand_attack elif second_attack == 'no': off_hand_attack = 0 return off_hand_attack
7285c0fb59d55e4e9e26dd14eac3daffe7f7639d
kKunov/W3
/D2/Graph.py
1,671
3.78125
4
class DirectedGraph: def __init__(self): self.nodes = {} def add_node(self, node): self.nodes[node] = [] def add_edge(self, nodeA, nodeB): if nodeA not in self.nodes: self.add_node(nodeA) if nodeB not in self.nodes: self.add_node(nodeB) if nodeB not in self.nodes[nodeA]: self.nodes[nodeA].append(nodeB) def get_neighbors_for(self, node): if node not in self.nodes: print("Ther's no such node!") else: print(self.nodes[node]) def path_between(self, nodeA, nodeB, p=[]): path = [] path += p path += nodeA if nodeA == nodeB: return path if nodeA not in self.nodes: return False for node in self.nodes[nodeA]: if node not in path: new_path = self.path_between(node, nodeB, path) if new_path: return new_path return False def toString(self): for node in self.nodes: print("%s:" % node) self.get_neighbors_for(node) def main(): my_graph = DirectedGraph() my_graph.add_node("A") my_graph.add_node("B") my_graph.add_node("C") my_graph.add_node("D") my_graph.add_node("E") my_graph.add_node("F") my_graph.add_edge("A", "B") my_graph.add_edge("B", "C") my_graph.add_edge("A", "D") my_graph.add_edge("C", "A") my_graph.add_edge("C", "E") my_graph.add_edge("C", "F") my_graph.add_edge("D", "W") print(my_graph.path_between("A", "W")) my_graph.toString() if __name__ == '__main__': main()
4cbd75520ded53d398bd1d52e026bf2cf12e7c58
Manish-Adhikari/Reminderapp
/rem.py
1,105
3.65625
4
import time import datetime import currentfile import os def reminderapp(date_entry,time_entry): year,month,day=date_entry.split('-') hrs,mins,secs=time_entry.split('-') year=int(year);month=int(month);day=int(day) hrs=int(hrs);mins=int(mins);secs=int(secs) epoch= datetime.datetime(year,month,day,hrs,mins,secs).strftime('%s') return epoch if __name__=='__main__': date_entry=input('Enter the date in YYYY-MM-DD form\t') time_entry=input('Enter the time in HRS-MINS-SEC in 24 Hrs Form\t') epoch=reminderapp(date_entry,time_entry) epoch=int(epoch) cepoch=currentfile.current() if epoch>cepoch: msg=input('Enter the Notification Message') while True: cepoch=currentfile.current() cepoch=int(cepoch) if epoch==cepoch: title='REMINDER: :) :)\n ' os.system('notify-send "'+title+'" "'+msg+'"') break; else: head='Error!!! :( \n' mst='Invalid Entry' os.system('notify-send "'+head+'" "'+mst+'"') print('OOPS! Invalid Entry')
13e7f3442783e8ff82db130b612a4bc033152a7d
Vputri/Python-2
/aulia.py
709
3.515625
4
def balok() : print " Menghitung Volume Balok " p= raw_input ("Masukkan Panjang Balok : ") l= raw_input ("Masukkan Lebar Balok : ") t= raw_input ("Masukkan Tinggi Balok : ") volume = int(p)*int(l)*int(t) print "Volume Balok adalah ",volume def lingkaran() : print " Menghitung Volume lingkaran " r=raw_input("Masukkan jari-jari lingkaran : ") keliling= 3.14*int(r)**2 print "Keliling lingkaran adalah ",keliling def kubus() : print " Menghitung Volume Kubus " s=raw_input("Masukkan Sisi Kubus: ") volume = int(s)*int(s)*int(s) print "Volume Kubus adalah ",volume print " PROGRAM HITUNG MATEMATIKA " print lingkaran() print kubus() print balok()
dc23c9f349248c0c943cc38b9be6e6f88efff532
starrye/LeetCode
/A daily topic/2020/may/200516_25. K 个一组翻转链表.py
1,962
3.703125
4
#!/usr/local/bin/python3 # -*- coding:utf-8 -*- """ @author: @file: 25. K 个一组翻转链表.py @time: 2020/5/16 11:00 @desc: """ from typing import List """ 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 k 是一个正整数,它的值小于或等于链表的长度。 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 示例: 给你这个链表:1->2->3->4->5 当 k = 2 时,应当返回: 2->1->4->3->5 当 k = 3 时,应当返回: 3->2->1->4->5   说明: 你的算法只能使用常数的额外空间。 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: prenode = ListNode(-1) prenode.next = head p = prenode p_list = [None for _ in range(k)] while True: # 构建前驱节点 prenode_tmp = p # 获取交换节点 for i in range(k): if p == None: break p = p.next p_list[i] = p # 当前k个范围内有终点 则直接返回 if p is None: break # 反转第一步:prenode指向p_list最后一个元素的地址,p_list第一元素位置指向最后一个元素的下一个元素地址 prenode_tmp.next = p_list[-1] p_list[0].next = p_list[-1].next # 反转元素:具体做法 倒序遍历,当前元素的指针指向前一个元素的地址 for i in range(k-1, 0, -1): p_list[i].next = p_list[i-1] # 修改前驱节点为P_list第一个元素的地址 p = p_list[0] return head
24253ee2e2a3f7295c5efb4d8f25dd8291710d21
rattanakchea/react-chat
/src/components/TabCoditor/files/python.py
131
3.921875
4
str = "hello" for i in range(len(s)) print s[i] ## for in for c in [str, array] ## enumerate for index, c in enumerate(array)
f16d9fdd26d0101a2f9f6cf52309962275ae0175
ppinko/python_exercises
/sort/hard_frugal_gentelman.py
861
3.59375
4
""" https://edabit.com/challenge/RWLWKmGcbp6drWgKB """ def chosen_wine(wines: list): if len(wines) == 0: return None elif len(wines) == 1: return wines[0]['name'] else: wines.sort(key=lambda x: x['price']) return wines[1]['name'] assert chosen_wine([{"name": "Wine A", "price": 8.99}, {"name": "Wine 32", "price": 13.99}, {"name": "Wine 9", "price": 10.99}]) == "Wine 9" assert chosen_wine([{"name": "Wine A", "price": 8.99}, {"name": "Wine B", "price": 9.99}]) == "Wine B" assert chosen_wine([{"name": "Wine A", "price": 8.99}]) == "Wine A" assert chosen_wine([]) is None assert chosen_wine([{"name": "Wine A", "price": 8.99}, {"name": "Wine 389", "price": 109.99}, {"name": "Wine 44", "price": 38.44}, {"name": "Wine 72", "price": 22.77}]) == "Wine 72" print('Success')
79e3d5ab6ab0de16fae130735b04ab6812ea96cf
yell/mnist-challenge
/ml_mnist/utils/_utils.py
3,057
3.84375
4
import sys import time import numpy as np class Stopwatch(object): """ Simple class encapsulating stopwatch. Examples -------- >>> import time >>> with Stopwatch(verbose=True) as s: ... time.sleep(0.1) # doctest: +ELLIPSIS Elapsed time: 0.100... sec >>> with Stopwatch(verbose=False) as s: ... time.sleep(0.1) >>> np.abs(s.elapsed() - 0.1) < 0.01 True """ def __init__(self, verbose=False): self.verbose = verbose if sys.platform == "win32": # on Windows, the best timer is time.clock() self.timerfunc = time.clock else: # on most other platforms, the best timer is time.time() self.timerfunc = time.time self.start_ = None self.elapsed_ = None def __enter__(self, verbose=False): return self.start() def __exit__(self, exc_type, exc_val, exc_tb): elapsed = self.stop().elapsed() if self.verbose: print "Elapsed time: {0:.3f} sec".format(elapsed) def start(self): self.start_ = self.timerfunc() self.elapsed_ = None return self def stop(self): self.elapsed_ = self.timerfunc() - self.start_ self.start_ = None return self def elapsed(self): if self.start_ is None: return self.elapsed_ return self.timerfunc() - self.start_ def print_inline(s): sys.stdout.write(s) sys.stdout.flush() def width_format(x, default_width=8, max_precision=3): len_int_x = len(str(int(x))) width = max(len_int_x, default_width) precision = min(max_precision, max(0, default_width - 1 - len_int_x)) return "{0:{1}.{2}f}".format(x, width, precision) def one_hot(y): """Convert `y` to one-hot encoding. Examples -------- >>> y = [2, 1, 0, 2, 0] >>> one_hot(y) array([[ 0., 0., 1.], [ 0., 1., 0.], [ 1., 0., 0.], [ 0., 0., 1.], [ 1., 0., 0.]]) """ n_classes = np.max(y) + 1 return np.eye(n_classes)[y] def one_hot_decision_function(y): """ Examples -------- >>> y = [[0.1, 0.4, 0.5], ... [0.8, 0.1, 0.1], ... [0.2, 0.2, 0.6], ... [0.3, 0.4, 0.3]] >>> one_hot_decision_function(y) array([[ 0., 0., 1.], [ 1., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.]]) """ z = np.zeros_like(y) z[np.arange(len(z)), np.argmax(y, axis=1)] = 1 return z def unhot(y): """ Map `y` from one-hot encoding to {0, ..., `n_classes` - 1}. Examples -------- >>> y = [[0, 0, 1], ... [0, 1, 0], ... [1, 0, 0], ... [0, 0, 1], ... [1, 0, 0]] >>> unhot(y) array([2, 1, 0, 2, 0]) """ if not isinstance(y, np.ndarray): y = np.asarray(y) _, n_classes = y.shape return y.dot(np.arange(n_classes)) if __name__ == '__main__': # run corresponding tests from testing import run_tests run_tests(__file__)
4d3b5093b02ef405ba6623ece411258c76446747
Gdango/Euler-Project
/Euler3.py
431
3.734375
4
'''The prime factors of 13195 are 5,7,13 and 29. %What is the largest prime factors of the number 600851475143? % 09/22/2018''' import math def isPrime(num): factor = 1 factorproduct = 1 while True: if factorproduct >= num: return factor - 2 elif num % factor == 0: factorproduct *= factor factor += 2 def main(): print(isPrime(600851475143)) main()
4cef225bf04670fd2a109752b441ffbe51c4d764
Hereiam123/Python-Data-Excercises
/Data Visualization with Seaborn/Seaborn Categorical.py
1,132
3.5625
4
import seaborn as sns import numpy as np import matplotlib.pyplot as plt tips = sns.load_dataset('tips') print(tips.head()) # Aggregate Categorical Data via a specific method, average by default #sns.barplot(x='sex', y='total_bill', data=tips, estimator=np.std) # Count plot, estimator is specifically number of occurences #sns.countplot(x='sex', data=tips) # Box plot, shows distribution of categorical data #sns.boxplot(x='day', y='total_bill', data=tips, hue='smoker') # Violin Plots, similar to boxplot # Show distribution of data across a category #sns.violinplot(x='day', y='total_bill', data=tips, hue='sex', split=True) # Draws scatterplot, where one variable is categorical # Jitter helps to differentiate very similar, possibly stacked poiints # sns.stripplot(x='day', y='total_bill', data=tips, # jitter=True, hue='sex', split=True) # Combining Violin above with Swarm below to show # Overall similarity between visual presentation #sns.swarmplot(x='day', y='total_bill', data=tips, color='black') # Good for group comparison sns.factorplot(x='day', y='total_bill', data=tips, kind='bar') plt.show()
24c6a2bdf7eb2a0302372e4a65dda1764f0c0efb
Shinkovatel/python_lesson
/lesson 3/Home missions.py
7,009
3.921875
4
number = int(input('Введите число ')) number += 2 print(number) number = int(input('Введите число ')) while True: if number > 10: print('Число больше загаданного, введите от 0 до 10') number = int(input('Введите число ')) elif number < 0: print('Число меньше нужного, введите от 0 до 10') number = int(input('Введите число ')) elif number <= 10 and number > 0: number = number**2 print('Вы угадали') print('Результат', number) break name = input('введите Имя: ') soname = input('введите Фамилию: ') weght = int(input('Сколько вы весите: ')) age = int(input('введите возраст: ')) if age < 50 and age > 20 and weght > 50 and weght < 120: print(name, soname, age,'лет,', weght, 'кг,', 'Отличное состояние') elif age > 30 and weght < 50 or weght > 120: print(name, soname, age,'лет,', weght, 'кг,', 'Следует занятся собой') elif age > 40 and weght < 50 or weght > 120: print(name, soname, age,'лет,', weght, 'кг,', 'Следует обратится к врачу') # Пробный вариант name = input('введите Имя: ') soname = input('введите Фамилию: ') weght = int(input('Сколько вы весите: ')) age = int(input('введите возраст: ')) if (age < 50 and age > 20 )and (weght > 50 and weght < 120): result = '{} {} {} лет {} кг, Отличное состояние'.format(name,soname,age,weght) print(result) # print(name, soname, age,'лет,',weght, 'кг,', 'Отличное состояние') elif (age < 40 and age > 30) and (weght < 50 or weght > 120): result1 = '{} {} {} лет {} кг, Требуется занятся собой' .format(name,soname,age,weght) print(result1) #elif age < 40 and weght > 120: #result1 = '{} {} {} лет {} кг, Требуется занятся собой'.format(name, soname, age, weght) #print(result1) #print(name, soname, age,'лет,',weght, 'кг,', 'Следует занятся собой') elif age > 40 and weght < 50: result2 = '{} {} {} лет {} кг, Следует обратиться к врачу'.format(name, soname, age, weght) print(result2) elif age > 40 and weght > 120: result2 = '{} {} {} лет {} кг, Следует обратиться к врачу'.format(name, soname, age, weght) print(result2) # ДЗ вторая часть my_list1 = [2,5,8,2,12,12,4] my_list2 = [2,7,12,3] my_list1 = set(my_list1) my_list2 = set(my_list2) print(my_list1 - my_list2) # Другой вариант for el in my_list1: if el in my_list2: my_list1.remove(el) print(my_list1) # использование Генератора print([el for el, in my_list1 if el not in my_list2]) # Задание № 3 # Dat_input = int(input('Введите дату: ')) # month_input = int(input('Введите месяц в цифровом формате: ')) # year_input = int(input('Введите год: ')) Data_input = input('Введите дату в формате dd.mm.gggg') Dates = { '01': 'Первое', '02': 'Второе', '03': 'Третье', '04': 'Первое', '05': 'Пятое', '06': 'Шестое', '07': 'Седьмое', '08': 'Восьмое', '09': 'Девятое', '10': 'Десятое', '11': 'Одинадцатое' } Months = { '01': 'Января', '02': 'Февраля', '03': 'Марта', '04': 'Апреля', '05': 'Мая', '06': 'Июня', '07': 'Июля', '08': 'Августа', '09': 'Сентября', '10': 'Октября', '11': 'Ноября', '12': 'Декабря' } data_day = Data_input[:2] data_month = Data_input[3:5] data_year = Data_input[6:] if data_day in Dates: data_day = Dates[data_day] if data_month in Months: data_month = Months[data_month] print(f" {data_day} {data_month} {data_year} года" ) # Вариант без среза через сплит Data_input = input('Введите дату в формате dd.mm.gggg') Data_split = Data_input.split('.') Dates = { '01': 'Первое', '02': 'Второе', '03': 'Третье', '04': 'Первое', '05': 'Пятое', '06': 'Шестое', '07': 'Седьмое', '08': 'Восьмое', '09': 'Девятое', '10': 'Десятое', '11': 'Одинадцатое' } Months = { '01': 'Января', '02': 'Февраля', '03': 'Марта', '04': 'Апреля', '05': 'Мая', '06': 'Июня', '07': 'Июля', '08': 'Августа', '09': 'Сентября', '10': 'Октября', '11': 'Ноября', '12': 'Декабря' } print(f"{Dates[Data_split[0]]} {Months[Data_split[1]]} {Data_split[2]} года") # Вариант через числовой ключ Data_input = input('Введите дату в формате dd.mm.gggg') Data_split = Data_input.split('.') Dates = { 1: 'Первое', 2: 'Второе', 3: 'Третье', 4: 'Первое', 5: 'Пятое', 6: 'Шестое', 7: 'Седьмое', 8: 'Восьмое', 9: 'Девятое', 10: 'Десятое', 11: 'Одинадцатое' } Months = { 1: 'января', 2: 'февраля', 3: 'марта', 4: 'апреля', 5: 'мая', 6: 'июня', 7: 'июля', 8: 'августа', 9: 'сентября', 10: 'октября', 11: 'ноября', 12: 'декабря' } first_day = Data_split[0] first_el_day = first_day[:1] first_month = Data_split[1] first_el_month = first_month[:1] if int(first_el_day) == 0: first_day = int(first_day[1:]) if int(first_el_month) == 0: first_month = int(first_month[1:]) print(f"{Dates[first_day]} {Months[first_month]} {Data_split[2]} года") # Задание 2.4 (получить список с уникальными элементами) numbers_1= [2, 2, 5, 12, 8, 2, 12] numbers_2 = set(numbers_1) numbers_3 = [] for i in numbers_2: if(numbers_1.count(i) == 1): numbers_3.append(i) print(numbers_3) # Проверка на дубликаты numbers_1 = [2, 2, 5, 12, 8, 2, 12] numbers_1.sort() for i in range (0, len(numbers_1)-1): if numbers_1[i] == numbers_1[i+1]: print (str(numbers_1[i])) # Получение индекса повторяющего списка numbers_1= [2, 2, 5, 12, 8, 2, 12] numbers_2 = set(numbers_1) numbers_3 = [] for i in numbers_2: if(numbers_1.count(i)> 1): index = [i for i, number_2 in enumerate(numbers_1) if numbers_2 == i] numbers_3.append((i, index)) print(numbers_3)
9caf748ce9b2078fe6a557d3d0b57c1d718075a3
crushdig/Data-Science-In-Practice-Project
/LB_project/src/helpers/data_dictionary.py
2,407
3.609375
4
from os import path import pandas as pd from datetime import datetime def save(dataset, # The source dataset. summary, # User defined summary str. include='all', # Summarise all cols in df. reader='read_csv', # How to read df. float_format = lambda x: "{:.2f}".format(x), # A formatter for floats. *args, **kwargs): """ Create and save a data dictionary from a dataset file. #Generate a column based summary description from the dataset using Pandas describe function and related methods. Numeric and categorical fields are handled by Pandas. Missing data counts are added separately. The resulting data description is written to a file, named after the source dataset, with the addition of .txt and saved in the same directory as the source. Args: dataset: pathname to dataset file. summary: user provided summary text to add to data dictionary. reader: a reader for the dataset filetype (default: read_pickle). float_format: a floating point formatter for floats. """ # The dataset basename. dataset_basename = path.basename(dataset) # Generate a name for the resulting data dictionary file. dd_filename = dataset + '.txt' # Read the dataset using the reader and any args provided. df = getattr(pd, reader)(dataset, *args, **kwargs) # Generate the data dictionary as a dataframe. dd = df.describe(include=include).T # Add cols to count missing values. missing = df.isnull().sum() dd['Missing'] = missing dd['%Missing'] = 100*missing/len(df) # Save dictionary and summary info. with open(dd_filename, 'w') as f: # Write the header info. f.write('Data dictionary for {} @ {}\n'.format( dataset_basename, str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))) f.write('Dataset shape, {} rows x {} columns.\n\n'.format(df.shape[0], df.shape[1])) f.write(summary+'\n\n\n') # Write the summary. f.write('Data Dictionary\n---------------\n') f.write(dd.to_string(na_rep='-', float_format=float_format)) # Write the dataframe description. return dd
b10012bc373e0239b4a19ed7c725417c4bf36332
bushki/python-tutorial
/lists.py
729
4
4
# List is a collection like JS array, allows dupes # create list numbers = [5,3,1] fruits = ['apples', 'oranges', 'grapes', 'bananas'] print (type(fruits)) # using constructor numbers2 = list((4,7,3)) print(numbers, numbers2) # get value print(fruits[2]) # get length print(len(fruits)) # append to end list fruits.append('papaya') print(fruits) # remove from list fruits.remove('grapes') print(fruits) # insert to specific position fruits.insert(1, 'pear') print(fruits) # remove from position fruits.pop(0) print(fruits) # change value fruits[0] = 'strawberries' # reverse list fruits.reverse() print(fruits) # sort alpha fruits.sort() print(fruits) # reverse sort fruits.sort(reverse=True) print(fruits)
e10a0415651b0398cb41981685927f070530a074
Bardia95/daily-coding-problems
/code-signal-arcade-universe/intro/python3/sum_up_numbers.py
817
4.25
4
import re def sum_up_numbers(s): numbers = re.findall(r"\d+", s) return sum([int(x) for x in numbers]) """ CodeMaster has just returned from shopping. He scanned the check of the items he bought and gave the resulting string to Ratiorg to figure out the total number of purchased items. Since Ratiorg is a bot he is definitely going to automate it, so he needs a program that sums up all the numbers which appear in the given input. Help Ratiorg by writing a function that returns the sum of numbers that appear in the given inputString. Example For inputString = "2 apples, 12 oranges", the output should be sumUpNumbers(inputString) = 14. Input/Output [execution time limit] 4 seconds (py3) [input] string inputString Guaranteed constraints: 0 ≤ inputString.length ≤ 105. [output] integer"""
3fb7e27addfa650e87a1fda52e18adf299bbedd2
tcano2003/ucsc-python-for-programmers
/code/lab_05_Important_Trick/lab05_2.py
377
3.546875
4
#!/usr/bin/env python """Interactive vowel counter.""" import lab05_1 import sys def main(): while True: sys.stdout.write("Phrase: ") count_this = sys.stdin.readline() if count_this == '\n': break sys.stdout.write("... has %d vowels.\n" % ( lab05_1.CountVowels(count_this))) if __name__ == '__main__': main()
bff7bec5517f455a14205b4c02a9397423d50dbd
theharshitgarg/leetcode_challenges
/practice/add_numbers_linked_list.py
2,035
3.859375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def get_linked_list(arr): lst = None for key, val in enumerate(arr): new_node = ListNode(val) if lst: new_node.next = lst lst = new_node return lst class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = None carry = 0 temp = l1 tail = None while l1 and l2: n_sum = (l1.val+l2.val+carry)%10 carry = (l1.val+l2.val+carry)/10 new_node = ListNode(n_sum) if not head: head = new_node tail = new_node else: tail.next = new_node tail = new_node l1 = l1.next l2 = l2.next remaining = l1 or l2 while remaining: n_sum = (remaining.val+carry)%10 carry = (remaining.val+carry)/10 new_node = ListNode(n_sum) if not head: head = new_node tail = new_node else: tail.next = new_node tail = new_node remaining = remaining.next if carry: new_node = ListNode(carry) if not head: head = new_node tail = new_node else: tail.next = new_node tail = new_node return head def print_list(head): while head: print head.val head = head.next sol = Solution() print_list(sol.addTwoNumbers(get_linked_list([2,4,3]), get_linked_list([5,6,4]))) print_list(sol.addTwoNumbers(get_linked_list([1,2,3]), get_linked_list([1,2,3]))) print_list(sol.addTwoNumbers(get_linked_list([2,4,3]), get_linked_list([5,6,4]))) print_list(sol.addTwoNumbers(get_linked_list([1,8]), get_linked_list([0])))
37b877f57e7baa836650839f2d577cc66ae795f1
akshaybab/phrase-playlist-generator
/playlist.py
4,192
3.75
4
# This file contains functions that interact with the Spotify API for non-authentication actions # such as creating a playlist and searching for songs def create_playlist(sentence, spotify): """Creates the phrase playlist. Args: sentence (str): the phrase that will be turned into a playlist. spotify (Spotify Client API object): the Spotify client object. Returns: str: the ID of the generated phrase playlist. None: if inputs were not valid or none of the input could be translated into song """ # if there is no input if not sentence: return None else: # truncate to first 100 characters just in case the user decided to inspect element to bypass character limit sentence = sentence[:100] tokens = sentence.split(' ') songs = [] # remove null results for token in tokens: if token_to_song(token, spotify) is not None: songs.append(token_to_song(token, spotify)) # no songs were found if not songs: return None # if songs is not empty, create a playlist playlist = spotify.user_playlist_create(user=spotify.me()['id'], name='Your Phrase Playlist', public=True, collaborative=False, description='Created using the Spotify Phrase Playlist Generator: https://phrase-playlist-generator.herokuapp.com.') # add the songs to the playlist spotify.user_playlist_add_tracks(user=spotify.me()['id'], playlist_id=playlist['id'], tracks=songs, position=None) return playlist['id'] def token_to_song(token, spotify): """Finds a song whose title is the token, ignoring case. Args: token (str): the word to be found. spotify (Spotify Client API object): the Spotify client object. Returns: str: the track URI if the song was found None: if the song was not found by checking the maximum amount of songs spotify allows OR if there were no results to start with. """ # excluding common terms that do not have song equivalents if token in ['a', 'to', 'the']: print(f'Song: \'{token}\' was excluded from the search because it is a known non-existent song.') return None # hard-coded "and" because it is a common phrase that is difficult to find by Spotify search if token.lower() == 'and': return '5cIZoKmBiFgjabaBG0D9fO' banned = [] # words to exclude from search MAX_QUERY_LENGTH = 1000 # Spotify's limit banned_suffix = "" # the suffix that will be added to the search query query = f"q='track:'{token}{banned_suffix}" # go through 1000 offsets and find a matching song for offset in range(0, 1000, 7): if len(banned) != 0: banned_suffix = " NOT " + " NOT ".join(word for word in banned) # print(f"q=track:{token}{banned_suffix}") # the search results, excluding banned terms tracks = spotify.search(q='track:' + token + banned_suffix, type='track', limit=50, offset=offset)['tracks']['items'] # no tracks were found if not tracks: # print(f'No songs were found for the search term {token}.') return None # check all tracks in results for a match for track in tracks: if track['name'].lower() == token.lower(): # print(f'Song \'{track["name"]}\' was found with an offset of {offset}!') return track['uri'] else: # reduces future search results by adding all "extra" words to a banned list words = track['name'].split(' ') for word in words: # makes sure to not add too many to banned list so that query is within Spotify's character limit if word.lower() != token.lower() and len(banned) < 20: banned.append(word) # reset offset to search with new query that excludes banned words offset = 0 # print(f'Song: \'{token}\' exhausted offset.') # nothing was found after going through all offsets return None
3de29705377d3e93b0eb2b547e8bdcf02c679ee9
cosmosZhou/sympy
/axiom/sets/el/imply/el/inverse/interval.py
1,378
3.625
4
from util import * @apply def apply(given): x, self = given.of(Element) a, b = self.of(Interval) if a.is_positive: domain = Interval(1 / b, 1 / a, left_open=self.right_open, right_open=self.left_open) elif b.is_negative: domain = Interval(1 / a, 1 / b, left_open=self.right_open, right_open=self.left_open) elif a == 0 and self.left_open: domain = Interval(1 / b, oo, left_open=self.right_open, right_open=self.left_open) elif b == 0 and self.right_open: domain = Interval(-oo, 1 / a, left_open=self.right_open, right_open=self.left_open) return Element(1 / x, domain) @prove def prove(Eq): from axiom import sets, algebra x, b = Symbol(real=True) a = Symbol(real=True, positive=True) Eq << apply(Element(x, Interval(a, b))) Eq << sets.el_interval.imply.et.apply(Eq[0]) Eq <<= algebra.ge.imply.le.inverse.apply(Eq[-2]), algebra.ge.imply.gt_zero.apply(Eq[-2]) Eq << algebra.gt_zero.imply.gt_zero.div.apply(Eq[-1]) Eq <<= algebra.gt_zero.le.imply.le.mul.apply(Eq[-1], Eq[3]), algebra.gt.le.imply.gt.transit.apply(Eq[-2], Eq[3]) Eq << algebra.gt_zero.imply.gt_zero.div.apply(Eq[-1]) Eq <<= algebra.gt_zero.ge.imply.ge.mul.apply(Eq[-1], Eq[-3]) Eq << sets.ge.le.imply.el.interval.apply(Eq[-1], Eq[4]) if __name__ == '__main__': run() # created on 2020-06-21
c0e435ecca28feb41f535336072b36ebfdc473b0
ChemicalMushroom/MyFirstPython
/zjazd2/kolekcje/zadanie4.py
373
3.65625
4
# napisz program wypisujący wszystkie liczby od 0 do 100,podzielne przez 3 lub podzielne przez 5.Wypisz także jak dużó takich liczb wystąpiło w tym przedziale ile_podzielnych = 0 for i in range(101): if i % 3 == 0 or i & 5 == 0: ile_podzielnych += 1 print(i) print(f'W przedziale 0-100 jest {ile_podzielnych} liczb podzielnych przez 3 lub 5')
6ad14ae8773e269b7d1209f215e96d0f7ba6bac7
iausteenlova/HACKER-RANK
/PYTHON/students-marks.py
532
3.984375
4
#!/usr/bin/env python # coding: utf-8 marksheet=[] scorelist=[] if __name__ == '__main__': for _ in range(int(input("Enter no. of students"))): name = input("name :") score = float(input("marks :")) marksheet+=[[name,score]] scorelist+=[score] b=sorted(list(set(scorelist)))[1] for name,score in sorted(marksheet): if score==b: print(f"The second highest scorer is {name}. and the score is {b}.")
82755ff6facdda95a0120e3766982aa29e4ea3db
Sen2k9/Algorithm-and-Problem-Solving
/leetcode_problems/559_Maximum_Depth_of_N_ary-Tree.py
1,693
3.734375
4
""" Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: 3 Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: 5 Constraints: The depth of the n-ary tree is less than or equal to 1000. The total number of nodes is between [0, 10^4]. """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root): # Solution 1: self # if not root: # return 0 # queue = [root] # dic = {} # dic[root] = 1 # level = [dic[root]] # while queue: # root = queue.pop() # if root.children: # for each in root.children: # queue += [each] # dic[each] = dic[root]+1 # level.append(dic[root] + 1) # # print(dic) # # print(level) # return max(level) # Solution 2: faster if not root: return 0 depth = 1 queue = [] queue.append((root, 1)) while queue: (node, d) = queue.pop() depth = max(depth, d) for each in node.children: queue.append((each, d + 1)) return depth
07172c6b0ba35bedb7200aaccc1359f0406b52a1
dundunmao/lint_leet
/mycode/lintcode/Binary Search/414 divide-two-integers.py
2,380
3.5625
4
# coding:utf-8 # 将两个整数相除,要求不使用乘法、除法和 mod 运算符。 # # 如果溢出,返回 2147483647 。 # # 您在真实的面试中是否遇到过这个题? Yes # 样例 # 给定被除数 = 100 ,除数 = 9,返回 11。 # 第一次减9,第二次减9+9=18,第三次减18+18 = 36,第四次减36+36=72,第五次减72+72=144>100了,所以从100-72=28重新减9 class Solution(object): def divide1(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend == 0: return 0 if divisor == 0: return float('inf') flag = True if dividend < 0 and divisor > 0: flag = False if dividend > 0 and divisor < 0: flag = False dividend = abs(dividend) divisor = abs(divisor) res = 0 while dividend >= divisor: count, left = self.count(dividend, divisor) # print count, left res += count dividend = left # print res if flag == False: return -res else: return res def count(self, dividend, divisor): count = 1 count_left = 1 dividend_left = 0 while dividend - divisor > 0: count_left = count dividend_left = dividend - divisor divisor = divisor + divisor count = count * 2 return count_left, dividend_left # 答案 def divide(self, dividend, divisor): # write your code here INT_MAX = 2147483647 if divisor == 0: return INT_MAX if dividend > 0 and divisor < 0 or dividend < 0 and divisor > 0: neg = True else: neg = False a = abs(dividend) b = abs(divisor) ans = 0 shift = 31 while shift >= 0: if a >= (b << shift): # 9<<3(左移3位)相当于9 * 2^3=9*8=72 a -= (b << shift) ans += (1 << shift) #1<<1(左移1位)相当于1 * 2^1=2 shift -= 1 if neg: ans = - ans if ans > INT_MAX: return INT_MAX return ans if __name__ == "__main__": a = 100 b = 9 s = Solution() # print s.helper(b) print s.divide(a,b)