blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b8ecc471b73c1c9ff01b74835b490b29a803b8db
giovanna96/Python-Exercises
/Divisors.py
279
4.125
4
#Practice Python #Create a program that asks the user for a number and then prints out a list of all the divisors of that number. divisor = [] value = int(input("enter a number: \n")) for i in range(value): if value%(i+1)==0: divisor.append(i+1) print(divisor)
true
b4b8658f9f4ad759f4111193d3763690ad9265b3
wahome24/Udemy-Python-Bible-Course-Projects
/Project 10.py
1,420
4.4375
4
#This is a bank simulator project using classes and objects class Bank: #setting a default balance def __init__(self,name,pin,balance=500): self.name = name self.pin = pin self.balance = 500 #method to deposit money def deposit(self,amount): self.balance += amount print(f'Your new balance is {self.balance}') #method to withdraw money def withdraw(self,amount): if self.balance >= amount: self.balance -= amount print(f'{amount} Has been withdrawn, Your new balance is {self.balance}') else: print('Insufficient balance') #method to display default balance def statement(self): print(f'Welcome {self.name},your current balance is {self.balance}') print('Welcome to Ashton Bank! Provide your details below: ') print() #get user input name = input('Enter Account Name: ') pin = input('Enter pin: ') #create a savings account object and pass in user input savings= Bank(name,pin) #display balance savings.statement() print() #loop to simulate deposit and withdrawal of money choice = input('Do you want to deposit or withdraw or quit?: ').lower() while choice != 'quit': if choice =='deposit': amount = int(input('Enter amount: ')) savings.deposit(amount) elif choice =='withdraw': amount = int(input('Enter amount: ')) savings.withdraw(amount) choice = input('Do you want to deposit or withdraw or quit?: ').lower()
true
cebc11a76eba589bec28dd26b3a4bab75e1e5ee8
shashankmalik/Python_Learning
/Week_4/Modifying the Contents of a List.py
787
4.34375
4
# The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list. def skip_elements(elements): # Initialize variables new_list = [] i = 0 # Iterate through the list for i in elements: # Does this element belong in the resulting list? if elements!=new_list: # Add this element to the resulting list new_list = elements # Increment i i return new_list[0::2] print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] print(skip_elements([])) # Should be []
true
4d540640c41d61c2472b73dceac524eb6494797e
chao-shi/lclc
/489_robot_cleaner_h/main.py
2,788
4.125
4
# """ # This is the robot's control interface. # You should not implement it, or speculate about its implementation # """ #class Robot(object): # def move(self): # """ # Returns true if the cell in front is open and robot moves into the cell. # Returns false if the cell in front is blocked and robot stays in the current cell. # :rtype bool # """ # # def turnLeft(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def turnRight(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def clean(self): # """ # Clean the current cell. # :rtype void # """ class Solution(object): def cleanRoom(self, robot): """ :type robot: Robot :rtype: None """ # Smart to use direction vector to determine where to turn self.d = 0 dir_v = [(0, 1), (1, 0), (0, -1), (-1, 0)] cleaned = set() def orient(i_1, j_1, i, j): v = (i_1 - i, j_1 - j) idx = dir_v.index(v) if (idx - self.d) % 4 == 1: robot.turnRight() elif (idx - self.d) % 4 == 2: robot.turnRight() robot.turnRight() elif (idx - self.d) % 4 == 3: robot.turnLeft() self.d = idx # Optimize here def gen_direction(): # return [(0, 1), (1, 0), (0, -1), (-1, 0)] # Optimization makes orient only one operation # no matter result of the wall return dir_v[self.d:] + dir_v[:self.d] # moved to i, j, moved from i_prev, j_prev def recur(i, j, i_prev, j_prev): if (i, j) not in cleaned: robot.clean() cleaned.add((i, j)) for v in gen_direction(): i_1, j_1 = i + v[0], j + v[1] if (i_1, j_1) not in cleaned: orient(i_1, j_1, i, j) if robot.move(): recur(i_1, j_1, i, j) if i_prev != None and j_prev != None: orient(i_prev, j_prev, i, j) robot.move() recur(0, 0, None, None) # Key point is to use the index, fit the orient function is very universal. # This approach is very efficient # Better than top voted solution. The top voted will go back and forth but only clean once. # Case of corner # # 1 # 0 -> 01 # 1 # Will go left. # The turning is very efficient !!!! Check if yourself
true
93897a144a08baf27692f9dd52da610be41c0ad3
p-perras/absp_projects
/table_printer/tablePrinter.py
788
4.1875
4
# !python3 # tablePrinter.py # ABSP - Chapter 6 def print_table(table): """ Summary: Prints a table of items right justified. Args: table (list): A 2d list of items to print. """ # Get the max length string of each row. rowMaxLen = [] for row in range(len(table)): rowMaxLen.append(max([len(col) for col in table[row]])) # Print table right justified. for col in range(len(table[0])): for row in range(len(table)): print(table[row][col].rjust(rowMaxLen[row]), end=' ') print() if __name__ == '__main__': tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] print_table(tableData)
true
fc607af81e8f640a2dce4593f55301346b268054
rubenhortas/python_examples
/native_datatypes/none.py
759
4.53125
5
#!/usr/bin/env python3 # None is a null number # Comparing None to anything other than None will always return False # None is the only null number # It has its own datatype (NoneType) # You can assign None to any variable, but you can not create other NoneType objects CTE_NONE1 = None CTE_NONE2 = None if __name__ == '__main__': print("None:") print(f"None == False -> {None == False}") # False print(f"None == 0 -> {None == 0}") # False print(f"None == '' -> {None == ''}") # False print(f"None == var_none -> {None == CTE_NONE1}") # True print(f"var_none == var_none2 -> {CTE_NONE1 == CTE_NONE2}") # True # In a boolean context None is False if not None: print("In a boolean context None is always False")
true
b4642af405871a89e0e22fc7a93763896ad1c240
EngageTrooper/Basic_Calculator_Python
/Calculator_Fle.py
820
4.15625
4
def add(num1,num2): return num1 + num2 def subtract(num1,num2): return num1 - num2 def multiply(num1,num2): return num1 * num2 def divide(num1,num2): return num1 / num2 print("Please Select Operation -\n" \ "1.Add \n" \ "2.Subtract \n" \ "3.Multiply \n" \ "4.Divide \n" ) select = int(input('Please Select Operation to Run 1,2,3,4;')) number1 = int(input("Enter 1st Number:")) number2 = int(input("Enter 2nd Number:")) if select == 1: print(number1, "+", number2, '=', add(number1,number2)) elif select == 2: print(number1, "-", number2, "=" , subtract(number1,number2)) elif select == 3: print(number1, "*", number2, "=", multiply(number1,number2)) elif select == 4: print(number1, "/", number2, "=", divide(number1,number2)) else: print("Invalid Input")
false
f86482889f39d990b99cd3ccb066a332e34eaf32
pillofoos/Ejemplos
/TomaDecisiones.py
636
4.1875
4
#Archivo: TomaDecisiones.py #Descripcion: Ejemplo en el que se muestra la utilizacion de la sentencia if, if..else, if..elif..else # la funcion input y la utilizacion del depurador (antes y despues de conversion) antiguedad = (int)(input("Ingrese la antiguedad en años:")) if antiguedad > 5: print("Le corresponden mas de 15 dias") else: print("Le corresponden solo 15 dias de licencia") if antiguedad <=5: dias_licencia = 15 elif 5< antiguedad <=10: dias_licencia=20 elif 10< antiguedad <=15: dias_licencia = 25 else: dias_licencia = 35 print(f"Le corresponden {dias_licencia} dias de licencia")
false
8f7e68843db46063d1ea23e20f305fda2408d991
zhenghaoyang/PythonCode
/ex15.py
1,317
4.15625
4
# --coding: utf-8 -- #从sys模块导入argv from sys import argv #用户输入参数解包 script,filename = argv #打开文件,赋值给txt txt = open(filename) #打印出文件名 print "Here's your file %r:"%filename #打印出txt变量读取文件的文本 #txt.close() print txt.read() txt.close() print "Type the filename again:" #读取用户输入的参数 file_again = raw_input(">") #读取用户输入的文件名,读取其中的文本,赋值给txt_again txt_again = open(file_again) #打印出txt_again读取到的文本 print txt_again.read() txt_again.close() #加分题 #与类和实例无绑定关系的function都属于函数(function); #与类和实例有绑定关系的function都属于方法(method)。 """print "Type the filename again:" #读取用户输入的参数 file_again = raw_input(">") #读取用户输入的文件名,读取其中的文本,赋值给txt_again txt_again = open(file_again) #打印出txt_again读取到的文本 print txt_again.read() """ #只是用 raw_input 写这个脚本,想想那种得到文件名称的方法更好,以及为什么。 #raw_input,可拓展行好 ''' >>> txt = open('D:\PythonCode\ex15_sample.txt') >>> txt.read() 'This is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.' '''
false
cd22aa8ee2bc1ba44c8af3f5bd7d880c7edac4eb
krishnavetthi/Python
/hello.py
817
4.5
4
message = "Hello World" print(message) # In a certain encrypted message which has information about the location(area, city), # the characters are jumbled such that first character of the first word is followed by the first character of the second word, # then it is followed by second character of the first word and so on #In other words, let’s say the location is bandra,mumbai #The encrypted message says ‘bmaunmdbraai’ #Let’s say the size or length of the two words wouldn’t match then the smaller word is appended with # and then encrypted in the above format. input_str = input("Enter") message1 = input_str[0::2] message2 = input_str[1::2] print(message1.strip('#') + "," + message2.strip('#')) #String Methods # upper() # lower() # strip() # lstrip() # rstrip() # count(substring, beg, end)
true
f4fad1000ed28895c819b3bc71a98e7a9f3e87b6
ofreshy/interviews
/hackerrank/medium/merge_the_tools.py
2,042
4.46875
4
""" Consider the following: A string, , of length where . An integer, , where is a factor of . We can split into substrings where each subtring, , consists of a contiguous block of characters in . Then, use each to create string such that: The characters in are a subsequence of the characters in . Any repeat occurrence of a character is removed from the string such that each character in occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string . Given and , print lines where each line denotes string . Example There are three substrings of length to consider: 'AAA', 'BCA' and 'DDE'. The first substring is all 'A' characters, so . The second substring has all distinct characters, so . The third substring has different characters, so . Note that a subsequence maintains the original order of characters encountered. The order of characters in each subsequence shown is important. Function Description Complete the merge_the_tools function in the editor below. merge_the_tools has the following parameters: string s: the string to analyze int k: the size of substrings to analyze Prints Print each subsequence on a new line. There will be of them. No return value is expected. Input Format The first line contains a single string, . The second line contains an integer, , the length of each substring. Constraints , where is the length of It is guaranteed that is a multiple of . """ def merge_the_tools(string, k): def remove_duplicate(chunk): duplicates = set() uniq = "" for c in chunk: if c not in duplicates: duplicates.add(c) uniq += c return uniq num_chunks = int((len(string)+1)/k) chunks = [string[(i*k):((i+1)*k)] for i in range(num_chunks)] removed = [remove_duplicate(chunk) for chunk in chunks] return removed print(merge_the_tools("ABCDEE", 3)) print(merge_the_tools("ABCDEE", 2))
true
06f8cf70cd26e9c71b989fcb63f7525fb4fc3fff
ofreshy/interviews
/interviewcake/apple_stock.py
2,451
4.21875
4
# -*- coding: utf-8 -*- """ Suppose we could access yesterday's stock prices as a list, where: The values are the price in dollars of Apple stock. A higher index indicates a later time. So if the stock cost $500 at 10:30am and $550 at 11:00am, then: stock_prices_yesterday[60] = 500 Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. For example: stock_prices_yesterday = [10, 7, 5, 8, 11, 9] get_max_profit(stock_prices_yesterday) # returns 6 (buying for $5 and selling for $11) No "shorting"—you must buy before you sell. You may not buy and sell in the same time step (at least 1 minute must pass). """ def get_max_profit(stock_prices_yesterday): """ :param stock_prices_yesterday: list of stock prices. Must have at least 2 elements :return: best profit that could have been gained throughout the day """ min_price = stock_prices_yesterday[0] max_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0] for current_price in stock_prices_yesterday[1:]: # see what our profit would be if we bought at the # min price and sold at the current price potential_profit = current_price - min_price # update max_profit if we can do better max_profit = max(max_profit, potential_profit) # update min_price so it's always # the lowest price we've seen so far min_price = min(min_price, current_price) return max_profit def get_max_profit_brute(stock_prices_yesterday): """ :param stock_prices_yesterday: list of stock prices. Must have at least 2 elements :return: best profit that could have been gained throughout the day """ n = len(stock_prices_yesterday) return max([ max([stock_prices_yesterday[j] - stock_prices_yesterday[i] for j in range(i + 1, n)]) for i in range(n - 1) ]) assert get_max_profit([10, 7, 5, 8, 11, 9]) == 6 assert get_max_profit([10, 10, 9, 7]) == 0 assert get_max_profit([10, 10, 9, 7]) == 0 assert get_max_profit([10, 3, 1, 16]) == 15 assert get_max_profit([10, 1, 3, 16]) == 15 assert get_max_profit_brute([10, 7, 5, 8, 11, 9]) == 6 assert get_max_profit_brute([10, 10, 9, 7]) == 0 assert get_max_profit_brute([10, 10, 9, 7]) == 0 assert get_max_profit_brute([10, 3, 1, 16]) == 15 assert get_max_profit_brute([10, 1, 3, 16]) == 15
true
7ddd97ed6cc317d4fdf9fc1731d8425d2eb3b6a4
gunjan-madan/Namith
/Module4/1.3.py
915
4.40625
4
#Real Life Problems '''Task 1: Delivery Charges''' print("***** Task 1: *****") print() # Create a program that takes the following input from the user: # - The total number of sand sack and cement sack # - Weight of each sack [Hint: use for loop to get the weight] # - Use a variable to which the weight of the sack gets added as entered [Hint: calculate this within the for loop] # - Calculates the total cost if each sack cost INR 300 [ outside the for loop] # So let's get started '''Task 2: Lets go Outdoors''' print("***** Task 2: *****") print() #Write a program that takes care of outdoor field trips for kids. # The program needs to: # - Take the total number of kids (Number cannot be more than 8) # - Get the name, and address for each kid # The program must display the total cost for the field trip where # - Cost for food for each kid is INR 500 # - Cost for travel for each kid is INR 1000
true
c8b8060d5aeb1374f0ef0bb89f436884e1b32748
gunjan-madan/Namith
/Module2/3.1.py
1,328
4.71875
5
# In the previous lesson, you used if-elif-else statements to create a menu based program. # Now let us take a look at using nested if-elif statements in creating menu based programs. '''Task 1: Nested If-else''' print() print("*** Task 1: ***") print() #Make a variable like winning_number and assign any number to it between 1 and 20. #Ask user to guess a number between 1 and 20. (Take input) #if user guessed correctly, print "YOU WIN" #if user didn't guessed correctly then: #if user guessed lower than actual number, then print "TOO LOW" #if user guessed lower than actual number, then print "TOO HIGH" '''Task 2: Nested If-else''' print() print("*** Task 2: ***") print() #This is a program to tell User the shipping cost based on the country and the weight. #Write a Program that takes two inputs: country_code(AU/US) and weight of the product. #Use the following conditions to find the shipping cost #country Product Size Shippping cost #US less than 1kg $5 #US between 1 and 2kg $10 #US greater than 2kg $20 #AU less than 1kg $10 #AU between 1 and 2kg $15 #AU greater than 2kg $25 # print("This Program will caluculate Shipping Cost")
true
552c0f6239df522b27684179f216efe7b10a7037
gunjan-madan/Namith
/Module2/1.3.py
1,705
4.21875
4
# You used the if elif statement to handle multiple conditions. # What if you have 10 conditions to evaluate? Will you write 10 if..elif statements? # Is it possible to check for more than one condition in a single if statement or elif statement? # Let's check it out """-----------Task 1: All in One ---------------""" print(" ") print("*** Task 1: ***") # Do you know what are isosceles and scalene triangles? # Write a program to check if a triangle is equilateral, scalene or isosceles. """-----------Task 1.2: All in One ---------------""" print(" ") print("*** Task 1.2: ***") #The program takes a number as an input #Program shall check if the number is divisible by both 3 and 4 """---------Task 2: Its raining Discount -------------""" print(" ") print("*** Task 2: ***") # Your store is giving a discount on the total purchase amount based on customer membership. # Write a program that calculates the discounted amount based on the below mentioned conditions: # If membership is silver, 5% discount # If membership is silver+ or gold, discount is 10% # If membership is gold+ or diamond, discount is 15% # if membership is platinum membership discount is 20% """---------Task 3: Theme Rides -------------""" print(" ") print("*** Task 3: ***") # You are managing the ticket counter at Imaginika Theme Park. Based on the age of the entrant, you issue tickets for the rides" # Age between 5 and 7 :Toon Tango, Net Walk # Age between 8 and 12: Wonder Splash, Termite Coaster Train # Age greater 13: Hang Glider, Wave Rider # If the age criteria does not match they can go for the nature walks # Write a program that grants access to the rides based on the age conditions.
true
f36fd365929003b92229a08a013b4cf1af4cc5bd
NasserAbuchaibe/holbertonschool-web_back_end
/0x00-python_variable_annotations/1-concat.py
383
4.21875
4
#!/usr/bin/env python3 """Write a type-annotated function concat that takes a string str1 and a string str2 as arguments and returns a concatenated string """ def concat(str1: str, str2: str) -> str: """[Concat two str] Args: str1 (str): [string 1] str2 (str): [string 2] Returns: str: [concatenated string] """ return str1 + str2
true
31bc1789c9cddfef609d48fc36f7c1ecb0542864
Lionelding/EfficientPython
/ConcurrencyAndParallelism/36a_MultiProcessing.py
2,434
4.46875
4
# Item 36: Multi-processing """ * For CPU intensive jobs, multiprocessing is faster Because the more CPUs, the faster * For IO intensive jobs, multithreading is faster Because the cpu needs to wait for the I/O despite how many CPUs available GIL is the bottleneck. * Multi-core multi-threading is worse than single core multithreading. * Mutli-core multi-processing is better since each process has an independent GIL * Example 1: single process * Example 2: multiprocess * Example 3: multiprocess + Pool * Example 4: multiprocess shares data with Queue """ import os import time import random from multiprocessing import Process, Pool, cpu_count, Queue ## Example 1: single process print("######## Example 1 ########") def long_time_task(): print(f'current process: {os.getpid()}') time.sleep(2) print(f"result: {8 ** 20}") print(f'mother process: {os.getpid()}') start = time.time() for i in range(2): long_time_task() end = time.time() print(f'Duration: {end-start}') ## Example 2: multi-process print("######## Example 2 ########") def long_time_task_i(i): print(f'current process: {os.getpid()}, {i}') time.sleep(2) # print("result: {8 ** 20}") print(f'mother process: {os.getpid()}') start2 = time.time() p1 = Process(target=long_time_task_i, args=(1, )) p2 = Process(target=long_time_task_i, args=(2, )) p1.start() p2.start() p1.join() p2.join() end2 = time.time() print(f'Duration: {end2-start2}') ## Example 3: multiprocess + pool print("######## Example 3 ########") """ 1. process.join() needs to be after .close() and .terminate() """ print(f"num cpu: {cpu_count()}") print(f'mother process: {os.getpid()}') start3 = time.time() pool3 = Pool(4) for i in range(5): pool3.apply_async(long_time_task_i, args=(i, )) pool3.close() pool3.join() end3 = time.time() print(f'Duration: {end3-start3}') ## Example 4: Share data between multi-process using Queue print("######## Example 4 ########") def write(q): print(f'Process to write: {os.getpid()}') for value in ['a', 'b', 'c']: print(f'Put: {value}') q.put(value) time.sleep(0.2) def read(q): print(f'Process to read: {os.getpid()}') while True: value = q.get(True) print(f'Get: {value}') q = Queue() pw = Process(target=write, args=(q, )) pr = Process(target=read, args=(q, )) pw.start() pr.start() pw.join() pr.terminate() ## REF: https://zhuanlan.zhihu.com/p/46368084 ## REF: https://zhuanlan.zhihu.com/p/37029560
true
368b25a3c24acd2bd61811676f685cb5083bbd46
Lionelding/EfficientPython
/3_ClassAndInheritance/27_Private_Attributes.py
1,778
4.28125
4
# Item 27: Prefer Public Attributes Over Private Attributes ''' 1. classmethod has access to the private attributes because the classmethod is declared within the object 2. subclass has no direct access to its parent's private fields 3. subclass can access parents' private fields by tweeking its attribute names 4. Document protected fields in parent classes 5. Only use private attributes when to avoid naming conflicts between parent and subclasses ''' class MyObject(object): def __init__(self): self.public_field = 3 self.__private_field1 = 'field1' self.__private_field2 = 'field2' def get_private_field1(self): return self.__private_field1 def get_private_field2(self): return self.__private_field2 @classmethod def get_private_field_of_instance(cls, instance): return instance.__private_field1 class MyChildObject(MyObject): def __init__(self): super().__init__() self._private_field1 = 'kid_field1' foo = MyObject() kid = MyChildObject() ## `Statement 1` print(f'public_field: {foo.public_field}') print(f'access from parent class: {foo.get_private_field2()}') print(f'access from classmethod: {MyObject.get_private_field_of_instance(foo)}') ## `Statement 2` #print(f'kid: {kid.get_private_field1()}') #should fail ## `Statement 3` ## However, because the way that python translated private attributes, private attributes are accessible print(f'illegal acess: {kid._MyObject__private_field1}') ## Hardcoding a private attribute, which is defined in a parent class, from a subclass is bad approach because there could be another ## layer of hierarchy added in the future. ## 'Statement 5` print(f'access kid private field: {kid._private_field1}') print(f'access parent private field from parent method: {kid.get_private_field1()}')
true
3eabf8de3faf6c8bda2531a8a2292bd763113f2e
josiellestechleinn/AulasPython
/recebendo_dados_usuario.py
1,241
4.40625
4
""" Recebendo dados do usuário input() -> todo dado recebido via input é do tio string Em python, string é tudo que estiver entre: - Aspas simples; - Aspas duplas; - Aspas simples triplas; - Aspas duplas triplas; Exemplos: - apsas simples -> 'Josielle' - aspas duplas -> "Josielle" - aspas simples triplas -> '''Josielle''' """ # aspas duplas triplas -> """Josielle """ # Entrada de dados # print("Qual seu nome?") # nome = input() nome = input('Qual seu nome?') #Processamento #Sáida de dados # Exemplo de print antigo 2.x #print('Seja bem vindo(a) %s' % nome) # Exemplo de print 'moderno' 3.x #print('Seja bem-vindo(a) {0}'.format(nome)) # Exemplo de print 'mais atual' 3.7 print(f'Seja bem-vindo(a) {nome}') # print("Qual sua idade?") # idade = input() idade = int(input('Qual sua idade?')) #pode ser utilizado o cast direto na variável # Exemplo de print antigo 2.x #print('A %s tem %s anos' % (nome, idade)) # Exemplo de print 'moderno' 3.x # print('A {0} tem {1} anos'.format(nome, idade)) # Exemplo de print 'mais atual' 3.7 print(f'A {nome} tem {idade} anos e nasceu em {2021 - idade}') # print(f'A {nome} nasceu em {2021 - int(idade)}') # int(idade) => cast (cast é a conversão de um tipo de dado para outro)
false
d1d051a33cc4da4eeec7a394394b976926ea51d8
jenny-liang/uw_python
/week05/screen_scrape_downloader.py
2,061
4.3125
4
""" Assignment: choose one or both or all three. I suspect 2 is a lot harder, but then you would have learned a lot about the GitHub API and JSON. 1. File downloader using screen scraping: write a script that scrapes our Python Winter 2012 course page for the URLs of all the Python source files, then downloads them all. """ import urllib2 import re from pprint import pprint from BeautifulSoup import BeautifulSoup import os import time if os.path.exists("downloads"): os.system("rm -rf downloads") os.system("mkdir downloads") # read a web page into a big string page = urllib2.urlopen('http://jon-jacky.github.com/uw_python/winter_2012/index.html').read() # parse the string into a "soup" data structure soup = BeautifulSoup(page) # find all the anchor tags in the soup anchors = soup.findAll('a') # find all the anchor tags that link to external web pages externals = soup.findAll('a',attrs={'href':re.compile('http.*')}) # find all the anchor tags that link to Python files pythonfiles = soup.findAll('a',attrs={'href':(lambda a: a and a.endswith('.py'))}) for files in pythonfiles: s = str(files) file_path = s[s.find('=') + 2 : s.find('>') -1] time.sleep(1) url = 'http://jon-jacky.github.com/uw_python/winter_2012/' + file_path print url fileContent = urllib2.urlopen(url) dir = os.path.dirname(file_path) if not os.path.exists("downloads/" + dir): os.system("mkdir -p downloads/%s" %dir) f = open("downloads/"+ dir + "/" + os.path.basename(file_path), "wb") meta = fileContent.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_path, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = fileContent.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close()
true
ead0d989fc780cb3a237b09967d676a8fd2fe378
inimitabletim/iii
/Numpy/4_change_array_shape.py
290
4.1875
4
# --- 變換陣列的形狀排列與維度 page.44 import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) a_2d = a.reshape(3, 4) print(a_2d) print('\n') a_3d = a.reshape(3, 2, 2) print(a_3d) print('\n') a_2d_col = a.reshape(3, 4, order='F') print(a_2d_col)
false
86528dd845be83a71b90850b26a7880f85a0f758
mk346/Python-class-Projects
/Guess_Game.py
492
4.25
4
secret_word ="trouser" guess= "" count=0 guess_limit = 3 out_of_guesses= False print("HINT: I have two legs but i cant walk") while guess!= secret_word and not(out_of_guesses): if count<guess_limit: guess = input("Enter Your Guess: ") count+=1 else: out_of_guesses= True if out_of_guesses: print("You are Remaining with: " + str(guess_limit - count) + "\t Guesses") print("Out of Guesses, You Lose!") else: print("You Win!")
true
a8a4f8ecc948c07a6c8f96173bb2b6e32ee550aa
deepgautam77/Basic_Python_Tutorial_Class
/Week 1/Day 2/for_loop.py
253
4.15625
4
#for i in range(10): # print("This is fun..") #range() function #print odd number from 0-100 for i in range(1,100,2): print(i, end=' ') #WAP to print even numbers from 2000-2500 #WAP to print odd numbers starting from 5200 and ending at 4800
true
d49cedb5535e851045d759e51e9a37f833f6c460
deepgautam77/Basic_Python_Tutorial_Class
/Day 5/homework_1.py
659
4.34375
4
#Create a phone directory with name, phone and email. (at least 5) #WAP to find out all the users whose phone number ends with an 8. #all the users who doesn't have email address. --done d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'}, {'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'}, {'name':'Princess', 'phone':'555-3841', 'email':''}, {'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}] #email #phone that ends with an 8 for item in d: if item['email']=='': print("The name ",item['name'], "doesn't have email address.") if item['phone'].endswith('8'): print("The phone number ending at 8: ",item['phone'])
true
694759e96c8e1988ff347b36ff6c50b55b113639
deepgautam77/Basic_Python_Tutorial_Class
/Week 1/Day 2/simple_task.py
294
4.3125
4
# -273 degree celsius < invalid.. temp = float(input("Enter the temperature: ")) while temp<-273: temp = eval(input(("Impossible temperature. Please enter above -273 degree celsius: "))) print("The temperature of ",temp," Celsius in Farenheit is: ", 9/5*temp+32) #break #continue #pass
true
802ac41bb0e8d2035d204bcff6f762736e66eb00
s0513/python_basic
/answer/210616_買最多禮物_15min.py
1,611
4.40625
4
''' 題目: 小明和小華生完第一個孩子後非常高興,他們的兒子喜歡玩具, 所以小明想買一些玩具。他面前擺著許多不同的玩具, 上面標有它們的價格,他想用手上的錢最大程度地購買玩具。 給定玩具的價格清單和能夠花費金額, 確定他可以購買的最大禮物數量。 #註: 注意每個玩具只能購買一次。 Example: 玩具價格清單 = [ 1, 2, 3, 4 ] 手上的錢k = 7 所以預算為7個貨幣單位,他可以購買組合為[1、2、3]或[3、4],因此最多3個玩具。 限制: 1. 玩具清單n最長為10個項目 2. 玩具價格i最高100 3. 手上有的錢k最高150 ''' import random #i = random.randint(1,100) #玩具價格最高100 #n = [random.randint(1,101) for i in range(random.randint(1,11))] #玩具清單最長為10個項目,價格最高100 n = random.sample(range(1,101), random.randint(1,11)) #玩具清單最長為10個項目(不重複),價格最高100 n.sort() #玩具清單價格排序 print('玩具的價格清單=', n) #print玩具清單價格 k = random.randint(1,151) #手上的錢k最高150元 print('能夠花費金額=', k) #print手上能夠花費金額 #確定他可以購買的最大禮物數量 for num in range(1, len(n)+1): price = sum(n[0:num]) #禮物加起來的價格 if price >= k: #終止條件:禮物加起來的價格 > 手上能夠花費金額 print('max_gift_num=', num - 1) break else: if num == len(n): #如果可以買所有禮物 print('max_gift_num=', num)
false
63e63ec4a0340d36b1734eb6abe7abd0661abf43
keylorch/python-101
/5-tuples.py
440
4.40625
4
# Tuples # Basic information and operations on Tuples in python # Tuples are INmutable myTuple = (1,2,3,4) print("myTuple: ", myTuple) print("min(myTuple): ", min(myTuple)) print("max(myTuple): ", max(myTuple)) print("sum(myTuple): ", sum(myTuple)) print("len(myTuple): ", len(myTuple)) print("1 in myTuple: ", 1 in myTuple) print("22 in myTuple: ", 22 in myTuple) # You can also slice, and loop for item in myTuple[1:]: print(item)
false
6448d6558262935be6a409bfa47878d58db9fbf2
san-smith/patterns_template
/factory_method/script.py
1,110
4.125
4
#coding: utf-8 """ Типы строя """ class Culture: """ Культура """ def __repr__(self): return self.__str__() class Democracy(Culture): def __str__(self): return 'Democracy' class Dictatorship(Culture): def __str__(self): return 'Dictatorship' """ Само правительство """ class Government: culture = '' def __str__(self): return self.culture.__str__() def __repr__(self): return self.culture.__repr__() def set_culture(self): """ Задать строй правительству : это и есть наш Фабричный Метод """ raise AttributeError('Not Implemented Culture') """ Правительство 1 """ class GovernmentA(Government): def set_culture(self): self.culture = Democracy() """ Правительство 2 """ class GovernmentB(Government): def set_culture(self): self.culture = Dictatorship() g1 = GovernmentA() g1.set_culture() print (str(g1)) g2 = GovernmentB() g2.set_culture() print (str(g2))
false
00af72c64e08a9f15b7f869ed9745e3130e676e7
markap/PythonPlayground
/language_features/decorator.py
535
4.375
4
""" a decorator example to multiply to numbers before executing the decorated function """ def multiply(n, m): def _mydecorator(function): def __mydecorator(*args, **kw): # do some stuff before the real # function gets called res = function(args[0] * n, args[1] * m, **kw) # do some stuff after return res # returns the sub-function return __mydecorator return _mydecorator @multiply(2,3) def p(n, m): return n, m print p(3,3)
true
8c763d12a5708eaf31d2da130d47304f4414bd6b
sean-blessing/20210424-python-1-day
/ch07/classes/main.py
640
4.1875
4
from circle import Circle class Rectangle: """Rectangle class holds length and width attributes""" # above doctring is optional area_formula = "area = length * width" def __init__(self, length, width): pass self.length = length self.width = width def area(self): """ calculate the area for this rectangle """ return self.length * self.width rect_1 = Rectangle(5, 6) rect_2 = Rectangle(10, 25) print('rect_1 area: ', rect_1.area()) print('rect_2 area: ', rect_2.area()) circle_1 = Circle(3) print('circle_1 area', circle_1.area()) print('circle_1 radius', circle_1.radius)
true
b8387b9ee340e02727a089494ef37a9d80ed5de5
sean-blessing/20210424-python-1-day
/ch01/rectangle-calculator/main.py
352
4.15625
4
print("Welcome to the area and perimeter calculator!") choice = "y" while choice == "y": length = int(input("enter length:\t")) width = int(input("enter width:\t")) perimeter = 2*length + 2*width area = length * width print(f"Area:\t\t{area}") print(f"Perimeter\t{perimeter}") choice = input("Try again?") print("Bye")
true
6726b05dfc6576f5e64d65f86d2db85b6e580cb4
guam68/class_iguana
/Code/Josh/python/lab17_palindrome_anagram.py
813
4.125
4
def check_palindrome(): word = input('Check and see if your word is a palindrome, give me a word\n>>').lower() word_list = [] for i in word: word_list.append(i) reversed_word_list = word_list[::-1] if reversed_word_list == word_list: return True else: return False # print(f'{check_palindrome()} this word is a palindrome') def check_anagram(): word = input('What\'s your word?\n>>').lower() anagram_word = input('give another word and I\'ll check if they are anagrams\n>>').lower() word_list = [] anagram_list = [] for i in word: word_list.append(i) for i in anagram_word: anagram_list.append(i) if sorted(word_list) == sorted(anagram_list): return True else: return False print(check_anagram())
false
a2939f9834efd995dce131b47835070982058687
guam68/class_iguana
/Code/Richard/python/lab-road-trip_3.py
1,609
4.21875
4
""" author: Richard Sherman 2018-12-21 lab-road-trip.py, an exercise in sets and dictionaries, finds the cities from an origin that are accessible by taking n 'hops' """ # this is the dictionary of sets of cities that can be reached from a given origin # a pair are added to the original lab to facilitate testing city_to_accessible_cities = { 'Boston': {'New York', 'Albany', 'Portland'}, 'New York': {'Boston', 'Albany', 'Philadelphia'}, 'Albany': {'Boston', 'New York', 'Portland'}, 'Portland': {'Boston', 'Albany'}, 'Philadelphia': {'New York'}, 'Kalamazoo' : {'Philadelphia'}, 'End of the World' : {'End of the World'} } # the main trick here is the in-place version of the union of sets operator | , |= , analogous to += def road_trip(origin, n_hops): origin = {origin} for hops in range(n_hops): dest = set() for city in origin: dest |= city_to_accessible_cities[city] origin = dest print(dest) return dest print('\nOne hop from Philadelphia:') road_trip('Philadelphia', 1) print('\nTwo hops from Philadelphia:') # respect to W.C. Fields road_trip('Philadelphia', 2) print('\nThree hops from Philadelphia -- does not return to Philadelphia:') road_trip('Philadelphia', 3) print('\nTwo hops from Kalamazoo:') road_trip('Kalamazoo', 2) print('\nThree hops from Portland -- goes everywhere:') road_trip('Portland', 3) print('\nTwo hops from New York:') road_trip('New York', 2) print('\nThree hops from New York - goes everywhere:') road_trip('New York', 3) print('\nFive hops from the End of the World:') road_trip('End of the World', 5)
false
de513e18abf270601e74fc0e738dc4f6ef7c5c1a
guam68/class_iguana
/Code/Richard/python/lab25-atm.py
1,914
4.34375
4
""" author: Richard Sherman 2018-12-16 lab25-atm.py, an ATM simulator, an exercise in classes and functions """ import datetime class ATM(): def __init__(self, balance = 100, rate = 0.01): self.balance = balance self.rate = rate self.transactions = [] def check_withdrawal(self, amount): if amount > self.balance: return False return True def withdraw(self, amount): if self.check_withdrawal(amount): self.balance -= amount self.transactions.append(f'Withdrawal of {amount}, {datetime.datetime.now()}, Balance = {self.balance} ') else: print('Insufficient funds') def deposit(self, amount): self.balance += amount self.transactions.append(f'Deposit of {amount}, {datetime.datetime.now()}, Balance = {self.balance}') def check_balance(self): self.calc_interest(self.balance) self.transactions.append(f'Interest of {self.rate} added to balance, {datetime.datetime.now()}, Balance = {self.balance}') return self.balance def calc_interest(self, rate): self.balance += self.balance * self.rate return self.balance def print_transactions(self): print(self.transactions) atm = ATM() while True: command = input('what would you like to do (deposit, withdraw, check balance, history, exit)? ') if command == 'exit': print('Thank you for banking with us!') break elif command == 'deposit': amount = float(input('what is the amount you\'d like to deposit? ')) atm.deposit(amount) elif command == 'withdraw': amount = float(input('what is the amount you\'d like to withdraw? ')) atm.withdraw(amount) elif command == 'check balance': print(f'Your account balance is ${atm.check_balance()}') elif command == 'history': atm.print_transactions()
true
164ff47a83bd250d278c32f37ecb28a1cb13e1b9
guam68/class_iguana
/Code/nathan/pythawn/lab_03_grading.py
1,016
4.15625
4
#ask user for input needing a number between 50 and 100 grade = input('what was your grade? \n>') #turn user input (string) into an integer grade = int(grade) # # if grade >= 96: # print('A+') # elif grade == 95: # print('A') # elif grade >= 90: # print('A-') # #lots of ifs and elifs to determine what to print for given integer if grade >= 90 and grade <= 94: print('A-') elif grade >= 80 and grade <=84: print('B-') elif grade >= 70 and grade <=74: print('C-') elif grade >= 60 and grade <= 64: print('D-') elif grade >= 50 and grade <= 54: print('F- oh no') elif grade >= 96 and grade <= 100: print('A+ wow') elif grade >= 86 and grade <= 89: print('B+') elif grade >= 76 and grade <= 79: print('C+') elif grade >= 66 and grade <= 69: print('D+') elif grade >= 56 and grade <= 59: print('F+') elif grade == 95: print('A') elif grade == 85: print('B') elif grade == 75: print('C') elif grade == 65: print('D') elif grade == 55: print('F')
false
bdf4fabb89d8d1d17131a525549a45e8ec38a334
guam68/class_iguana
/Code/nathan/pythawn/lab_13_rot13.py
1,050
4.3125
4
#making rot13 function attached to dictionary def rot13(user_string): rot_dict = {'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u', 'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c', 'q': 'd', 'r': 'e', 's': 'f', 't': 'g', 'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k', 'y': 'z'} #blank string output output = '' for char in user_string: print(f'{char} {rot_dict[char]}') #for loop; each character in input string used as key in dictionary to encode input string with dictionary user_string = input('please help me generate a string: ') print(rot13(user_string)) #print function and user string
false
7a9349976447f50f8a54c6999aa1419e5e382f2e
guam68/class_iguana
/Code/Scott/Python/lab_11_simple_calculator_version2.py
898
4.28125
4
#lab_11_simple_calculator_version2.py #lab_11_simple_calculator_lvl_1 #operator_dict = {'+': +,} operator = input("What type of calculation would you like to do? Please enter '+', '-', '**', or '/' :") operand_a = input('Please enter the first number:') operand_b = input('Please enter the second number:') operand_a = float(operand_a) operand_b = float(operand_b) if operator == '+': result = operand_a + operand_b print(f'Answer: {result}') elif operator == '-': result = operand_a - operand_b print(f'Answer: {result}') elif operator == '*': result = operand_a * operand_b print(f'Answer: {result}') elif operator == '/': result = operand_a / operand_b print(f'Answer: {result}') while True: operator = input("Please enter '+', '-', '**', or '/' or if you are finished, type 'done'") if operator == 'done': print('Goodbye.') break
true
2eba7e9bccb0005fdf14007ee56046302fe2da97
guam68/class_iguana
/Code/Scott/Python/lab6_password_generatory.py
2,431
4.375
4
#lab6_password_generatory.py #1. acquire all possible characters import random import string # n = input('How many characters would you like your password to have?:\n') # n = int(n) # character_list = list(string.ascii_lowercase) + list(string.digits) + list(string.punctuation) # password = '' # for c in range(0, n): # password = password + random.choice(character_list) # print(f'Your new password is {password}') password_list = [] lc = input('How many lower-case alphabet characters do you need?:\n') lc = int(lc) lower_case_portion = '' for l in range(lc): lower_case_portion += random.choice(list(string.ascii_lowercase)) #password_list.append(random.choice(string.ascii_lowercase)) uc = input('How many upper-case alphabet characters do you need?:\n') uc = int(uc) upper_case_portion = '' for u in range(uc): upper_case_portion = upper_case_portion + random.choice(list(string.ascii_uppercase)) num = input('How many numeric characters do you need?:\n') num = int(num) numeric_portion = '' for n in range(num): numeric_portion = numeric_portion + random.choice(list(string.digits)) char = input('How many special characters do you need?:\n') char = int(char) character_portion = '' for c in range(char): character_portion = character_portion + random.choice(list(string.punctuation)) password_list = list(lower_case_portion) + list(upper_case_portion) + list(numeric_portion) + list(character_portion) print(password_list) #this will show the list of all of the collected characters in order of their collection; ie, 2 by 2 or 3 by 3 password = '' for i in range(len(password_list)): random_index = random.randint(0, len(password_list)-1) # variable for a randomly selected element (by index). to establish the proper range, use -1 because indexing starts with 0 print(password_list) #will show the same list as the one above first time through the loop, then each time missing a randomly selected element # print(random_index) random_element = password_list.pop(random_index) #this is removing whatever element was randomely seclected on line 47 via # print(random_element) #print() password += random_element # add random character to output print(password)#this print statement (located here in the loop) will show the password growing by one element at a time. print() print(f'Your new password is {password}') # random.shuffle(password)
false
d04a6a59d53ba2a8f1e969c17a945f5afaf589b9
aeroswitch/GeekBrains
/1_Python_basics/6_OOP_Basics/Task2.py
2,401
4.375
4
""" 2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см * число см толщины полотна. Проверить работу метода. Например: 20м * 5000м * 25кг * 5см = 12500 т """ class Road: def __init__(self, length, width): self._length = length self._width = width def calculate_asphalt_weight(self): result = int(self._width * self._length * 25 * 5 / 1000) return result example_road = Road(5000, 20) print(f'Calculated asphalt weight is {example_road.calculate_asphalt_weight()} tons') # # -------------------------------------------------------- 2 -------------------------------------------------------- # # # class Road: # def __init__(self, length, width): # self._length = length # self._width = width # # def get_full_profit(self): # return f"{self._length} м * {self._width} м * 25 кг * 5 см = {(self._length * self._width * 25 * 5) / 1000} т" # # # road_1 = Road(5000, 20) # print(road_1.get_full_profit()) # # # # ------------------------------------------- вариант решения ------------------------------------------------------- # # # class Road: # def __init__(self, _lenght, _width): # self._lenght = _lenght # self._width = _width # # def calc(self): # print(f"Масса асфальта - {self._lenght * self._width * 25 * 5 / 1000} тонн") # # # def main(): # while True: # try: # road_1 = Road(int(input("Enter width of road in m: ")), int(input("Enter lenght of road in m: "))) # road_1.calc() # break # except ValueError: # print("Only integer!")
false
791832ac4be5e5aea1049360ad832411becc7175
aeroswitch/GeekBrains
/1_Python_basics/3_Functions/Task1.py
1,217
4.4375
4
""" 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. """ def division(var_1, var_2): """Принимает два числа и возвращает результат их деления""" try: return var_1 / var_2 except ZeroDivisionError: return print('Реализация через input в вызове функции: ') print(division(float(input('Введите делимое: ')), float(input('Введите делитель: ')))) # способ 2 def division_2(): """Принимает два числа и возвращает результат их деления""" try: var_1 = float(input('Введите делимое: ')) var_2 = float(input('Введите делитель: ')) return var_1 / var_2 except ZeroDivisionError: return print('Реализация через input в теле функции: ') print(division_2())
false
b7816fc8efb71a1535030bc5c2a0dc583c29116c
yvette-luong/first-repo
/data-types.py
668
4.1875
4
""" Boolean = True or False String = "Yvette" Undefined = A value that is not defined Integer = 132432 Camel Case = lower case first word and then capitalize each following word: example: helloWorld """ "1231314" Yvette = 123 Yvette def helloYvette(): # this is a function, which is indicated by brackets print("Hello my name is Yvette") helloYvette() # calling the function def helloAnyone(name): # accept a parameter print(f"Hello my name is {name}") helloAnyone("sjfajkhf") # sjfajkhf is an argument def multiply(x, y): return x * y print(multiply(6, 2)) print("Hello this is print") def add(a, b): return a + b print(add(4, 5))
true
4f3b7f5a2114e451ea26d078798405827063f9ba
jnthmota/ParadigmasProg
/Exercicio6/Ex2.py
430
4.28125
4
# 2 Defna a função div que recebe como argumentos dois números naturais m # e n e devolve o resultado da divisão inteira de m por n. Neste exercício você não # pode recorrer às operações aritmétcas de multplicação, divisão e resto da divisão # inteira. # Ex: div(7,2) = 3 def div( dividendo, divisor ): return 0 if dividendo < divisor else 1 + div(dividendo - divisor, divisor) print(div(5,2)) print(div(2,3))
false
3c6d0774f7dd6da59fa5b32f3e37e389fe93f248
davakir/geekbrains-python
/lesson-4/fifth.py
648
4.28125
4
""" Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка """ from functools import reduce def multiplication(multiplier_1, multiplier_2): return multiplier_1 * multiplier_2 my_list = [number for number in range(100, 1001) if number % 2 == 0] print(reduce(multiplication, my_list))
false
5d726403aa52295dd2d32f3e6c2345dda7ef1bbc
davakir/geekbrains-python
/lesson-6/Employee.py
1,277
4.25
4
""" Employee больше подходит для сущности "сотрудник" """ class Employee: _income = {} def __init__(self, name, surname, position): self.name = name self.surname = surname self.position = position def set_income(self, salary, bonus): self._income = {'salary': salary, 'bonus': bonus} """ Должность никогда логически не может быть расширением сущности "сотрудник", поэтому будем просто передавать извне сотрудника, у которого будем вызывать указанные методы """ class EmployeePosition: def __init__(self, employee: Employee): self.__employee = employee def get_employee_full_name(self): return self.__employee.name + ' ' + self.__employee.surname def get_employee_total_income(self): return self.__employee._income['salary'] + self.__employee._income['bonus'] employee = Employee('Иван', 'Иванов', 'Монтажник') employee.set_income(10000, 3000) employee_position = EmployeePosition(employee) print(employee_position.get_employee_full_name()) print(employee_position.get_employee_total_income())
false
7c263f8cb4c3eedce2b1cd3d678e90b57613bab6
gdevina1/MIS3640-Repository
/Session 5/Session5InClass.py
1,699
4.1875
4
print("Session 5 - Functions II") import turtle bear = turtle.Turtle() print(bear) #for i in range(4): #the range has to be an integer # bear.fd(100) # bear.lt(90) #for i in range(4): # print(i) # #turtle.mainloop() def square(t, length): for i in range(4): t.fd(length) t.lt(90) #square(bear, 180) #turtle.mainloop() def polygon(t, length,n): for i in range(n): t.fd(length) t.lt(360/n) #polygon(bear, 20, 8) #polygon(bear, n=8, length=20) # this would work #turtle.mainloop() import math def circle(t, r): circumference = 2 * math.pi * r n = 50 length = circumference / n polygon(t, length, n) #sequence of the arguments matter, if it had been t,n,length the function aint gonna run #circle(bear, 90) #turtle.mainloop() def arc(t, r, angle): arc_length = 2 * math.pi * r * angle/360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = angle / n for i in range(n): t.fd(step_length) t.lt(step_angle) #arc(bear,100,180) #turtle.mainloop() def polyline(t, n, length, angle): """Draws n line segments with the given length and angle (in degrees) between them. t is a turtle. """ for i in range(n): t.fd(length) t.lt(angle) def polygon(t, n, length): angle = 360.0 / n polyline(t, n, length, angle) def arc(t, r, angle): arc_length = 2 * math.pi * r * angle / 360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle) def circle(t, r): arc(t, r, 360) #polyline(bear,20,20,20) #circle(bear,70) #turtle.mainloop()
false
2e7839e32546b9cf8a790c16b71c24986d8f12cb
stevenhughes08/CIT120
/work/python/unit7/SuperMarket.py
1,337
4.28125
4
# SuperMarket.py - This program creates a report that lists weekly hours worked # by employees of a supermarket. The report lists total hours for # each day of one week. # Input: Interactive # Output: Report. # Declare variables. HEAD1 = "WEEKLY HOURS WORKED" DAY_FOOTER = "Day Total " SENTINEL = "done" # Named constant for sentinel value hoursWorked = 0 # Current record hours hoursTotal = 0 # Hours total for a day prevDay = "" # Previous day of week notDone = True # loop control # Print two blank lines. print("\n\n") # Print heading. print("\t" + HEAD1) # Print two blank lines. print("\n\n") # Read first record dayOfWeek = input("Enter day of week or done to quit: ") if dayOfWeek == SENTINEL: notDone = False else: hoursWorked = input("Enter hours worked: ") prevDay = dayOfWeek hoursTotal += int(hoursWorked) print("\t" + DAY_FOOTER + str(hoursTotal)) while notDone == True: dayOfWeek = input("Enter day of week or done to quit: ") if dayOfWeek == SENTINEL: break # Implement control break logic here # Include work done in the dayChange() function if prevDay != dayOfWeek: hoursTotal = 0 hoursWorked = input("Enter hours worked: ") prevDay = dayOfWeek hoursTotal += int(hoursWorked) print("\t" + DAY_FOOTER + str(hoursTotal))
true
f25313f5260876e54141d6ee9a82cc2117d77521
FelixTang-only/learn_py
/day9.py
1,807
4.125
4
# 函数的参数详细解读 # 位置参数 # def power(x): # return x * x # power(4) # power(x, n) # def power(x, n): # s = 1 # while n > 0: # n = n - 1 # s = s * x # return s # print(power(5, 2)) # 默认参数 # power(5) # def power(x, n = 2): # s = 1 # while n > 0: # n = n - 1 # s = s * x # return s # power(5) # print(power(n = 1, x = 2)) # power(2, 1) # def add_end(l=[]): # l.append('end') # return l # print(add_end()) # print(add_end()) # def add_end(l=None): # if l is None: # l = [] # l.append('end') # return l # print(add_end()) # print(add_end()) # 可变参数 # def calc(numbers): # sum = 0 # for n in numbers: # sum = sum + n * n # return sum # calc([1, 2, 3]) # calc((1, 2, 3)) # def calc(*numbers): # sum = 0 # for n in numbers: # sum = sum + n * n # return sum # nums = [1, 2, 3] # calc(nums[0], nums[1], nums[2]) # calc(*nums) # 关键字参数 # dict # def preson(name, age, **kw): # print('name:', name, 'age:', age, 'other:', kw) # print(preson('kim', 18)) # print(preson('jim', 30, city='beijing', jod='teacher')) # extre = {'city': 'beijinng', 'job': 'teacher'} # preson('jack', 24, city=extre['city'], job=extre['job']) # preson('jack', 24, **extre) # 命名关键字参数 # city age # def preson(name, age, *, city, job): # print(name, age, city, job) # **kw # * # preson('jack', 24, city='beijing', job='teacher') # def preson(name, age, *args, city, job): # print(name, age, city, job) # print(preson('jack', 24, 'beijing', 'teacher')) # def preson(name, age, *, city, job='teacher'): # print(name, age, city, job) # preson('kim', 21, city='beijing') # 参数组合 def f1(a, b, c=0, *args, **kw): print(a, b, c, args, kw)
false
a3d6d0d7062c1452341c59741ea67aada4dc9ed8
danangsw/python-learning-path
/sources/8_loops/4_else_loop.py
640
4.3125
4
# Python supports `else` with a loops. # When the loop condition of `for` or `while` statement fails then code part in `else` is executed. # If `break` statement is executed then `else` block will be skipped. # Even any `continue` statement within a loops, the `else` block will be executed. count = 0 while count < 5: print(count) count += 1 pass else: print("Reach maximum counting (%d)" % count) pass print() for i in range(0,10): if i % 5 == 0: break print(i) pass else: print("this is not printed because for loop is terminated because of break but not due to fail in condition") pass
true
2e4761e091c6838cfdedbd8bdd48c727a606afd5
hjhorsting/Bootrain2
/PythonBasics.py
549
4.4375
4
# 1. Write a code that outputs your name and surname in one line. print("Harald Horsting") # or: print("Harald", "Horsting") # 2. Write a 1-line code that outputs your name and surname in two separate lines by using # a single print() call. print("Harald \n Horsting") # 3. Use print() function that returns the following text. # Notice the quotes in the text. Those quotes should be seen in the output! # `I don't want to be an "artist". I want to be a "Data Scientist."` print('''`I don't want to be an "artist". I want to be a "Data Scientist."`''')
true
0129054fc9cac41a867350212d2d11c4ac157f9f
Wanderson96/ATIVIDADE-COMPLETA
/LETRAS A B C D E.py
1,229
4.15625
4
dia = int(input("escreva o dia: ")) mes = int(input("escreva o mês: ")) ano = int(input("escreva o ano: ")) print("DATA: ",dia,'/',mes,'/',ano) A = int(input("escreva a variavel A: ")) B = int(input("escreva a variavel B: ")) C = int(input("escreva a variável C: ")) print("MEDIA DAS VARIÁVEIS: ",(A+B+C)/3) X = int(input("escreva a variavel X: ")) print("RESULTADO DO NÚMERO ELEVADO AO CUBO: ",X**3) HORA = int(input("escreva a quantidade de horas: ")) MINUTOS = int(input("escreva a quantidade de minutos: ")) SEGUNDOS = int(input("escreva a quantidade de minutos: ")) TOTAL_DE_SEGUNDOS= HORA*3600+MINUTOS*60+SEGUNDOS*1 print("TOTAL DE SEGUNDOS: ",TOTAL_DE_SEGUNDOS) LARGURA = float(input("escreva a largura em metros: ")) COMPRIMENTO = float(input("escreva o comprimento em metros: ")) H = float(input("escreva a altura em metros: ")) AREA_DO_PISO = LARGURA*COMPRIMENTO VOLUME_DA_SALA = LARGURA*COMPRIMENTO*H AREA_DAS_PAREDES_DA_SALA = 2*(H*LARGURA)+2*(H*COMPRIMENTO) print ("Área do piso: %.2f " % AREA_DO_PISO,'METROS QUADRADOS') print ("Volume da sala: %.2f " % VOLUME_DA_SALA,'METROS CÚBICOS') print ("Área das paredes da sala: %.2f " % AREA_DAS_PAREDES_DA_SALA,'METROS QUADRADOS')
false
2c099c78fb2eff10a340d1ba214e333cfb17d720
MarKuchar/intro_to_algorithms
/1_Variables/operators.py
1,205
4.15625
4
# Operators # =, -, *, /, // (floor division) # % (modulo): 'mod' remainder # ** (power) print(10 % 3) # 1 print(10 ** 2) # 100 print(100 // 3) # 33 print(100 - 5) # = : assignment number = 7 number = number + 3 # increment number by 3 number += 3 # increment number by 3 # -= : decrement operator print("number = " + str(number)) # string concatenation (+) # *= : multiply by number *= 2 # /= : divide by # Boolean Operators # Comparison # == : equality (equal) print(3 == 4) # != : not equal to # > : greater than # >= : greater than or equal to # <= : less than or equal to print(3 < 4) x = 10 # check if x is greater than equal to 7 and less than 12 print(x >= 7 and x < 12) # and (both have to be true to return TRUE), or (either one has to be true to return TRUE) print(7 <= x < 12) # only in python! same as "print(x >= 7 and x < 12)" print((3 != 3) or (4 == 4)) # 4 == death (in chinnes), 13 == bad luck # Exercise num = 10 # print((num > 10) and (num / 0 = 0)) # ZeroDivisionError print((num > 10) and (num / 0 == 0)) # False print((num > 7) or (num / 0 == 0)) # True # print((num > 10) or (num / 0 = 0)) # ZeroDivisionError print(not True) # False print(not False) # True
true
5b25724eae900e42228b5687f4f2691b7bb10031
MarKuchar/intro_to_algorithms
/8_Functions/functions.py
1,050
4.28125
4
# Functions are a very convenient way to divide your code into useful blocks, make it more readable and help 'reuse' it. # In python, functions are defined using the keyword 'def', followed by function's name. # "input --> output", "A reusable block of code" def print_menu(): print("----- Menu -----") print("| 1. Tacos ") print("| 2. Pizza ") print("| 3. BBQ ") print("| 4. Feijoada ") print("| 5. Halusky ") print("----------------") print_menu() # call the function # printing menu 5x for i in range(5): print_menu() # call execute the function def score_to_letter_grade(mark): if 100 >= mark >= 90: return "A" elif 90 > mark >= 80: return "B" elif 80 > mark >= 70: return "C" elif 70 > mark >= 60: return "D" elif 60 > mark >= 0: return "F" print(score_to_letter_grade(82)) print(score_to_letter_grade(63)) print(score_to_letter_grade(21)) letter = score_to_letter_grade(90) print(letter) print(score_to_letter_grade(95))
true
1d7501c04e7e41331f36b5085202c7c1da7aa91b
MarKuchar/intro_to_algorithms
/4_Tuples/tuples_basics.py
970
4.34375
4
# Tuples are almost identical to lists # The only big difference between lists and tuples is that tuples cannot be modified (Immutable) # You can NOT add(append), changed(replace), or delete "IMMUTABLE LIST" # elements from the tuple vowels = ("a", "e", "i", "o", "u") # consonants (b, c, d, ...) print(vowels[0]) print("k" in vowels) # vowels[0] = "A" # Error # Methods vowels.index("e") vowels.count("i") # Use cases # 1. return multiple values from a function def a(): return (1, "Mars") # example def get_combo(name): if name == "Big-mac": return ("Coke", "Big-mac", "Fries") # 2. check if an item is in a tuple print("a" in vowels) # 3. multiple assignments year, country = (2020, "Canada") _, country, provice = (2020, "Canada", "BC") # underscore we use when we want to ignore part of assignment # swap x = 10 y = 20 # I want to swap x and y # in python x, y = y, x # in other languages temp = x # temporary variable x = y y = temp
true
e783da31a78d9b2f0f786c0a7f5b9a7bd707833e
MarKuchar/intro_to_algorithms
/1_Variables/variable_type.py
883
4.3125
4
# Data types # There are many different data types in Python # int: integer # float: floating point (10.23, 3.14, etc) # bool: boolean (True, False) # str: a sequence of characters in quotes "aa", 'aa' language = "en_us" print(type(language)) # check the type of the variable users = 10 """ print(users + language) # ERROR - we must match the type """ print(str(users) + language) # Type conversion (type changing): "changing types". # There are several built-in functions that let you convert one data type to another. # str(x): converts x into a string representation. # int(x): converts x into an integer. # float(x): converts x into a floating-point number. #Ecercise: what is the type of following operations? # 10. 1 / 2 -> float print(str(1/2)) # 2. 10 // 4 -> int division print(type(10 // 4)) # 3. float("a.12") -> Error # 4. float(5) -> 5.0 (float) print(float(5))
true
46f360e2ece2d5195fe417c92cc1b91cd1f467ae
Chauhan98ashish/Hacktoberfest_2020
/newton_sqrt.py
219
4.34375
4
print("*****Square Root By Newton's Method*****") x=int(input("Enter the number::>>")) r=x a=10**(-10) while abs(x-r*r)>a: r=(r+x/r)/2 print(r) r=round(r,3) print("Square root of {} is {}".format(x,r))
true
c7aa27a1bd3cb900533845dd60eada06f6773b7f
sairaj225/Python
/Regular Expressions/5Find_a_word_in_string.py
307
4.28125
4
import re # if re.search("hello", "we have said hello to him, and he replied with hellora hello"): # print("There is hello in the string") # findall() returns list of all matches words = re.findall("hello", "we have said hello to him, and he replied with hellora hello") for i in words: print(i)
true
6c7e393680152b14a04838a6406298cce3e9e3fb
sairaj225/Python
/Generators/1demo.py
774
4.5625
5
''' Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way. ''' # If a function contains at least one yield statement # It becames a Generator function. # Generator function contains one or more yield statements. ''' both 'yeild' and 'return' returns the same value. ''' # when the function terminates, StopIteration is raised automatically on further calls. # A simple generator function. def first_generator(): n=1 print("First statement") yield n n=n+1 print("Second statement") yield n n=n+1 print("Third statement") yield n a = first_generator() print(next(a)) print(next(a)) print(next(a)) print(next(a))
true
afc839d183e205f373d0d0431261cb9d26a2035c
sairaj225/Python
/Regular Expressions/12verify_phone_number.py
251
4.125
4
import re # \w = [a-zA-Z0-9_] # \W = [^a-zA-Z0-9_] phone_number = "412-555-1212" if re.search("\w{3}-\w{3}-\w{4}", phone_number): print("It is a phone number") if re.search("\d{3}-\d{3}-\d{4}", phone_number): print("It is a phone number")
false
65d380c3a9a7e96e88682e0d935fa3eb61f5eebd
sairaj225/Python
/Dictionaries/accessing.py
299
4.25
4
d = { "name" : 'sairaju', "roll no" : 225 } print(d) # Accessing the dictionary print(d['roll no']) print(d.get('name')) # Changing the value of the dictionary key d['name'] = "raje" print(d) # Adding new item into dictionary d["class"] = "MCA" print(d) # Dictionary length print(len(d))
false
f7917d704ac0e45d8b0ffc804eeac7dc65eac66b
Dnavarro805/Python-Programming
/Data Structures - Arrays/StringReverse.py
358
4.1875
4
# Problem: Create a funciton that reverses a string. # Input: "Hi My Name is Daniel" # Output: "lienaD si emaN yM iH" def reverse(str): reversed = [] for x in range (len(str)-1, -1, -1): reversed.append(str[x]) return ''.join(reversed) def reverse2(str): return str[::-1] print(reverse("Daniel")) print(reverse2("Daniel"))
true
dee9b44b301c333cd39a4f05808b6e3aa1621075
LeeSinCOOC/My_File_Library
/Python_排序算法/selection.py
729
4.125
4
def selection_sort(arr): ''' 1.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置 2.然后,再从剩余未排序元素中继续寻找最小(大)元素 3.然后放到已排序序列的末尾。 4.以此类推,直到所有元素均排序完毕。 ''' for i in range(len(arr)-1): minIndex=i for j in range(i+1,len(arr)): if arr[minIndex]>arr[j]: minIndex=j if i==minIndex: pass else: arr[i],arr[minIndex]=arr[minIndex],arr[i] return arr if __name__ == '__main__': testlist = [17, 23, 20, 14, 12, 25, 1, 20, 81, 14, 11, 12] print(selection_sort(testlist))
false
2402ee630147b2b855b0d5b0413bf1bbbdad179c
memomora/Tarea2
/E3_S4.py
2,221
4.3125
4
''' Escriba una función en Python que permita determinar si un número es perfecto o no. Un número perfecto es un número entero positivo cuyo valor es igual a la suma de todos sus divisors enteros positivos. (https://es.wikipedia.org/wiki/Número_perfecto) ''' print("========================================") print("= Ejercicio No. 3, Tarea No. 2 =") print("= Por: Guillermo Mora B. =") print("========================================") print("") #Funcion para solicitar los numeros al usuario def solicitar_numero(): num_str1 = input("Digite el numero a verificar: ") return(num_str1) #Funcion para convertir los string en integer def convertir_numero(num1): num1 = int(num1) return(num1) #Funcion para determinar si el numero es correcto def verfifica_numero(num1): esta_correcto = False if num1 > 0: esta_correcto = True return (esta_correcto) #Funacion pra realizar la busqueda de los divisores del numero def busca_divisor(num1): maximo_rango = (num1 // 2) + 1 resultado_division = 0 #ciclo para comprobar divisores del numero for divisor in range(1,maximo_rango): if num1 % divisor == 0: resultado_division = resultado_division + divisor return(resultado_division) #Funcion para vierificar si el numero es perfecto def verifica_perfecto(num1,num2): numero_perfecto = False if num1 == num2: numero_perfecto = True return (numero_perfecto) #Cuerpo del programa salir = "" while salir != "s" and salir != "S": numero_string = solicitar_numero() numero_int = convertir_numero(numero_string) numero_correcto = verfifica_numero(numero_int) if numero_correcto: suma_divisores = busca_divisor(numero_int) numero_perfecto = verifica_perfecto(numero_int,suma_divisores) if numero_perfecto: print("El numero {} es un numero perfecto ".format(numero_int)) print("") else: print("El numero {} no es un numero perfecto ".format(numero_int)) print("") else: print("El numero debe ser mayor que cero ") print("") salir = input("Digite cualquier tecla para continuar o (S)alir ")
false
53f1c9eee659d35d7ed4b563d21a6e4502d811e5
nolanroosa/intermediatePython
/hw21.py
1,835
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 12 16:59:35 2020 @author: nolanroosa """ # Question 1 import pandas as pd pop = pd.read_csv("/Users/nolanroosa/Desktop/Python/pop.csv") def menu(): print (''' Population Menu: 1. Display the entire table 2. Display the total population of all the states 3. Prompt for the name of a state. Display its population 4. Display the table sorted by state name 5. Dissplay the table grouped by region 6. Display the table sorted by population, largest to smallest 0. Quit ''') menuRequest = int(input('Enter a menu option: ')) menuOption = [] for i in range(0,7): menuOption.append(i) if menuRequest not in menuOption: print('\nEnter a valid menu item.') else: return(menuRequest) def statereq(): stateRequest = input('Enter the name of a state: ') namedPop = pop.set_index('NAME') print('\nThe population of the entered state is', namedPop.loc[stateRequest][2]) def main(): continueFlag = True while continueFlag: menuRequest = menu() if menuRequest == 1: print(pop) elif menuRequest == 2: print(pop['POPULATION']) elif menuRequest == 3: statereq() elif menuRequest == 4: print(pop.sort_values(by = 'NAME')) elif menuRequest == 5: print(pop.sort_values(by = 'REGION')) elif menuRequest == 6: print(pop.sort_values(by = 'POPULATION', ascending = False)) elif menuRequest == 0: print("You have quit.") continueFlag = False if __name__ == "__main__": main()
true
e50af84ac8ce77f08597c3ef94481e5aef55fd48
yogeshBsht/CS50x_Plurality
/Plurality.py
1,469
4.34375
4
# Plurality max_candidates = 5 candidates = ['Lincoln', 'Kennedy', 'Bush', 'Obama', 'Trump', 'Biden'] # Taking number of candidates as input flag = 1 while flag: num_candidates = int(float(input("Enter number of candidates: "))) if num_candidates < 2: print("Value Error! At least 2 candidates must contest the election.") elif num_candidates > max_candidates: print(f"Value Error! Number of candidates must not exceed {max_candidates}.") else: flag = 0 # Randomly selecting contestants from candidates list import random contestants = [*random.sample(candidates, num_candidates)] print("Contestants are: ", end=" ") print(*contestants, sep=", ") # Taking number of voters as input voters = int(float(input("Enter number of voters: "))) # Random voting based on number of voters dict = {} for _ in range(voters): val = random.sample(contestants,1)[0] if val in dict: dict[val] += 1 else: dict[val] = 1 # Winner selection based on vote count winner, count = [], 0 for cont in dict: if dict[cont] == count: winner.append(cont) count = dict[cont] elif dict[cont] > count: winner = [cont] count = dict[cont] if len(winner) == 1: print(f"Winner {winner[0]} secured {count} votes out of {voters} votes.") else: print("Election tied among: ", end=" ") print(*winner, sep = ", ")
true
9a8686df420357ee5df29a2d351bc47d9502c9af
chrylzzz/first_py
/day14/3.自定义异常.py
550
4.15625
4
""" 抛出自定义异常的语法为 raise 异常类对象 """ ##长度小于3抛出异常 class SIError(Exception): def __init__(self, len, min_len): self.len = len self.min_len = min_len def __str__(self): return f'你输入的长度是{self.len},不能少于{self.min_len}' def main(): try: con = input('输入密码: ') if len(con) < 3: raise SIError(len(con), 3) except Exception as result: print(result) else: print('密码输入完成') main()
false
d8fd09cbd25c6fe085aacf33768aedcc713b7e04
jurbanski/week2
/solution_10.py
2,721
4.34375
4
#!/usr/local/bin/python3 # 2015-01-14 # Joseph Urbanski # MPCS 50101 # Week 2 homework # Chapter 8, Question 10 solution. # Import the sys module to allow us to read the input filename from command line arguments import sys # This function will prompt the user for a filename, then check to see if the file exists. If the file does not exist, it prompts again. If the file does exist, it returns the name of the file. def prompt_for_filename(): while True: filename = input("Please enter an input filename: ") try: infile = open(filename, 'r') return filename except OSError: print("File not found!") # Check to see if the filename has been provided as a command line argument, if it hasn't, prompt for user input with the prompt_for_filename() function. try: filename = sys.argv[1] infile = open(filename, 'r') # CASE: File not found. except OSError: print("File not found!") filename = prompt_for_filename() # CASE: No filename provided on the command line. except IndexError: filename = prompt_for_filename() # infile may not be set when the try block above finishes (out of scope if we have to prompt for a filename with prompt_for_filename()), so set it here. infile = open(filename, 'r') # Initialize some working variables. leg = 0 odometer_prev = 0 miles_total = 0 gas_total = 0 # Loop over every line in the file. for line in infile: # Split the current line into an array of strings. currline = line.split() # Set the current odometer to the first value in the current line. odometer_curr = float(currline[0]) # Test to see if this is the first line in the file. if leg == 0: # If so, then: # Set the previous odometer to be the current odometer. odometer_prev = odometer_curr # Increment the leg counter. leg += 1 else: # If not the first line, then: # Set the gas used to the second item in the current line. gas_used = float(currline[1]) # Determine the miles traveled from the two odometer values. miles_traveled = odometer_curr - odometer_prev # Add the miles traveled on the current leg to the total. miles_total += miles_traveled # Add the gas used to the total. gas_total += gas_used # Calculate the MPG for this leg of the trip. mpg_curr = miles_traveled / gas_used # Output the MPG for this leg. print("Leg", leg, "MPG:", round(mpg_curr, 2)) # Set the previous odometer to the current odometer for the next loop odometer_prev = odometer_curr # Increment the leg counter. leg += 1 # Finally, calculate the total average MPG for the trip and output that value. print("Total MPG:", round(miles_total / gas_total, 2))
true
e8e74b30ac6da31bb4907216ea45f4a3136c23cb
eembees/molstat_water
/rotation.py
2,600
4.15625
4
## rotation.py Version 1.0 ## Written by Magnus Berg Sletfjerding (eembees) ########################################################### """Rotation Functions, inspired by http://paulbourke.net/geometry/rotate/ Verified as working 01/07/17 by eembees""" """Importing modules""" import numpy as np from math import pi, sin, cos, sqrt def rotation3d(axis1, axis2, point, angle): """Rotates a point around an arbitrary axis in a 3D space INPUTS: *axis1 -- 3d (xyz) array of 1st axis point *axis2 -- 3d (xyz) array of 2nd axis point *point -- 3d (xyz) array of point to be rotated *angle -- angle (radians) of rotation Positive angles are counter-clockwise. """ #Translate axis to (virtual) origin, define new point ax ax = point - axis1 axis1_neg = [-x for x in axis1] axis2_neg = [-x for x in axis2] #Initialize virtual rotation point rot rot = [0.0, 0.0, 0.0] # Axis direction vector (normalized) N = map(sum, zip(axis2, axis1_neg)) # axis vector sqsum = sqrt(sum((N[i]**2) for i in range(3))) direction = [N[i]/sqsum for i in range(3)] # Simplifying 3d rotation matrix factors - cosine, sine, translation factor co = cos(angle) tr = (1-cos(angle)) si = sin(angle) x = direction[0] y = direction[1] z = direction[2] # Matrix 'D'[3x3] 3D rotation matrix d11 = tr*x**2 + co d12 = tr*x*y - si*z d13 = tr*x*z + si*y d21 = tr*x*y + si*z d22 = tr*y**2 + co d23 = tr*y*z - si*x d31 = tr*x*z - si*y d32 = tr*y*z + si*x d33 = tr*z**2 + co # # Define rot rot[0] = d11 * ax[0] + d12 * ax[1] + d13 * ax[2] rot[1] = d21 * ax[0] + d22 * ax[1] + d23 * ax[2] rot[2] = d31 * ax[0] + d32 * ax[1] + d33 * ax[2] # # Define output point as rotation point transformed back newpoint = rot + axis1 return newpoint if __name__ == '__main__': import extract as ex a, b, c = ex.readfile("w6.xyz") # # reading file # Test for distances > paste this after rotation to see if the rotation maintains accurate distance ''' dlist = [] d = 0 for i in range(3): d += c[1][i]-c[0][i] d = np.sqrt(d) dlist.append(d) d = 0 for i in range(3): d += c[1][i]-c[2][i] d = np.sqrt(d) dlist.append(d) d = 0 for i in range(3): d += c[0][i]-c[2][i] d = np.sqrt(d) dlist.append(d) dist = np.sqrt(sum([i**2 for i in dlist])) print "DISTANCE BEFORE: \n", dist ''' c[1] = rotation3d(c[0], c[2], c[1], 1*pi) ex.writefile("w6_rotated.xyz", a, b, c) # # Writing file
true
7c57ed755f03c05a03c281e2b9a03529f8b441a2
Re-Creators/ScriptAllTheThings
/Temperature Scale Converter/temperature_scale_converter.py
1,211
4.5
4
""" Temperature Scale Converter - Inputs the value from the user and converts it to Fahrenheit,Kelvin & Celsius Author : Niyoj Oli Date : 01/10/21 """ temp = input("Input the temperature you would like to convert? (e.g., 45F, 102C, 373K ) : ") degree = float(temp[:-1]) # the first value of the input is taken as the degree i_convention = temp[-1] # second value becomes the unit if i_convention.upper() == "C": result_1 = float((degree*1.8)+32) o_convention_1 = "Fahrenheit" result_2 = float(degree+273.15) o_convention_2 = "Kelvin" elif i_convention.upper() == "F": result_1 = float((degree-32)/1.8) o_convention_1 = "Celsius" result_2 = float(result_1+273.15) o_convention_2 = "Kelvin" elif i_convention.upper() == "K": result_1 = float((degree-273.15)*1.8+32) o_convention_1 = "Fahrenheit" result_2 = float(degree-273.15) o_convention_2 = "Celsius" else: print("Input proper convention.") quit() # stops the program and code after this will not be executed print("The temperature in", o_convention_1, "is", result_1, "degrees. \nThe temperature in", o_convention_2, "is", result_2, "degrees.") # \n represents new line
true
efc8169de6a436f2ba9910ae37a8526d92bd7456
JuliasBright/Python
/Simple Calculator.py
1,685
4.3125
4
import sys while True: print("Welcome To My Simple Calculator") print("Enter this Abbreviations To Continue") print("Enter + for Adding") print("Enter - for Substractiing") print("Enter * for Multiplication") print("Enter / for Dividing") print("Enter ** for Exponation") print("To quit Enter Q") user_input = input(":") if user_input == "Q": sys.exit() elif user_input == "+": print("You have Enter Adding") num1 = (float(input("You have to Enter a number"))) num2 = (float(input("Enter another number"))) result = (str(num1 + num2)) print(result) elif user_input == "-": print("You have Enter Substraction") num1 = (float(input("You have to Enter a number"))) num2 = (float(input("Enter another number"))) result = (str(num1 - num2)) print(result) elif user_input == "*": print("You have Enter Adding") num1 = (float(input("Enter a number"))) num2 = (float(input("Enter a number"))) result = (str(num1 * num2)) print(result) elif user_input == "/": print("You have Enter Adding") num1 = (float(input("Enter a number"))) num2 = (float(input("Enter a number"))) result = (str(num1 / num2)) print(result) elif user_input == "**": print("You have Enter Adding") num1 = (float(input("Enter a number"))) num2 = (float(input("Enter a number"))) result = (str(num1 ** num2)) print(result) else: sys.exit() print("You have enter the wrong choice Goodbye")
true
5a5bfac15fdf423e125b8aa56655bdb3dbccff7a
Gagan-453/Python-Practicals
/Searching names from a list.py
1,103
4.1875
4
# Searching elements in a list lst=['Gagan Adithya', 'Advith', 'Harsha', 'Praveen'] for i in range(len(lst)): lst[i] = lst[i].lower() #Converting all the names in the list into lower case letters print(lst) x = input("enter element to search:") x = x.lower() #Converting all the letters into lower case letters from the input x = x.lstrip() #Removing all the spaces from the input at left x = x.rstrip() #Removing all the spaces from the input at right for i in lst: if x in i: print(i) continue # Alternate Method lst=['Gagan Adithya', 'advith', 'Harsha', 'Praveen', 'Ranjeet'] x = input("Enter element to search:") #taking input from the user x = x.strip() #Removing the spaces from beginning or end of the name from the input for i in range(len(lst)): for j in lst: if x.lower() in lst[i].lower(): #Converting all letters into lower case letters from the input and all elements in the list and checking if input is in the list print(lst[i]) #if input is in list print the name which is in lst break # Stopping the loop
true
3756486b3c91b557bff353dff8708ef25cca9a32
Gagan-453/Python-Practicals
/GUI/Canvas/Creating oval.py
1,375
4.875
5
# Creating Oval using Canvas from tkinter import * #Create a root window root = Tk() # var c is Canvas class object # root is the name of the parent window, bg is background colour, height is the height of the window and width is the breadth of window, cursor represents the shape of the cursor in the canvas c = Canvas(root, bg = 'green', height = 700, width = 1200, cursor = 'star') # create_oval() function can used to create oval or circle # (100, 100, 400, 300) are pixels, which creates an oval in the rectangular area defined by the top left coordinates (100, 100) and bottom lower coordinates (400, 300) # (100, 100) represents 100 pixels from the top left corner and 100 pixels to down from that point, this is where an oval is made # (400, 300) represents 400 pixels from top left corner and 300 pixels down from that point(400 pixels from top left corner), these are measurements of the oval # Width specifies the width of the line, fill specifies the colour of the line, outline specifies the colour of the border, activefill represents the colour to be filled when the mouse is placed on the oval id = c.create_oval(100, 100, 400, 300, width = 5, fill='yellow', outline = 'red', activefill = 'green') #Once the Canvas is created, it should be added to the root window. Then only it will be visible. This is done using pack() method c.pack() root.mainloop()
true
52a149c679fb0740c4dc8685c485ee583ce9a66b
Gagan-453/Python-Practicals
/Abstract Class example.py
1,041
4.34375
4
# Example of Abstract Class from abc import* class Car(ABC): def __init__(self, regno): self.regno = regno def opentank(self): print('Fill the fuel into the tank') print('For the car with regno ', self.regno) @abstractmethod def steering(self): pass @abstractmethod def braking(self): pass print('---------MARUTI CAR---------') class Maruti(Car): def steering(self): print('Maruti uses manual steering') print('Drive the car') def braking(self): print('Maruti uses hydraulic brakes') print('Apply brakes and stop the car') m = Maruti(1001) m.opentank() m.steering() m.braking() print('---------SANTRO CAR---------') class Santro(Car): def steering(self): print('Santro uses power steering') print('Drive the car') def braking(self): print('Maruti uses gas brakes') print('Apply brakes and stop the car') s = Santro(7878) s.opentank() s.steering() s.braking()
false
44c151aff1f59e0ca9418405b9a4d7ba2ce98f30
Gagan-453/Python-Practicals
/GUI/Canvas/Creating images.py
939
4.125
4
#We can display an image with the help of create_image function from tkinter import * #Create a root window root = Tk() #Create Canvas as a child to root window c = Canvas(root, bg='white', height=700, width=1200) #Copy images into files file1 = PhotoImage(file="Peacock.png") file2 = PhotoImage(file='Screenshot (40).png') #The image is displayed relative to the point represented by the coordinates (500, 200) #The image can be placed in any direction from this point indicated by anchor (8 Directions - NW, N, NE, E, SE, S, SW, W, CENTER) #Image to be displayed is file1 and 'activeimage' is the image to be shown when the cursor is placed on the image id = c.create_image(500,200, anchor=NE, image=file1, activeimage=file2) #Create some text id = c.create_text(800, 500, text='This is a thrilling photo', font=('Helvetica', 30, 'bold underline'), fill='blue') #Add canvas to the root c.pack() #Wait for any events root.mainloop()
true
554f38054fbb5da57d3a88668beb4acae711007d
Gagan-453/Python-Practicals
/GUI/Frame/Frame and Widget.py
1,701
4.375
4
# FRAME Container #a frame is similar to canvas that represents a rectangular area where some text or widgets can be displayed from tkinter import * #Create root window root = Tk() #Give a title for root window root.title('Gagan\'s frame') #Create a frame as child to root window f = Frame(root, height=400, width=500, bg='yellow', cursor='cross') # f is the object of Frame class # The options 'height' and 'width' represent the height and width of the frame in pixels # 'bg' represents the back ground colour to be displayed and 'cursor' indicates the type of the cursor to be displayed in the frame #Attach the frame to the root window f.pack() #Let the root window wait for any events root.mainloop() # WIDGETS #A widget is a GUI component that is displayed on the screen and can perform a task as desired by the user #To create widget suppose Button widget, we can create an object of the Button class as: # b = Button(f, text='My Button') # 'f' is frame object to which the button is added, 'My Button is the text that is displayed on the button #When the user interacts with a widget, he will generate an event, these events should be handled by writing functions or routines, these are called event handlers # Event handler example: #def ButtonClick(self): # print('You have clicked me') #This message should be displayed when the user clicks on Button 'My Button' # When user clicks on the button, that clicking event should be linked with the 'event handler' function # This is done using bind() method #Example for bind(): # b.bind('<Button-1>, ButtonClick) # 'b' represents the push button and <Button-1> indicates the left mouse button, linked to the function ButtonClick()
true
21e92d5add01747577aac38d6d9e46180f0492eb
Gagan-453/Python-Practicals
/GUI/Frame/Listbox Widget.py
2,547
4.40625
4
# LISTBOX WIDGET # It is useful to display a list of items, so that he can select one or more items from tkinter import * class ListBox: def __init__(self, root): self.f = Frame(root, width=700, height=400) #Let the frame will not shrink self.f.propagate(0) # Attach the frame to the root window self.f.pack() # Create a label self.lbl = Label(self.f, text='Click one or more universities below:', font=('Calibri 14')) self.lbl.place(x=50, y=50) #Create List box with university names # 'fg' option represents the colour of the text in the list box, 'bg' represents the back ground colour, 'height' represents the height of the list box, 'selectmode' option represents to select single or multiple items from the box # 'selectmode' can be 'BROWSE', 'SINGLE', 'MULTIPLE', 'EXTENDED' self.lb = Listbox(self.f, font='Arial 12 bold', fg='green', bg='yellow', height=10, selectmode=MULTIPLE) self.lb.place(x=50, y=100) #Using for loop, insert items into list box for i in ["Standford University", "Oxford University", "Texas A&M University", "Cambridge University", "University of California"]: self.lb.insert(END, i) #We can insert items into list box using insert() method # Bind the ListboxSelect event to on_select() method self.lb.bind('<<ListboxSelect>>', self.on_select) # Create a text box to display selected items self.t = Text(self.f, width=40, height=6, wrap=WORD) self.t.place(x=300, y=100) def on_select(self, event): #Create an empty list self.lst = [ ] #Know the indexes of the selected items # We can know the selected items in the list box using curselection() method indexes = self.lb.curselection() # Retrieve the items names depending on indexes # Append the items names to the list # We can get the selected items from indexes using get(index) method for i in indexes: self.lst.append(self.lb.get(i)) # Delete the previous content of the text box self.t.delete(0.0, END) # Insert the new contents into the text box self.t.insert(0.0, self.lst) # Create root window root = Tk() # title for the root window root.title("List box") # Create object to ListBox class obj = ListBox(root) # Handle any events root.mainloop()
true
d96e1b7876aebe651540e50fa717d03bd162c853
Gagan-453/Python-Practicals
/GUI/Frame/Button Widget/Arranging widgets in a frame/Place layout manager.py
1,899
4.5625
5
# PLACE LAYOUT MANAGER # Place layout manager uses place() method to arrange widgets #The place() method takes x and y coordinates of the widget along with width and height of the window where the widget has to be displayed from tkinter import * class MyButton: #Constructor def __init__(self, root): #Create a frame as child to root window self.f = Frame(root, height=400, width=500) #Let the frame will not shrink self.f.propagate(0) #Attach the frame to root window self.f.pack() #Create 3 push buttons and bind them to buttonClick method and pass a number self.b1 = Button(self.f, text='Red', command= lambda: self.buttonClick(1)) self.b2 = Button(self.f, text='Green', width=15, height=2, command= lambda: self.buttonClick(2)) self.b3 = Button(self.f, text='Blue', width=15, height=2, command= lambda: self.buttonClick(3)) #Attach buttons to the frame self.b1.place(x=20, y=30, width=100, height=50) #Display at (20, 30), coordinates in the window 100 px width and 50 px height self.b2.place(x = 20, y = 100, width=100, height=50) # Display at (20, 100) self.b3.place(x=200, y=100, width=100, height=50) #Display at (200, 100) #Method to be called when the Button is clicked def buttonClick(self, num): #Set background color of the frame depending on the button clicked if num==1: self.f["bg"] = 'red' print('You have chosen Red') if num==2: self.f["bg"] = 'green' print('You have chosen Green') if num==3: self.f["bg"] = 'blue' print('You have chosen Blue') #Create root window root = Tk() #Create an object to MyButton class mb = MyButton(root) #The root window handles the mouse click event root.mainloop()
true
c0309348cb3d4dba07c8d321cbc157e5dbdd6d0f
Gagan-453/Python-Practicals
/GUI/Frame/Menu Widget.py
1,979
4.1875
4
# MENU WIDGET # Menu represents a group of items or options for the user to select from. from tkinter import * class MyMenu: def __init__(self, root): # Create a menubar self.menubar = Menu(root) # attach the menubar to the root window root.config(menu=self.menubar) # create file menu # 'tearoff' can be 0 or 1 self.filemenu = Menu(root, tearoff=0) # create menu items in the file menu # Add options and bind it to donothing() method self.filemenu.add_command(label="New", command=self.donothing) self.filemenu.add_command(label="Open", command=self.donothing) self.filemenu.add_command(label="Save", command=self.donothing) # add a horizontal line as separator # This creates a separator after the 3 options "New", "Open", "Save" self.filemenu.add_separator() # create another menu item below the separator self.filemenu.add_command(label='Exit', command=root.destroy) # add the file menu with a name "file" to the menubar self.menubar.add_cascade(label="File", menu=self.filemenu) # create edit menu self.editmenu = Menu(root, tearoff=0) # create menu items in edit menu self.editmenu.add_command(label="Cut", command=self.donothing) self.editmenu.add_command(label="Copy", command=self.donothing) self.editmenu.add_command(label="Paste", command=self.donothing) # add the edit menu with a name 'Edit' to the menubar self.menubar.add_cascade(label="Edit", menu=self.editmenu) def donothing(self): pass # create root window root = Tk() # title for the root window root.title("A Menu Example...") # Create object to MyMenu class obj = MyMenu(root) # define the size of the root window root.geometry('600x500') # handle any events root.mainloop()
true
56b0a0a2582b0e26197affa6d27865dbfe5abb26
Gagan-453/Python-Practicals
/Date and Time.py
2,356
4.5625
5
#The epoch is the point where the time starts import time epoch = time.time() #Call time function of time module print(epoch) #Prints how many seconds are gone since the epoch .i.e.Since the beginning of the current year #Converting the epoch into date and time # locatime() function converts the epoch time into time_struct object import time t = time.localtime(epoch) #Retrieve the date from the structure t d = t.tm_mday m = t.tm_mon y = t.tm_year print('Current date is: %d - %d - %d' %(d, m, y)) #Retrieve the time from the structure t h = t.tm_hour m = t.tm_min s = t.tm_sec print('Current time is: %d:%d:%d' %(h, m, s)) print('----------------------------------------------') import time t = time.ctime(epoch) #ctime() with epoch seconds print(t) #Using ctime() without epoch import time t = time.ctime() #ctime() without epoch time print(t) #Current date and time print('----------------------------------------------') #Using datetime module to know current date and time # now() method can be used to access day, month and year using the attributes day, month, year. Similarly, we can use hour, minute, second from datetime import * #import datetime module now = datetime.now() print(now) print('Date now: {}/{}/{}' .format(now.day, now.month, now.year)) #Retrieve current date using now() method print('Time now: {} : {} : {}' .format(now.hour, now.minute, now.second)) #Retrieve current time using now() method print('----------------------------------------------') #Program to know today's date and time from datetime import * tdm = datetime.today() #today() of datetime class gives date and time print("Today's date and time = ", tdm) td = date.today() # today() of date class gives date only print("Today's date = ", td) print('----------------------------------------------') #Combining date and time from datetime import * d = date(2020, 5, 27) #Create date class object and store some date t = time(15, 30, 24) dt = datetime.combine(d, t) #Combine method of 'datetime' class used to combine date and time objects print(dt) print('----------------------------------------------') #Create a datetime object and then change its contents from datetime import * dt1 = datetime(year = 2020, month = 10, day = 27, hour = 9, minute = 45) #Create a datetime object print(dt1) dt2 = dt1.replace(year = 2008, hour = 17, month = 5) print(dt2)
true
ec4fc0042d9e6100b485588b60be49413925bcb7
Gagan-453/Python-Practicals
/Exceptions.py
2,030
4.59375
5
# Errors which can be handled are called 'Exceptions' # Errors cannot be handled but exceptions can be handled #to handle exceptions they should be written in a try block #an except block should be written where it displays the exception details to the user #The statements in thefinally block are executed irrespective of whether there is an exception or not # SYNTAX: #try: # statements #except exceptionname1: # handler1 #except exceptionname2: #A try block can be followed by several except blocks # handler2 #else: # statements #finally: # statements try: 2/0 except ZeroDivisionError as ZDE: print('Division by zero is not possible') print('Please don\'t input zero as input') else: print('Solution is calculated') #if zero is not given as input print 'Solution is calculated finally: print('Problem Solved') # else block and finally block are optional print('--------------------') # Using the try block with finally block try: x = int(input('Enter a number: ')) y = 1/x finally: print('No exception') print('The inverse is: ', y) print('--------------------') # The assert statement # This statement is used to check whether a condition is True or not # If the condition is False then an AssertionError is raised try: x = int(input('Enter a number between 5 and 10:')) assert x>=5 and x<=10 #If these conditions fulfill the input print('The number entered: ', x) #Print the number except AssertionError: print('Wrong input Entered: ', x) print('--------------------') #Passing message if the input is not correct try: x = int(input('Enter a number between 5 and 10:')) assert x>=5 and x<=10, 'Your input is incorrect' #If these are False, print('Your input is incorrect') print('The number entered: ', x) #Print the number except AssertionError as obj: #We can catch the expression as an object that contains some description about the exception print(obj) # except: # statements # 👆This catches all types of exceptions
true
b3a045b0649342236300272420e3d5ecdb13f65d
sabbir421/python
/if elif else.py
313
4.1875
4
day=int(input("number of day: ")) if day==1: print("Saturday") elif day ==2: print("Sunday") elif day ==3: print("Monday ") elif day ==4: print("Tuesday ") elif day ==5: print("Wednesday ") elif day ==6: print("Tuesday") elif day ==7: print("Friday ") else: print("7 days in week")
false
58d37c8c9a0be25faee85b7d15e6a1958cbf466f
harshbhardwaj5/Coding-Questions-
/Allsubarrayrec.py
501
4.15625
4
# Python3 code to print all possible subarrays def printSubArrays(arr, start, end): # Stop if we have reached the end of the array if end == len(arr): return # Increment the end point and start from 0 elif start > end: return printSubArrays(arr, 0, end + 1) # Print the subarray and increment the starting # point else: print(arr[start:end + 1]) return printSubArrays(arr, start + 1, end) # Driver code arr = ["1, 2, 3,4"] printSubArrays(arr, 0, 0)
true
93fe621719192fd6fc2a29f328bdb0181be8ba54
ncamperocoder1017/CIS-2348
/Homework1/ZyLabs_2_19.py
1,885
4.125
4
# Nicolas Campero # 1856853 # Gather information from user of ingredients and servings amount print('Enter amount of lemon juice (in cups):') l_juice_cups = float(input()) print('Enter amount of water (in cups):') water_cups = float(input()) print('Enter amount of agave nectar (in cups):') agave_cups = float(input()) print('How many servings does this make?') servings = int(input()) # output amount of ingredients for x amount of servings print('\n', end='') print('Lemonade ingredients - yields', '{:.2f}'.format(servings), 'servings') print('{:.2f}'.format(l_juice_cups), 'cup(s) lemon juice') print('{:.2f}'.format(water_cups), 'cup(s) water') print('{:.2f}'.format(agave_cups), 'cup(s) agave nectar') print('\n', end='') print('How many servings would you like to make?') servings_to_make = float(input()) # adjust amounts of each ingredient to match servings amount print('\n', end='') print('Lemonade ingredients - yields', '{:.2f}'.format(servings_to_make), 'servings') multiple_of_servings = float(servings_to_make / servings) lemon_after_servings = l_juice_cups * multiple_of_servings water_after_servings = water_cups * multiple_of_servings agave_after_servings = agave_cups * multiple_of_servings print('{:.2f}'.format(lemon_after_servings), 'cup(s) lemon juice') print('{:.2f}'.format(water_after_servings), 'cup(s) water') print('{:.2f}'.format(agave_after_servings), 'cup(s) agave nectar') # convert ingredient measurements from part 2 to gallons lemon_gallons = lemon_after_servings / 16.00 water_gallons = water_after_servings / 16.00 agave_gallons = agave_after_servings / 16.00 print('\n', end='') print('Lemonade ingredients - yields', '{:.2f}'.format(servings_to_make), 'servings') print('{:.2f}'.format(lemon_gallons), 'gallon(s) lemon juice') print('{:.2f}'.format(water_gallons), 'gallon(s) water') print('{:.2f}'.format(agave_gallons), 'gallon(s) agave nectar')
true
73f2fa07999ca1fcc2bc2f8bf0abd832276bd149
juliagolder/unit-2
/unitConverter.py
938
4.46875
4
#julia golder #2/14/18 #unitConverter.py - how to convert units print('1: kilometers to Miles') print('2: Kilograms to Pounds') print('3: Liters to Gallons') print('4: Celsius to Fahrenheit') number = int(input('Choose a number: ')) if number == 1: celcius = int(input('Enter Degrees in Celcius: ')) fahrenheit = celcius * 1.8 + 32 print(celcius,'degrees Celsius is', fahrenheit,'degres in Fahrenheit') elif number == 3: kilograms = int(input('Enter a number of Kilograms: ')) pounds = kilograms/0.453592 print(kilograms,'Kilograms is', pounds,'pounds') elif number == 2: liters = int(input('Enter amount in liters: ')) gallons = liters/3.785411784 print(liters,'liters is', gallons,' gallons') elif number == 4: kilometers = int(input('Enter a number of Kilometers')) miles = kilometers/1.60934 print(kilometers,'kilometers is', miles,'miles') else: print('Error, number not an option')
false
e38197efcd64d6ad928d207bf789273cb0a6fb08
cr8ivecodesmith/basic-programming-with-python
/lpthw/ex11.py
756
4.25
4
# Exercise 11: Asking questions print('How old are you?', end=' ') age = input() print('How tall are you?', end=' ') height = input() print('How much do you weigh?', end=' ') weight = input() print("So you're %r old, %r tall and %r heavy." % (age, height, weight)) # Note # Notice that we put an end=' ' after the string in the print command. This so # we can change the default way Python ends a print command from a newline (\n) # to just using a space (' '). # Study Drills # 1. Go online and find out what Python's input() does. # 2. Can you find other ways to use it? Try some of samples you find. # 3. Write another "form" like this to ask some other questions. # Personal Challenge # 4. Remove the end=' ' in the print command. What happens?
true
637c98c17ed65d72a4538fb19958ed10198a017b
onkcharkupalli1051/pyprograms
/ds_nptel/test 2/5.py
676
4.28125
4
""" A positive integer n is a sum of three squares if n = i2 + j2 + k2 for integers i,j,k such that i ≥ 1, j ≥ 1 and k ≥ 1. For instance, 29 is a sum of three squares because 10 = 22 + 32 + 42, and so is 6 (12 + 12 + 22). On the other hand, 16 and 20 are not sums of three squares. Write a Python function sumof3squares(n) that takes a positive integer argument and returns True if the integer is a sum of three squares, and False otherwise. """ def sumof3squares(n): for i in range(n): for j in range(n): for k in range(n): if(n == i**2 + j**2 + k**2): return True return False print(sumof3squares(16))
true
812dde47bf82dde83275c5a6e5c445ef6a0171ab
onkcharkupalli1051/pyprograms
/ds_nptel/NPTEL_DATA_STRUCTURES_TEST_1/ques4.py
580
4.34375
4
""" Question 4 A list is a non-decreasing if each element is at least as big as the preceding one. For instance [], [7], [8,8,11] and [3,19,44,44,63,89] are non-decreasing, while [3,18,4] and [23,14,3,14,3,23] are not. Here is a recursive function to check if a list is non-decreasing. You have to fill in the missing argument for the recursive call. def nondecreasing(l): if l==[] or len(l) == 1: return(True) else: return(...) Open up the code submission box below and fill in the missing argument for the recursive call. """ l[0] <= l[1] and nondecreasing(l[1:])
true
62edb5acaf0f4806e84966e822083a39cdf66805
YhHoo/Python-Tutorials
/enumerate.py
477
4.125
4
''' THIS IS enumerate examples**** it allows us to loop over something and have an automatic counter ''' c = ['banana', 'apple', 'pear', 'orange'] for index, item in enumerate(c, 2): # '2' tell the enumerate to start counting from 2 print(index, item) ''' [CONSOLE] 2 banana 3 apple 4 pear 5 orange ''' c = ['banana', 'apple', 'pear', 'orange'] for index, item in enumerate(c): print(index, '+', item) ''' [CONSOLE] 0 + banana 1 + apple 2 + pear 3 + orange '''
true
1dd0e6d8e73c6dbd174227baf893ad6695f56dab
thisguyisbarry/Uni-Programming
/Year 2/Python/labtest2.py
2,048
4.5
4
import math class Vector3D(object): """Vector with 3 coordinates""" def __init__(self, x, y, z): """Takes in coordinates for a 3d vector""" self.x = x self.y = y self.z = z self.magnitude = 0 def __add__(self, v2): """Adds two 3D vectors (x+a, y+b, z+c) where x,y,z are from the first vector and a,b,c are from the second vector""" return self.x + v2.x, self.y + v2.y, self.z + v2.z def __sub__(self, v2): """Subtracts two 3D vectors (x-a, y-b, z-c) where x,y,z are from the first vector and a,b,c are from the second vector""" return self.x - v2.x, self.y - v2.y, self.z - v2.z def __mul__(self, n): """Multiplies the a 3d vector either by an integer in the form (x*n, y*n, z*n) or in the form (x*a + y*b + z*c) where x,y,z are from the first vector and a,b,c are from the second vector to get the dot product""" # Check which type of multiplication needs to be done if type(n) == int: return self.x * n, self.y * n, self.z * n else: return self.x * n.x + self.y * n.y + self.z * n.z def magnitude(self): """Finds the magnitude of a 3d vector The magnitude is gotten by: sqrt(x^2+y^2+z^2)""" self.magnitude = math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) def __str__(self): return "( {}, {}, {} )".format(self.x, self.y, self.z) v1 = Vector3D(1, 2, 3) v2 = Vector3D(5, 5, 5) print("Printing v1") print("v1 = ", v1) print("Printing v2") print("v2 = ", v2) v3 = v1 + v2 print("Printing addition") print("v1 + v2 = ", v3) v4 = v1 - v2 print("Printing subtraction") print("v1 - v2 = ", v4) v5 = v1 * v2 print("Printing dot product") print("v1 * v2 = ", v5) print("Printing integer multiplication") v6 = v1 * 2 print("v1 * 2 = ", v6) # Not sure why this isn't working # print("v1 magnitude is ", v1.magnitude())
true
30e68edadbaba888f4e0c6b4f04e074a43051738
The-Blue-Wizard/Miscellany
/easter.py
627
4.40625
4
#!/bin/python # Python program to calculate Easter date for a given year. # This program was translated from an *ancient* BASIC program # taken from a certain black papercover book course on BASIC # programming whose title totally escapes me, as that was # during my high school time. Obviously placed in public # domain, and don't ask me how it works! :-) print i = int(raw_input('Year: ')) v = i % 19 w = i % 4 t = i % 7 c = 19*v+24 s = c % 30 c = 2*w+4*t+6*s+5 z = c % 7 d = 22+s+z if d <= 31: print 'The date of Easter is March %d, %d' % (d,i) else: d -= 31 print 'The date of Easter is April %d, %d' % (d,i)
true
132c7a205f2f0d2926e539c172223fb505a0f2c1
L-ByDo/OneDayOneAlgo
/Algorithms/Searching_Algorithms/Binary Search/SquareOfNumber.py
1,338
4.25
4
#Find the square of a given number in a sorted array. If present, Return Yes with the index of element's index #Else return No #Program using Recursive Binary Search #Returns True for Yes and False for No def BinarySearch(arr, left, right, NumSquare): #check for preventing infinite recursive loop if right >= left : mid = left + (right-left) // 2 # If element is present at the middle itself if arr[mid] == NumSquare: return True # If element is smaller than mid, then it # can only be present in left subarray elif arr[mid] > NumSquare: return BinarySearch(arr, left, mid-1, NumSquare) # Else the element can only be present # in right subarray else: return BinarySearch(arr, mid+1, right, NumSquare) #Element not present in array else: return False #input a sorted array. A sorted array is either of ascending order or descending order arr = [int(x) for x in input().split()] left = 0 #left index Num = int(input()) #Number whose square is to be searched for NumSquare = Num*Num #Function CAll result = BinarySearch(arr, 0, len(arr)-1, NumSquare) #check for True if result: print("Yes! " + "The index of square of {} is {}".format(Num, arr.index(Num*Num))) #For false else: print("No")
true
94e17585ee5d0fc214dea1cbc886bd8fa33af30e
EmreCenk/Breaking_Polygons
/Mathematical_Functions/coordinates.py
2,277
4.5
4
from math import cos,sin,radians,degrees,sqrt,atan2 def cartesian(r,theta,tuple_new_origin=(0,0)): """Converts height given polar coordinate r,theta into height coordinate on the cartesian plane (x,y). We use polar coordinates to make the rotation mechanics easier. This function also converts theta into radians.""" #theta=0.0174533*theta #1 degrees = 0.0174533 radians theta=radians(theta) # we need to modify our calculation for the new origin as well x=r*cos(theta)+tuple_new_origin[0] #finding x y=r*sin(theta)+tuple_new_origin[1] #finding y return (x,y) def polar(x,y,tuple_new_origin=(0,0)): """Is the inverse function of 'cartesian'. Converts height given cartesian coordinate; x,y into height polar coordinate in the form (r, theta). """ w=(x-tuple_new_origin[0]) #width of mini triangle h=(y-tuple_new_origin[0]) #height of mini triangle r=sqrt((w**2)+(h**2)) # from the pythagorean theorem theta=atan2(h,w) return r,degrees(theta) #I was going to use the following function, but it increases the computational complexity of the game too much # def elipse_to_polygon(centerx, centery, height, width, accuracy=5): # print("input",centerx, centery, height, width) # """This function converts an elıpse to """ # coordinates=[] # coordinates2=[] # y_dif= 2 * height / accuracy # for i in range(accuracy): #loop through y values on the elipse and calculate the corresponding x coordinate. # # y=y_dif*i+centery # #using the equation of an elipse, we can solve for x: # # soloution_part_1=sqrt( # (1- (((y-centery)/width)**2))*(height**2) # ) # #The square root can be positive or negatve. That's why we will add both coordinates. # coordinates.append([y, centerx + soloution_part_1]) # coordinates2.append([y, centerx - soloution_part_1]) # # final=[] # for i in coordinates: # final.append(i) # for i in range(1,len(coordinates2)): # final.append(coordinates2[-i]) # return final if __name__ == '__main__': angle=123 r=12 new=cartesian(r,angle) print(new) neww=polar(new[0],new[1]) print(neww)
true
893fff12d545faa410309b4b2b087305e6ad99cc
AxiomDaniel/boneyard
/algorithms-and-data-structures/sorting_algorithms/insertion_sort.py
1,596
4.59375
5
#!/usr/bin/env python3 def insertion_sort(a_list): """ Sorts a list of integers/floats using insertion sort Complexity: O(N^2) Args: a_list (list[int/float]): List to be sorted Returns: None """ for k in range(1, len(a_list)): for i in range(k - 1, -1, -1): # print("k: " + str(k) + " i: " + str(i)) if a_list[i] > a_list[i + 1]: a_list[i + 1], a_list[i] = a_list[i], a_list[i + 1] else: # print("break") break # print(a_list) def main(): sample_list = [5, 2, 1, 3, 6, 4] print("Unsorted List: " + str(sample_list)) insertion_sort(sample_list) print("Sorted List: " + str(sample_list)) if __name__ == '__main__': main() ''' Reasoning for complexity: Insertion sort imaginarily partitions the array into two parts: one unsorted and one sorted. The sorted partition starts off with one element only, that is, the first element in the array. With each successive iteration, insertion grows the sorted partition by one element. In the process of growing the sorted partition by one element, it has to find an appropriate position for that element. This requires the algorithm to compare that element with elements already within the sorted partition. With N elements, insertion sort will have to run N-1 iterations to grow the sorted partition. At k-th iteration, it might have to do a maximum of k-1 comparisons. k is bounded by N, which is the number of elements in the list Therefore, insertion sort can be bounded by O(N^2) '''
true
deb7f660c0f607492dbbcd59c71936876c893b35
Erik-D-Mueller/Python-Neural-Network-Playground
/Version1point0/initial.py
1,363
4.3125
4
# 02-12-2020 # following along to a video showing how to implement simple neural network # this is a perceptron, meaning it has only one layer import numpy as np # sigmoid function is used to normalize, negatives values return a value below 1/2 and approaching zero, positive values return above 1/2 and approaching 1 def sigmoid(x): return 1 / (1 + np.exp(-x)) # def sigmoid_derivative(x): return x * (1 - x) # training input data training_input_data = np.array([ [0,1,0], [1,1,1], [1,0,1], [0,1,0]]) training_output_data = np.array([[0, 1, 1, 0]]).T #creates a 1x3 matrix with values between -1 and 1 synaptic_weights = 2 * np.random.random((3, 1)) - 1 print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('Initial Random starting synaptic weights: ') print(synaptic_weights) input_layer = training_input_data for iteration in range(200): outputs = sigmoid(np.dot(training_input_data,synaptic_weights)) error = training_output_data - outputs adjustments = error + sigmoid_derivative(outputs) synaptic_weights += np.dot(input_layer.T, adjustments) print('Synaptic weights after training') print(synaptic_weights) print('Final Synaptic Weights') print(synaptic_weights) print('Outputs after training') print(outputs)
true
1326800eed0a49d19b8e959f7d58e2e65195963a
ImtiazMalek/PythonTasks
/input.py
215
4.375
4
name=input("Enter your name: ")#user will inter name and comment age=input("Enter your age: ")#and we are saving it under various variables print("Hello "+name+", you are "+age+" years old")#it'll print the result
true
45e52f554eee3a9c1153ab1fe29bedac254891a3
sitati-elsis/teaching-python-demo
/inheritance.py
760
4.1875
4
class Parent(): def __init__(self,last_name,eye_color): print ("Parent constructor called") self.last_name = last_name self.eye_color = eye_color def show_info(self): print "%s %s" %(self.last_name,self.eye_color) billy_cyrus = Parent("Cyrus","blue") billy_cyrus.show_info() class Child(Parent): def __init__(self,last_name,eye_color,number_of_toys): print "Child constructor called" """ To initiliaze the values we are inheriting from class parent we should reuse class parent's __init__method """ Parent.__init__(self,last_name,eye_color) # Initialize number of toys self.number_of_toys = number_of_toys miley_cyrus = Child("Cyrus","blue",5) miley_cyrus.show_info() # print miley_cyrus.last_name # print miley_cyrus.number_of_toys
true
1715e784d1614edae62ce5918e286ec187997c34
doctorOb/euler
/P9-pythagoreanTriplet.py
720
4.1875
4
"""There exists exactly one Pythagorean triplet for which a + b + c = 1000 Find the product abc.""" import math def isPythagoreanTriplet(a,b,c): """determine if a < b < c and a^2 + b^2 = c^2 formally, a Pythagorean triplet""" if a < b and b < c: return (a**2 + b**2) == c**2 else: return False def solve(n): """n = a + b + c, where a,b,c are a pythagorean triplet""" for a in range(1,n): for b in range(a,n): for c in range(b,n): if a + b + c == 1000 and isPythagoreanTriplet(a,b,c): return (a,b,c) if __name__ == '__main__': print("{} tiplet? {}".format((3,4,5),isPythagoreanTriplet(3,4,5))) ans = solve(1000) print(ans) sum = reduce(lambda x,y: x*y,ans) print("{}".format(sum))
false
2245c07a64384e77a44b9540fcd551f245492289
ShimaSama/Python
/email.py
344
4.3125
4
#program to know if the email format is correct or not email=input("Introduce an email address: ") count=email.count('@') count2=email.count('.') end=email.rfind('@') #final start=email.find("@") if(count!=1 or count2<1 or end==(len(email)-1) or start==0): print("Wrong email address") else: print("correct email address")
true
5fc28ab298c14b482825b23bb6320ca32e50b514
sudiptasharif/python
/python_crash_course/chapter9/fraction.py
1,763
4.4375
4
class Fraction(object): """ A number represented as a fraction """ def __init__(self, num, denom): """ :param num: integer numerator :param denom: integer denominator """ assert type(num) == int and type(denom) == int, "ints not used" self.num = num self.denom = denom def __str__(self): """ :return: Returns a string representation of self """ return str(self.num) + "/" + str(self.denom) def __add__(self, other): """ Adds two fractions :param other: other fraction :return: a new fraction representing the addition """ top = self.num * other.denom + self.denom * other.num bottom = self.denom * other.denom return Fraction(top, bottom) def __sub__(self, other): """ Subtracts two fractions :param other: other fraction :return: a new fraction representing the subtraction """ top = self.num * other.denom - self.denom * other.num bottom = self.denom * other.denom return Fraction(top, bottom) def __float__(self): """ returns the float value of the fraction :return: float value of fraction """ return self.num / self.denom def __mul__(self, other): """ multiplication of two fractions :param other: a Fraction object :return: a fraction that represents the multiplication """ top = self.num * other.num bottom = self.denom * other.denom return Fraction(top, bottom) a = Fraction(1, 4) print(a) b = Fraction(3, 4) print(b) c = a + b print(c) d = a - b print(d) print(float(c)) print(float(d))
true
253e80b1f9ae499d49eb0d79c34b821e0c8dfb6d
waditya/HackerRank_Linked_List
/09_Merge_Sorted_LinkList.py
2,952
4.28125
4
""" Merge two linked lists head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def MergeLists(headA, headB): #Flag flag = 1 #Counter counter = 0 #NodeCounters counterA = True counterB = True ##Pointer to the Heads nodeA = headA nodeB = headB if((headA != None) and (headB == None)): return(None) elif((headA == None) and (headB != None)): return(headB) elif((headA != None) and (headB == None)): return(headA) else: ctr = 1 principal_node = Node(None,None); node = principal_node currNodeA = nodeA currNodeB = nodeB while(counterA or counterB): if((currNodeA.data < currNodeB.data) and (counterA)): if(ctr == 1): temp = Node(currNodeA.data, None) principal_node.next = temp node = node.next ctr = ctr + 1 if(currNodeA.next != None): currNodeA = currNodeA.next else: counterA = False else: temp = Node(currNodeA.data, None) node.next = temp node = node.next if(currNodeA.next != None): currNodeA = currNodeA.next else: counterA = False else: if(ctr == 1): temp = Node(currNodeB.data, None) principal_node.next = temp node = node.next ctr = ctr + 1 if(currNodeB.next != None): currNodeB= currNodeB.next else: counterB = False currNodeB.data = currNodeA.data + 1 else: temp = Node(currNodeB.data, None) node.next = temp node = node.next if(currNodeB.next != None): currNodeB= currNodeB.next else: counterB = False currNodeB.data = currNodeA.data + 1 return(principal_node.next)
true
6647f2a03e8d08ca8807c5dad2c2a0694d264713
SethGoss/notes1
/notes1.py
363
4.28125
4
# this is a comment, use them vary often print(4 + 6) # addition print(-4 -5) #subtraction print(6 * 3) #multiplication print(8 / 3) #division print(3 ** 3) #exponents - 3 to the 3rd power print(10 % 3) #modulo gives the remainder print(15%5) print(9%4) # to make variable, think of a name name = input("What is your name?: ") print("hello "+ name)
true