blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1f3b7f46287e477c08c75ad540c4610cb1ba8799
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_03_functions/exponentiation.py
296
4.25
4
def power(a, n): if n < 0: a = 1 / a n = -n return power(a, n) elif n > 0: return a * power(a, n - 1) else: return 1 print("Calculates a^n (a to the power of n).") a = float(input("Give a: ")) n = int(input("Give n: ")) print(power(a, n))
false
15720a0a5e835375b857d2efd3f58b305c0d162f
jedzej/tietopythontraining-basic
/students/sendecki_andrzej/lesson_01_basics/hello_harry.py
262
4.53125
5
# lesson_01_basics # Hello, Harry! # # Statement # Write a program that greets the user by printing the word "Hello", # a comma, the name of the user and an exclamation mark after it. print("Enter your name:") my_name = input() print("Hello, " + my_name + "!")
true
782275fee4250e4a33a7ec8dc3cb46c9074976d5
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_01_basic/car_route.py
404
4.125
4
# Problem «Car route» (Easy) # Statement # A car can cover distance of N kilometers per day. # How many days will it take to cover a route of length M kilometers? The program gets two numbers: N and M. import math print('Please input km/day:') speed = int(input()) print('Please input length:') length = int(input()) print('Distance can be travelled in: ' + str(math.ceil(length / speed)) + ' days')
true
9ad0674a05315b989d111ffec5557c847582c540
jedzej/tietopythontraining-basic
/students/myszko_pawel/lesson_02_flow_control/14_The number of zeros.py
405
4.125
4
# Given N numbers: the first number in the input is N, after that N integers are given. # Count the number of zeros among the given integers and print it. # You need to count the number of numbers that are equal to zero, not the number of zero digits. # Read an integer: N = int(input()) # Print a value: zeroes = 0 for i in range(N): a = int(input()) if a == 0: zeroes += 1 print(zeroes)
true
878f0faf7a7ab7caa19c504133b058008e02645b
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_03_functions/badly_organized_calculator.py
1,316
4.15625
4
# functions def help(): """help """ print("a - add") print("s - subtract") print("m - multiply") print("d - divide") print("p - power") print("h,? - help") print("q - QUIT") def inputs(message): """data input message : str """ print(message) var_1 = int(input("Input 1st operand: ")) var_2 = int(input("Input 2nd operand: ")) print("Result:") return var_1, var_2 def add(): var_1, var_2 = inputs("ADD") print(var_1 + var_2) def subtract(): var_1, var_2 = inputs("SUBTRACT") print(var_1 - var_2) def multiply(): var_1, var_2 = inputs("MULTIPLY") print(var_1 * var_2) def divide(): var_1, var_2 = inputs("DIVIDE") print(var_1 / var_2) def power(): var_1, var_2 = inputs("POWER") print(var_1 ** var_2) # program print("Welcome to well organized calculator:") help() while True: print("Enter option:") option = input() if option == "a": add() elif option == "s": subtract() elif option == "m": multiply() elif option == "d": divide() elif option == "p": power() elif option in {"h", "?"}: help() elif option == "q": print("GOOD BYE") break else: print("No such option. Repeat:")
false
c8c1963bad864b383a77727973232b4e3b7c392b
danserboi/Marketplace
/tema/consumer.py
2,594
4.34375
4
""" This module represents the Consumer. Computer Systems Architecture Course Assignment 1 March 2021 """ import time from threading import Thread class Consumer(Thread): """ Class that represents a consumer. """ def __init__(self, carts, marketplace, retry_wait_time, **kwargs): """ Constructor. :type carts: List :param carts: a list of add and remove operations :type marketplace: Marketplace :param marketplace: a reference to the marketplace :type retry_wait_time: Time :param retry_wait_time: the number of seconds that a producer must wait until the Marketplace becomes available :type kwargs: a dict with the following format: {'name': <CONSUMER_ID>}. :param kwargs: other arguments that are passed to the Thread's __init__() """ Thread.__init__(self, **kwargs) self.carts = carts self.marketplace = marketplace self.retry_wait_time = retry_wait_time def run(self): """ Here we make orders for every cart of the consumer. """ # we parse every cart of the consumer for cart in self.carts: # we create a new cart for the consumer cart_id = self.marketplace.new_cart() # we parse every action that is done with the current cart for action in cart: # we want to produce the action in the specified number of times curr_no = action["quantity"] while curr_no > 0: # we verify the type of action if action["type"] == "add": is_added = self.marketplace.add_to_cart(cart_id, action["product"]) # if the product is successfully added to the cart, # we decrease the current number if is_added: curr_no -= 1 # else, we should wait and try again after else: time.sleep(self.retry_wait_time) # the action of removing is always successful # so we don't have to verify anything, # just decrease the current number after elif action["type"] == "remove": self.marketplace.remove_from_cart(cart_id, action["product"]) curr_no -= 1 # now we can place the order for this cart self.marketplace.place_order(cart_id)
true
35d8e0f70cfd155ab513ed9b405903a140164f19
rkp872/Python
/6)Functions/TypesOfArgument.py
2,926
4.65625
5
# Information can be passed into functions as arguments. # Arguments are specified after the function name, inside # the parentheses. #In python we have different types of agruments: # 1 : Position Argument # 2 : Keyword Argument # 3 : Default Argument # 4 : Variable length Argument # 5 : Keyworded Variable length Argument #------------------------------- # 1 : Position Argument # while calling the function ,order of passing the values is important #because the values will be binded with the formal argument in the same order #this types of argument is called as positional argument def person(name,age): print("Name is: ",name) print("Age is : ",age) name="Rohit" age=23 person(name,age) #person(age,name) This is not the correct way because 23 will go to name and rohit will go to age in the function #--------------------------------- # 2 : Keyword Argument #Many a times the function is defined by some other people and is used by some other people. #So the caller doesn't know the formal agrument order #In this case keyword argument can be used where we use the keyword with the # arguments while caling it def person(name,age): print("Name is: ",name) print("Age is : ",age) name="Rohit" age=23 person(age=age,name=name) #-------------------------------------------------- # 3 : Default Argument #Sometimes caller doesn't provide all the values for the formal argument #In this case while defining the funtion only we can provide default value for the argument whose value will not be passed by caller #This type of argument is called default argument def person(name,age=18): print("Name is: ",name) print("Age is : ",age) name="Rohit" person(name) #------------------------------------------ # 4 : Variable length Argument #sometimes caller may paas more number of arguments than the number of formal agruments #In that case the formal arguments must be of variable length # we can create variable length argument by putting * sign before the name of last argument def sum(a,*b): sum=a for i in b: #In the funtion all the passed value will be stored in a tuple with name b,So for accessing it we have to use for loop here sum=sum+i print("Sum is ",sum) sum(10,20) sum(10,20,30) sum(10,20,30,40,50,60,40) #----------------------------------------------------------- # 5 : Keyworded Variable length Argument # Foe having meaningful use of the variable length arguments we can also # specify a keyword with them while passing ,which denotes the what data # it is storing .Such type of arguments are called as #Keyworded Variable length Argument def person(name,**data): print(name) for i,j in data.items(): #Foe accessing one data at a time we use item() function print(i,j) person("Rohit",age=25,city="Ranchi",Mobile=9123114708)
true
e87320897e3f5dfaf10564b9f79b6487649dfcc4
rkp872/Python
/3)Conditional/SquareCheck.py
272
4.34375
4
#Take values of length and breadth of a rectangle from user and check if it is square or not. len=int(input("Enter length : ")) bre=int(input("Enter breadth : ")) if(len==bre): print("Given rectangle is square") else: print("Given rectangle is not a square")
true
ac0091ebda2a4599eac69b2467b398a984942c5f
rkp872/Python
/1)Basics/Basic.py
444
4.125
4
print("Hello World")#printing Hello World #we dont need to declare variable type as python is dyamically typed language x=10 #aiigning value to any variable y=20 print(x) #basic arithmetic operator z=x+y print(z) z=x-y print(z) z=x*y print(z) z=x/y # will give float result print(z) z=x//y # will give int result print(z) z=x**y # x is multiplied by x ,y number of times print(z)
false
1af02fa80c544f52c1f2e4a2f0c767c96b14a4b6
rkp872/Python
/2)Data Types/Set.py
726
4.21875
4
# Set: Set are the collection of hetrogeneous elements enclosed within {} # Sets does not allows duplicates and insertion order is not preserved #Elements are inserted according to the order of their hash value set1={10,20,20,30,50,40,60} print(set1) print(type(set1)) set1.add(36) print(set1) set2=set1.copy() print(set2) set2.remove(20) set2.remove(60) print(set2) print(set1.difference(set2)) #returns elements which are present in set1 but not in set2 print(set2.difference(set1)) #returns elements which are present in set2 but not in set1 print(set1.intersection(set2)) #Returns intersection of two sets print(set1.union(set2)) #Returns Union of two sets print(len(set1))
true
d85c3e867c8d10f6b71231e9c581d0f4274ec9c3
Randy760/Dice-rolling-sim
/Dicerollingsimulator.py
694
4.1875
4
import random # making a dice rolling simulator youranswer = ' ' print('Would you like to roll the dice?') #asks if they want to roll the dice while True: youranswer = input() if youranswer == 'yes': diceroll = random.randint(1,6) #picks a random number between 1 and 6 print(diceroll) #prints the random diceroll print('Would you like to roll the dice, again?') #asks if they want to roll again elif youranswer != 'yes': #if their answer is not 'yes' , then the loop is broken break print('Thanks for playing!') # prints this once the program reaches the end
true
7e52cf50f97a380fd642400ed77ac5c0e6e9706a
LukeBrazil/fs-imm-2021
/python_week_1/day1/fizzBuzz.py
324
4.15625
4
number = int(input('Please enter a number: ')) def fizzBuzz(number): if number % 3 == 0 and number % 5 == 0: print('FizzBuzz') elif number % 3 == 0: print('Fizz') elif number % 5 == 0: print('Buzz') else: print(f'Number does not fit requirements: {number}') fizzBuzz(number)
false
d385bb61ec1eaf766666c24f71f472a4138cf98e
mahadev-sharma/Python
/biggest among three.py
490
4.125
4
#find the biggest numbr among three numbers def biggestGuy (num1,num2,num3): if ((num1 > num2) and (num1 > num3)) : print('number 1 is the biggest number among them') elif ((num2 > num1) and (num2 > num3)) : print('number 2 is the biggest number among them') elif ((num3 > num2) and (num3 > num1)) : print('number 3 is the biggest number among them') else: print('any two or all three numbers are equal') biggestGuy(1,1,1)
false
38611f668686c832c7d1fe7e3c671d54d2f9ecf1
FdelMazo/7540rw-Algo1
/Ejercicios de guia/ej34.py
1,388
4.15625
4
import math def calcular_norma(x,y): """Calcula la norma de un punto""" return math.sqrt(x**2+y**2) def restar_puntos(punto1,punto2): """Resta dos puntos""" x1 = punto1[0] y1 = punto1[1] x2 = punto2[0] y2 = punto2[1] return x2-x1, y2-y1 def distancia(punto1, punto2): """Calcula la distancia entre dos puntos""" x,y = restar_puntos(punto1,punto2) return calcular_norma(x,y) def pedir_punto(): """Pide un punto en el plano xy a un usuario""" punto = input("Dar un punto en el plano xy separados por una coma: ") punto = punto.split(", ") x = int(punto[0]) y = int(punto[1]) return x, y def semiperimetro(a,b,c): """Calcula el semiperimetro de un triangulo de 3 lados""" p = a + b + c return p/2 def area(a,b,c,p): """Calcula el area de un triangulo""" raiz = p*(p-a)*(p-b)*(p-c) return math.sqrt(raiz) def main(): """Funcion principal para calcular el area de un triangulo""" punto1 = pedir_punto() punto2 = pedir_punto() punto3 = pedir_punto() lado1 = distancia(punto1, punto2) lado2 = distancia(punto2, punto3) lado3 = distancia(punto1, punto3) semiperimetro1 = semiperimetro(lado1,lado2,lado3) area1 = area(lado1,lado2,lado3,semiperimetro1) print ("El area es {} ".format(area1)) main()
false
f6b4bb1aff6e2c8a495f04ae256d68d252e3babf
Rhalith/gaih-students-repo-example
/Homeworks/Hw2-day1.py
248
4.21875
4
n = int(input("Please enter an single digit integer: ")) while (n > 9 or n < 0): n = int(input("Your number is not a single digit. Please enter an single digit integer: ")) for num in range(n+1): if num % 2 == 0: print(num)
false
3591366d9968bf42380c2f40c55f8db2ae34052a
keshav1245/Learn-Python-The-Hard-Way
/exercise11/ex11.py
729
4.40625
4
print "How old are you ?", age = raw_input() print "How tall are you ?", height = raw_input() print "How much do you weight ? ", weight = raw_input() #raw_input([prompt]) #If the prompt argument is present, it is written to standard output without a trailing newline. The #function then reads a line from input, converts it to a string (stripping a trailing newline), and #returns that. When EOF is read, EOFError is raised. Example: name = raw_input("What is your name? >> ") print "So, you're %r old, %r tall and your weight is %r."%(age,height,weight) print ("Your name is : %s"% name + "\n")*10 #getting a number marks = float(raw_input("Enter your CGPA : ")) print "CGPA is : ",marks print ("%s \n %r")%(name,name)
true
1f39795b7719af506164b48da51370bd90c397ca
a-tran95/PasswordGenerator
/app.py
2,059
4.125
4
import random letterbank_lower = 'abcdefghijklmnopqrstuvwxyz' letterbank_upper = letterbank_lower.upper() numberbank = '1234567890' symbolbank = '!@#$%^&*()-=_+`~{}|[];:<>,./?' thebank = [letterbank_lower,letterbank_upper,numberbank,symbolbank] password = [] def charcheck(check): try: if check.upper() == 'Y': check = 1 elif check.upper() == 'N': check = 0 else: print('You have entered an invalid input') except ValueError: print('You have entered an invalid input') return check while True: is_lower = input('Password contains lower case characters? Y/N\n') is_lower = charcheck(is_lower) if is_lower == 1 or is_lower == 0: break while True: is_upper = input('Password contains upper case characters? Y/N\n') is_upper = charcheck(is_upper) if is_upper == 1 or is_upper == 0: break while True: is_numbers = input('Password contains numbers? Y/N\n') is_numbers = charcheck(is_numbers) if is_numbers == 1 or is_numbers== 0: break while True: is_symbols = input('Password contains symbols? Y/N\n') is_symbols = charcheck(is_symbols) if is_symbols== 1 or is_symbols == 0: break if is_lower == False: thebank.remove(letterbank_lower) if is_upper == False: thebank.remove(letterbank_upper) if is_numbers == False: thebank.remove(numberbank) if is_symbols == False: thebank.remove(symbolbank) if len(thebank) == 0: print('You have no characters to choose from. The program will now close.') exit() try: passlength = int(input('Finally, please enter the desired length of the password. Invalid inputs will automatically be 12.\n')) except ValueError: print('Your value is invalid. Your password length is assigned as 12 characters.') passlength = 12 for p in range(0,passlength): password.append(random.choice(random.choice(thebank))) print(f'Your password is {"".join(password)}')
false
2f1bd009c20a51bab241ad3c31528b0f0664ed93
rohan-khurana/MyProgs-1
/SockMerchantHR.py
1,687
4.625
5
""" John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . Function Description Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. sockMerchant has the following parameter(s): n: the number of socks in the pile ar: the colors of each sock Input Format The first line contains an integer , the number of socks represented in . The second line contains space-separated integers describing the colors of the socks in the pile. Constraints where Output Format Return the total number of matching pairs of socks that John can sell. Sample Input 9 10 20 20 10 10 30 50 10 20 Sample Output 3 Explanation sock.png John can match three pairs of socks. """ # SOLUTION #!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the sockMerchant function below. def sockMerchant(n, ar): Sum = 0 for value in Counter(ar).values(): Sum += value//2; return Sum if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) ar = list(map(int, input().rstrip().split())) result = sockMerchant(n, ar) fptr.write(str(result) + '\n') fptr.close()
true
0a47ead1f61b1ab1ffe627e55a08f31ebed03c5e
rohan-khurana/MyProgs-1
/basic8.py
225
4.15625
4
num = input("enter a number to be checked for prime number") num = int(num) i = num j=1 c=0 while j<=i : if i%j==0 : c+=1 j+=1 if c==2 : print("entered number is prime") else : print("not prime")
false
9f6ee9426e3bd6c017e82c317f0800236cd2dc13
rohan-khurana/MyProgs-1
/TestingHR.py
2,987
4.28125
4
""" This problem is all about unit testing. Your company needs a function that meets the following requirements: For a given array of integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, the returned index should be the smallest one. If an empty array is passed to the function, it should raise an Exception. Note: The arrays are indexed from . A colleague has written that function, and your task is to design separated unit tests, testing if the function behaves correctly. The implementation in Python is listed below (Implementations in other languages can be found in the code template): def minimum_index(seq): if len(seq) == 0: raise ValueError("Cannot get the minimum value index from an empty sequence") min_idx = 0 for i in range(1, len(seq)): if a[i] < a[min_idx]: min_idx = i return min_idx Another co-worker has prepared functions that will perform the testing and validate returned results with expectations. Your task is to implement classes that will produce test data and the expected results for the testing functions. More specifically: function get_array() in TestDataEmptyArray class and functions get_array() and get_expected_result() in classes TestDataUniqueValues and TestDataExactlyTwoDifferentMinimums following the below specifications: get_array() method in class TestDataEmptyArray has to return an empty array. get_array() method in class TestDataUniqueValues has to return an array of size at least 2 with all unique elements, while method get_expected_result() of this class has to return the expected minimum value index for this array. get_array() method in class TestDataExactlyTwoDifferentMinimums has to return an array where there are exactly two different minimum values, while method get_expected_result() of this class has to return the expected minimum value index for this array. Take a look at the code template to see the exact implementation of functions that your colleagues already implemented. """ # SOLUTION def minimum_index(seq): if len(seq) == 0: raise ValueError("Cannot get the minimum value index from an empty sequence") min_idx = 0 for i in range(1, len(seq)): if seq[i] < seq[min_idx]: min_idx = i return min_idx class TestDataEmptyArray(object): @staticmethod def get_array(): # complete this function return list() class TestDataUniqueValues(object): @staticmethod def get_array(): # complete this function return [0,1,-1] @staticmethod def get_expected_result(): # complete this function return 2 class TestDataExactlyTwoDifferentMinimums(object): @staticmethod def get_array(): # complete this function return [0,1,-1,-1] @staticmethod def get_expected_result(): # complete this function return 2
true
8e07f7fdba8ee6adae646070615b9b8d756462bc
rohan-khurana/MyProgs-1
/TheXORProblemHR.py
1,865
4.25
4
""" Given an integer, your task is to find another integer such that their bitwise XOR is maximum. More specifically, given the binary representation of an integer of length , your task is to find another binary number of length with at most set bits such that their bitwise XOR is maximum. For example, let's say that = "0100" and = 1. The maximum possible XOR can be obtained with = "1000", where XOR = "1100". Input Format The first line of input contains an integer, , the number of tests. The first line of each test contains a binary string representing . The second line of each test contains an integer, , denoting the maximum number of set bits in . Constraints Output Format Print exactly lines. In the of them, print the string denoting in the test case. Sample Input 0 2 10010 5 01010 1 Sample Output 0 01101 10000 Explanation 0 For the first case, (x xor y) gives 11111 which is the maximum possible number that can be obtained. In the second case, (x xor y) gives 11010. Note that any other y would given a lesser xor sum. """ #SOLUTION #!/bin/python3 import math import os import random import re import sys # # Complete the 'maxXorValue' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING x # 2. INTEGER k # def maxXorValue(x, k): # Write your code here x = list(str(x)) value = [] for i in x : if i == '0' and k >0: value.append('1') k -= 1 else : value.append('0') value = ''.join(value) return value if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): s = input() k = int(input().strip()) y = maxXorValue(s, k) fptr.write(y + '\n') fptr.close()
true
f7e30fb9549c6e8c88792ac40d5c59ef0a86edf6
tonyvillegas91/python-deployment-example
/Python Statements/list_comprehension2.py
205
4.34375
4
# Use a List Comprehension to create a list of the first letters of every word in the string below: st = 'Create a list of the first letters of every word in this string' [word[0] for word in st.split()]
true
420dc0c8d97e56b4fb94dd5ea72f6bff4a8cec0b
jdstikman/PythonSessions
/AcuteObtuseAndRight.py
226
4.125
4
a = input("Enter number here") a = int(a) if a < 90: print("number is acute") elif a == 90: print("right angle") elif a > 90 and a < 180: print("obtuce") else: print("i have no idea what you are talking about")
false
79aa8a94a6c3953ea852f3a087f1f0a89dbd0af7
hamanovich/py-100days
/01-03-datetimes/program2.py
1,197
4.25
4
from datetime import datetime THIS_YEAR = 2018 def main(): years_ago('8 Aug, 2015') convert_eu_to_us_date('11/03/2002') def years_ago(date): """Receives a date string of 'DD MMM, YYYY', for example: 8 Aug, 2015 Convert this date str to a datetime object (use strptime). Then extract the year from the obtained datetime object and subtract it from the THIS_YEAR constant above, returning the int difference. So in this example you would get: 2018 - 2015 = 3""" date_format = '%d %b, %Y' return THIS_YEAR - datetime.strptime(date, date_format).year def convert_eu_to_us_date(date): """Receives a date string in European format of dd/mm/yyyy, e.g. 11/03/2002 Convert it to an American date: mm/dd/yyyy (in this case 03/11/2002). To enforce the use of datetime's strptime / strftime (over slicing) the tests check if a ValueError is raised for invalid day/month/year ranges (no need to code this, datetime does this out of the box)""" date_format_EU = '%d/%m/%Y' date_format_USA = '%m/%d/%Y' return datetime.strptime(date, date_format_EU).strftime(date_format_USA) if __name__ == "__main__": main()
true
d1db24e49d5698c3d9f2b6db4794fa94aebb3e5f
inest-us/python
/algorithms/c1/tuple.py
642
4.15625
4
# Tuples are very similar to lists in that they are heterogeneous sequences of data. # The difference is that a tuple is immutable, like a string. # A tuple cannot be changed. # Tuples are written as comma-delimited values enclosed in parentheses. my_tuple = (2,True,4.96) print(my_tuple) # (2, True, 4.96) print(len(my_tuple)) # 3 print(my_tuple[0]) # 2 print(my_tuple * 3) # (2, True, 4.96, 2, True, 4.96, 2, True, 4.96) print(my_tuple[0:2]) # (2, True) # my_tuple[1]=False # Traceback (most recent call last): # File "<pyshell#137>", line 1, in <module> # my_tuple[1]=False # TypeError: 'tuple' object does not support item assignment
true
90c309b7049aabd853e1520494df51296dc9a0f6
inest-us/python
/algorithms/c1/dictionary.py
1,360
4.65625
5
capitals = {'Iowa':'DesMoines','Wisconsin':'Madison'} print(capitals) # {'Wisconsin': 'Madison', 'Iowa': 'DesMoines'} # We can manipulate a dictionary by accessing a value via its key or by adding another key-value pair. # The syntax for access looks much like a sequence access # except that instead of using the index of the item we use the key value. To add a new value is similar. print(capitals['Iowa']) # DesMoines capitals['Utah']='SaltLakeCity' print(capitals) # {'Iowa': 'DesMoines', 'Wisconsin': 'Madison', 'Utah': 'SaltLakeCity'} capitals['California']='Sacramento' print(len(capitals)) # 4 for k in capitals: print(capitals[k], " is the capital of ", k) phone_ext={'david':1410, 'brad':1137} print(phone_ext) # {'brad': 1137, 'david': 1410} print(phone_ext.keys()) # dict_keys(['brad', 'david']) print(list(phone_ext.keys())) # ['brad', 'david'] print("brad" in phone_ext) # True print(1137 in phone_ext) # False : 1137 is not a key in phone_ext print(phone_ext.values()) # dict_values([1137, 1410]) print(list(phone_ext.values())) # [1137, 1410] print(phone_ext.items()) # dict_items([('brad', 1137), ('david', 1410)]) print(list(phone_ext.items())) # [('brad', 1137), ('david', 1410)] print(phone_ext.get("kent")) # None print(phone_ext.get("kent","NO ENTRY")) # 'NO ENTRY' del phone_ext["david"] print(phone_ext) # {'brad': 1137}
false
42d484424e2bb30b0bae4e3ea9a9f3cb668d8f8c
jsburckhardt/pythw
/ex3.py
693
4.15625
4
# details print("I will now count my chickens:") # counts hens print("Hens", float(25 + 30 / 6)) # counts roosters print("Roosters", float(100 - 25 *3 % 4)) # inform print("Now I will count the eggs:") # eggs print(float(3 + 2 + 1 + - 5 + 4 % 2 - 1 / 4 + 6)) # question 5 < -2 print("Is it true that 3 + 2 < 5 - 7?") # validates 5<-2 print(3 + 2 < 5 - 7) # 3 + 2 print("What is 3 + 2?", float(3 + 2)) # 5-7 print("What is 5 - 7?", float(5 - 7)) # affirms print("Oh, that's why it's False") # informs print("How about some more.") # greater than print("Is it greater?", 5 > -2) # greater or equal print("Is it greater or equal?", 5 >= -2) # less or equal print("Is it less or equal?", 5 <= -2)
true
0081ea28bee4c8b24910c6a3a8b3d559431efde5
lima-BEAN/python-workbook
/programming-exercises/ch7/larger_than_n.py
1,565
4.40625
4
# Larger Than n # In a program, write a function that accepts two arguments: # a list and a number, n. Assume that the list contains numbers. # The function should display all of the numbers in the list that # are greater than the number n. import random def main(): numbers = Numbers() user_num = UserNum() Compare(numbers, user_num) def Numbers(): numbers = [] for x in range(20): number = random.randint(1, 100) numbers.append(number) return numbers def UserNum(): number = float(input('Choose between 1-100 to compare to a list of 20 random numbers. ')) while number <= 0 or number > 100: number = float(input('Please choose a number between 1-100 ')) return number def Compare(numbers, user_num): greater_than = [] smaller_than = [] equal_to = [] count = 0 for num in numbers: if num < user_num: smaller_than.append(num) elif num > user_num: greater_than.append(num) else: equal_to.append(num) print() print('====== Random Numbers Smaller Than Your Number =====') for num in smaller_than: count += 1 print(str(count) + '. ' + str(num)) print() print('====== Random Numbers Greater Than Your Number =====') for num in greater_than: count += 1 print(str(count) + '. ' + str(num)) print() print('====== Random Numbers Equal To Your Number =====') for num in equal_to: count += 1 print(str(count) + '. ' + str(num)) main()
true
43dc28165ec22f719d9e594091c82366cc574384
lima-BEAN/python-workbook
/programming-exercises/ch2/distance-traveled.py
618
4.34375
4
## Assuming there are no accidents or delays, the distance that a car ## travels down the interstate can be calculated with the following formula: ## Distance = Speed * Time ## A car is traveling at 70mph. Write a program that displays the following: ## The distance a car will travel in 6 hours ## The distance a car will travel in 10 hours ## The distance a car will travel in 15 hours speed = 70 time1 = 6 time2 = 10 time3 = 15 distance1 = speed * time1 distance2 = speed * time2 distance3 = speed * time3 print("Distance 1 is", distance1, "\nDistance 2 is", distance2, "\nDistance 3 is", distance3)
true
a913e26be57a7dcad82df5ddf127b85933c4c0c0
lima-BEAN/python-workbook
/programming-exercises/ch5/kinetic_energy.py
983
4.53125
5
# Kinetic Energy # In physics, an object that is in motion is said to have kinetic energy. # The following formula can be used to determine a moving object's kinetic # energy: KE = 1/2 mv**2 # KE = Kinetic Energy # m = object's mass (kg) # v = velocity (m/s) # Write a program that asks the user to enter values for mass and velocity # and then calls kinetic_energy function to get obj KE def main(): mass = Mass() velocity = Velocity() kinetic_energy = KineticEnergy(mass, velocity) Results(mass, velocity, kinetic_energy) def Mass(): m = int(input('How much does the object weigh in kilograms? ')) return m def Velocity(): v = int(input('What\'s the vehicle\'s velocity in meters/s? ')) return v def KineticEnergy(m, v): ke = (1/2) * m * (v**2) return ke def Results(m, v, ke): print() print('================== Results ========================') print('Mass:', m, '\tVelocity:', v, '\tKinetic Energy:', ke) main()
true
44ecf7731cf113a646f9fbfb9358a09f5dead62a
lima-BEAN/python-workbook
/programming-exercises/ch8/date_printer.py
933
4.375
4
# Date Printer # Write a program that reads a string from the user containing a date in # the form mm/dd/yyyy. It should print the date in the form # March 12, 2014 def main(): user_date = UserDate() date_form = DateForm(user_date) Results(date_form) def UserDate(): date = input('Enter a date in the format (mm/dd/yyyy): ') return date def DateForm(date): months = [ 'January', 'Feburary', 'March', 'April', \ 'May', 'June', 'July', 'August',\ 'September', 'October', 'November', 'December' ] f_date = '' split_date = date.split('/') m_date = '' d_date = split_date[1] y_date = split_date[2] for x in range(len(months)): if int(split_date[0]) == x+1: m_date = months[x] f_date = m_date + ' ' + d_date + ', ' + y_date return f_date def Results(date): print() print('Your formatted date is:', date) main()
true
e8404b90ca40907cfca6018ce0c4bebf8752caec
lima-BEAN/python-workbook
/programming-exercises/ch2/ingredient-adjuster.py
832
4.40625
4
## A cookie recipe calls for the following ingredients: ## - 1.5 cups of sugar ## - 1 cup of butter ## - 2.75 cups of flour ## The recipe produces 48 cookies with this amount of the ingredients. ## Write a program that asks the user how many cookies he or she wants to ## make, and then displays the number of cups of each ingredient needed ## for the specified number of cookies. cookies = int(input("How many cookies do you want? ")) # 0.03215 cups of sugar per cookie sugar = cookies * 0.03125 # 0.02083 cups of butter per cookie butter = cookies * 0.02083 # 0.05729 cups of flour per cookie flour = cookies * 0.05729 print("For", cookies, "cookies, you need:", "\n\t", format(sugar, ".2f"), "cups of sugar", "\n\t", format(butter, ".2f"), "cups of butter", "\n\t", format(flour, ".2f"), "cups of flour",
true
cbae1470e46184c8a3b830ff5ad9076fe0f1864f
lima-BEAN/python-workbook
/programming-exercises/ch4/population.py
720
4.46875
4
# Write a program that predicts the approximate size of a population of organisms # The application should use text boxes to allow the user to enter the starting # number of organisms, the average daily population increase (as percentage), # and the number of days the organisms will be left to multiply. number_organisms = int(input("Starting number of organisms: ")) percent_increase = int(input('What is the daily increase (as percenetage): ')) days_to_multiple = int(input('How many days to multiple: ')) print('Day\tPopulation') for day in range(1, (days_to_multiple+1)): if day > 1: number_organisms += (number_organisms * percent_increase)/100 print(day, '\t', format(number_organisms, '.1f'))
true
27eda59c433dd226459b8966720505f2c78d0cd1
lima-BEAN/python-workbook
/programming-exercises/ch10/Information/my_info.py
794
4.46875
4
# Also, write a program that creates three instances of the class. One # instance should hold your information, and the other two should hold # your friends' or family members' information. import information def main(): my_info = information.Information('LimaBean', '123 Beanstalk St.', '12 pods', '1-800-LimaBean') fam1_info = information.Information('GreenBean', '456 Green St.', '3 beans', '555-My-Greens') fam2_info = information.Information('BlackBean', '987 Refried St.', '7 black beans', '222-BLACK-REFRIED') print('My Info:', my_info.get_name()) print('Fam1 Info:', fam1_info.get_name()) print('Fam2 Info:', fam2_info.get_name()) main()
true
8d62cbef5cbe028c9a8d83ddd18c5e52106d9c6b
lima-BEAN/python-workbook
/programming-exercises/ch3/roman-numerals.py
982
4.34375
4
# Write a program that prompts the user to enter a number within the range of 1 # through 10. The program should display the Roman numeral version of that # number. If the number is outside the range of 1 through 10, # the program should display an error message. number = int(input("What number do you want to convert to Roman Numeral? (1-10) ")) if number == 1: print(number, "is converted to I") elif number == 2: print(number, "is converted to II") elif number == 3: print(number, "is converted to III") elif number == 4: print(number, "is converted to IV") elif number == 5: print(number, "is converted to V") elif number == 6: print(number, "is converted to VI") elif number == 7: print(number, "is converted to VII") elif number == 8: print(number, "is converted to VIII") elif number == 9: print(number, "is converted to IX") elif number == 10: print(number, "is converted to X") else: print("Choose a number between 1 and 10")
true
3c683a28f22e656365df3d5a555d2f3128fa1bb8
lima-BEAN/python-workbook
/programming-exercises/ch8/initials.py
1,126
4.25
4
# Write a program that gets a string containing a person's first, middle # and last names, and then display their first, middle and last initials. # For example, John William Smith => J. W. S. def main(): name = Name() initials = Initials(name) Results(initials) def Name(): name = input('What is your full name? ') return name def Initials(name): initial = name.split(' ') initials = [] if len(initial) == 3: f_initial = initial[0][:1] + '.' m_initial = initial[1][:1] + '.' l_initial = initial[2][:1] + '.' initials.append(f_initial.title()) initials.append(m_initial.title()) initials.append(l_initial.title()) elif len(initial) == 2: f_initial = initial[0][:1] + '.' l_initial = initial[1][:1] + '.' initials.append(f_initial.title()) initials.append(l_initial.title()) return initials def Results(initials): full_initials = '' for x in range(len(initials)): full_initials += initials[x] full_initials += ' ' print('Your initials are:', full_initials) main()
false
f9500fd6cfdd6d846ed4b6fa2b034bd681d3d637
lima-BEAN/python-workbook
/algorithm-workbench/ch2/favorite-color.py
220
4.21875
4
## Write Python code that prompts the user to enter his/her favorite ## color and assigns the user's input to a variale named color color = input("What is your favorite color? ") print("Your favorite color is", color)
true
54b6e4930811ab19c5c64d37afc05fb0a8d69270
lima-BEAN/python-workbook
/programming-exercises/ch10/Retail/item_in_register.py
1,023
4.25
4
# Demonstrate the CashRegister class in a program that allows the user to # select several items for purchase. When the user is ready to check # out, the program should display a list of all the items he/she has # selected for a purchase, as well as total price. import retail_item import cash_register def main(): add = input('Would you like to add an item to your cart? (y/n) ') while add == 'Y' or add == 'y': AddItem() add = input('Would you like to add another item? (y/n) ') Total() Show() def AddItem(): desc = input('What item would you like? ') inv = input('How many ' + desc + ' would you like? ') price = input('What is the price of that item? ') new_item = retail_item.RetailItem(desc, inv, price) cash_register.CashRegister.purchase_item(new_item) def Total(): print('The total amount for the items is:', cash_register.CashRegister.get_total()) def Show(): print('Items purchased:') cash_register.CashRegister.show_items() main()
true
14abd73ae4d52d04bfa9c06e700d9191d194f6b3
lima-BEAN/python-workbook
/programming-exercises/ch5/sales_tax_program_refactor.py
1,702
4.1875
4
# Program exercise #6 in Chapter 2 was a Sales Tax Program. # Redesign solution so subtasks are in functions. ## purchase_amount = int(input("What is the purchasing amount? ")) ## state_tax = 0.05 ## county_tax = 0.025 ## total_tax = state_tax + county_tax ## total_sale = format(purchase_amount + (purchase_amount * total_tax), '.2f') ## ## print("The purchase amount for the item is $" + str(purchase_amount), ## "\n\tState tax:", format((state_tax * purchase_amount), '.2f'), ## "\n\tCounty tax:", format((county_tax * purchase_amount), '.2f'), ## "\n\tTotal tax:", format((total_tax * purchase_amount), '.2f'), ## "\n\tTotal sale amount is $" + str(total_sale)) COUNTY_TAX = 0.025 STATE_TAX = 0.05 def main(): purchase_amount = float(input('What is the purchasing amount? ')) county_tax = CountyTax(purchase_amount) state_tax = StateTax(purchase_amount) total_tax = TotalTax(county_tax, state_tax) total_sale = TotalSale(purchase_amount, total_tax) PrintBill(purchase_amount, county_tax, state_tax, total_tax, total_sale) def CountyTax(p_amount): return p_amount * COUNTY_TAX def StateTax(p_amount): return p_amount * STATE_TAX def TotalTax(c_tax, s_tax): return c_tax + s_tax def TotalSale(p_amount, t_tax): return p_amount + t_tax def PrintBill(p_amount, c_tax, s_tax, t_tax, t_sale): print('============ Bill Summary ================') print("Purchase amount:", format(p_amount, '.2f'), "\nTotal tax:", '\t', format(t_tax, '.2f'), "\t\t=>","\tCounty tax:", format(c_tax, '.2f'), "+ State tax:", format(s_tax, '.2f'), "\nTotal sale:", '\t', format(t_sale, '.2f')) main()
true
3d9deda751cdfa233cdf0c711f3432be950980d3
tejastank/allmightyspiff.github.io
/CS/Day6/linkedList01.py
1,399
4.21875
4
""" @author Christopher Gallo Linked List Example """ from pprint import pprint as pp class Node(): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node def __str__(self): return str(self.data) class linked_list(): def __init__(self): self.head = None self.current = None self.tail = None def __str__(self): if self.head is None: return None start = self.head out = "%s" % (start) while start.next != None: start = start.next out += ", %s" % str(start) return out def __iter__(self): self.current = None return self def next(self): if self.head and not self.current: self.current = self.head return self.current elif self.current.next: self.current = self.current.next return self.current else: raise StopIteration def add_node(self, node): if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node if __name__ == "__main__": my_list = linked_list() my_list.add_node(Node('a')) my_list.add_node(Node('b')) my_list.add_node(Node(100)) # print(my_list) for l in my_list: print(l)
true
611d3db5bf36c987bb459ff19b7ab0a215cfec83
laurenwheat/ICS3U-Assignment-5B-Python
/lcm.py
753
4.25
4
#!/usr/bin/env python3 # Created by: Lauren Wheatley # Created on: May 2021 # This program displays the LCM of 2 numbers def main(): a = input("Please enter the first value: ") b = input("Please enter the second value: ") try: a_int = int(a) b_int = int(b) if (a_int > b_int): maximum = a_int else: maximum = b_int while(True): if(maximum % a_int == 0 and maximum % b_int == 0): print("LCM is {0}".format(maximum)) break maximum = maximum + 1 except Exception: print("That is not a number!!!!!!") finally: print("") print("Thanks for playing <3") if __name__ == "__main__": main()
true
722c9fef00cc8c68bda1a32eb5964413311f1a2d
smtorres/python-washu-2014
/Assignment01/school.py
1,042
4.21875
4
from collections import OrderedDict class School(): def __init__(self, school_name): self.school_name = school_name self.db = {} # Function that adds values and keys to a dictionary. Keys are school grades and each can take as value the name of a kid belonging to that grade. # It returns a dictionary with the name of the keys def add(self, name, grade): if grade in self.db: self.db[grade].add(name) else: self.db[grade] = {name} # Function that takes as input Grade and delivers the names of the kids that belong to that group. def grade(self, grade): if grade not in self.db.keys(): return None else: return self.db.get(grade) print self.db.keys # Function that sorts and converts the values of the dictionary from sets to tuples. def sort(self): new_dic = self.db for i in range(0, len(new_dic)): Key = new_dic.keys()[i] Value = new_dic.values()[i] Value = list(Value) Value = tuple(Value) new_dic[Key] = Value print new_dic.values return new_dic
true
8a199663c4dc2228104bbab583fd9ecaddcac34d
amitopu/ProblemSet-1
/NonConstructibleChange/nonConstructibleChange.py
1,728
4.40625
4
def nonConstructibleChangePrimary(coins): """ Takes an arrary of coin values and find the minimum change that can't be made by the coins available in the array. solution complexity : O(nlogn) time complexity and O(1) space complexity args: ----------- coins (array): an array contains available coin values. output: ----------- number (int) : represent the minimum amount of change that can't be made by the coins. """ # if the array is empty return 1 # if array has single element and greater than 1 return 1 n = len(coins) if n == 0 or (n == 1 and coins[0] > 1): return 1 #sort the list of coins coins.sort() # add adjacent elements successively # and check if there is a minimum change that can't be done sum = 0 for i in range(len(coins)-1): sum += coins[i] if coins[i+1] - sum >= 2: return sum + 1 return sum + coins[n-1] + 1 def nonConstructibleChangeBetter(coins): """ Takes an arrary of coin values and find the minimum change that can't be made by the coins available in the array. solution complexity : O(nlogn) time complexity and O(1) space complexity and has less lines of code. args: ----------- coins (array): an array contains available coin values. output: ----------- number (int) : represent the minimum amount of change that can't be made by the coins. """ currentChange = 0 # sort the array coins.sort() # iterate through the array and find the minimum change and return # if current itaration stage can't find minimum change add current coin # with the current change and make new current change. for coin in coins: if currentChange + 1 < coin: return currentChange + 1 currentChange += coin return currentChange + 1
true
e874e83c5936a8dcd28f2f04dde6de4d604c5980
amitopu/ProblemSet-1
/ValidateSubsequence/validate_subsequence.py
795
4.3125
4
def isValidSubsequence(array, sequence): """ Takes one array and a sequence(another array) and checks if the sequence is the subsequence of the array. solution complexity : O(n) time complexity and O(1) space complexity args: ----------- array : an array of numbers sequence : an array of numbers output: ----------- True : if the sequence is subsequence of the array. False : if above line is not true. """ arr_index = 0 seq_index = 0 #iterate over the array and check if elems in sequence are in the array while(arr_index <= len(array)-1): if(array[arr_index] == sequence[seq_index]): if(seq_index == len(sequence)-1): return True seq_index += 1 # take the next element in the sequence arr_index += 1 # take the next elem in the array return False
true
610395c1c0a55d4f8b7099bea152e4feb27dec23
Patryk9201/CodeWars
/Python/6kyu/one_plus_array.py
693
4.1875
4
""" Given an array of integers of any length, return an array that has 1 added to the value represented by the array. the array can't be empty only non-negative, single digit integers are allowed Return nil (or your language's equivalent) for invalid inputs. Examples For example the array [2, 3, 9] equals 239, adding one would return the array [2, 4, 0]. [4, 3, 2, 5] would return [4, 3, 2, 6] """ import unittest def up_array(arr): if not arr or min(arr) < 0 or max(arr) > 9: return None else: return [int(y) for y in str(int("".join([str(x) for x in arr])) + 1)] if __name__ == '__main__': x = up_array([2, 3, 9]) print(x) unittest.main()
true
a03d3d86b25f8f132efb169ad8bd8174a9152ddb
Patryk9201/CodeWars
/Python/8kyu/temperature_in_bali.py
1,092
4.1875
4
""" So it turns out the weather in Indonesia is beautiful... but also far too hot most of the time. Given two variables: heat (0 - 50 degrees centigrade) and humidity (scored from 0.0 - 1.0), your job is to test whether the weather is bareable (according to my personal preferences :D) Rules for my personal preferences i. if humidity > 0.5 or the heat >= 36, it's unbearable return false ii. if 25 < heat < 36 and the humidity > 0.4, also unbearable return false iii. otherwise, it's sunbathing time :), return true Examples > heat = 36, humdity = 0.3 -> return false > heat = 36, humdity = 0.5 -> return false > heat = 10, humdity = 0.51 -> return false -> triggered rule 1 > heat = 27, humdity = 0.5 -> return false -> triggered rule 2 > heat = 27, humdity = 0.4 -> return true > heat = 25, humdity = 0.5 -> return true > heat = 33, humdity = 0.38 -> return true -> triggered rule 3 """ def bareable(heat, humidity): return False if heat > 35 or humidity > 0.5 or humidity > 0.4 and 26 <= heat <= 35 else True if __name__ == '__main__': x = bareable(0.5, 10) print(x)
true
6151cf5dbcf387ec524efa0e39cf400c69ca1ee7
yurjeuna/teachmaskills_hw
/anketa.py
1,580
4.25
4
name = input("Hi! What's your name, friend? ") year_birth = int(input("Ok, do you remember when you were born? \ Let's start with the year of birth - ")) month_birth = int(input("The month of your birth - ")) day_birth = int(input("And the day of your birth, please,- ")) experience = int(input("Have you studied programming before? \ Choose the right option: 1 No 2 On your own 3 On course 4 In the university ")) goal = input("What are your expectations from this course? Continue the phrase: I'm here for ... ") year_now = int(input("So the last question," + name + ". What's the date of filling this form? \ Let's start with the year of filling - ")) month_now = int(input("The month of filling - ")) day_now = int(input("And the day of filling, please, - ")) if month_birth > month_now: age = year_now - year_birth elif month_birth < month_now: age = year_now - year_birth + 1 elif month_birth == month_now: if day_birth > day_now: age = year_now - year_birth else: age = year_now - year_birth + 1 print("Thank you, ", name, ". You are ", age, " years old. It's the perfect age.", sep='') if experience == 1: print("You haven't any experience in programming.") elif experience == 2: print("You tried to study programming on your own.") elif experience == 3: print("You have already tried to study programming on some course.") elif experience == 4: print("You studied programming in the university.") print("And now you are here for ", goal, ". So good luck to you! See you on lessons.", sep='')
true
9d569685b0d8d137b9ee7a23180289cfdd10488e
ErickaBermudez/exercises
/python/gas_station.py
1,752
4.3125
4
def canCompleteCircuit(gas, cost): numberOfStations = len(gas) # checking where it is possible to start for currentStartStation in range(numberOfStations): currentGas = gas[currentStartStation] canStart = True # with the current starting point, we can reach all the points # go through the circuit for station in range(numberOfStations): ###### to move in a circular array we use % ####### currentStation = (currentStartStation + station) % numberOfStations nextStation = (currentStation + 1) % numberOfStations # reference of this: https://www.geeksforgeeks.org/circular-array/ #################################################### # let's check what happens if we try to go to the next station currentGas -= cost[currentStation] # if the cost is greater than our current gas, we cannot afford it # therefore the currentStartStation is not an option anymore if currentGas < 0: canStart = False # this starting point is no longer suitable break # <-- we try another startStation # if we could go to the next, we are allowed to put more gas currentGas += gas[nextStation] # if we finish the circuit succesfully, we can start at the currentStartStation # and we don't need to continue checking if canStart: return currentStartStation # if we go through all the options to start and we don't find any solution return -1 # example startAt = canCompleteCircuit([5,1,2,3,4], [4,4,1,5,1]) if startAt > 0: print(startAt) else: print("We don't have enough gas </3")
true
b2ee470fd49b2af6f975b9571c5f7579082da359
mhkoehl0829/sept-19-flow-control
/Grade Program.py
515
4.125
4
print('Welcome to my grading program.') print('This program will determine which letter grade you get depending on your score.') print('What grade did you make?') myGrade = input('') if myGrade >= '90': print('You made an A.') else: if myGrade >= '80' and myGrade < '90': print('You get a B.') if myGrade >= '70' < myGrade < '80': print('You earned a C.') if myGrade >= '60' and myGrade < '70': print('You get a D.') if myGrade <= '60': print('You flunked.')
true
cbbcb84d2be44faf95bb4e30d5292deb2224f796
adri-leiva/python_dev
/Ejercicios_bloque1/ejercicio1.py
394
4.125
4
""" EJERCICIO 1 - Crear variables una "pais" y otra "continente" - Mostrar su valor por pantalla (imporimi) - Poner un comentario poniendo el tipo de dato """ pais = "Argentina" #tipo de detos: cadena continente = "Americano" #tipo de detos: cadena """ print(pais) print (continente) """ #print ("{} \n {}" . format(pais,continente)) print(f" Pais: {pais} \n Continente: {continente}")
false
ec7c0d69a9e98853f063fd32ef431f4f28448d76
Alleinx/Notes
/Python/Book_Learning_python/fluent_python/cp8/var.py
875
4.5625
5
# This program demonstrate the difference between shallow copy and deep copy import copy class Bus: def __init__(self, passengers=None): if passengers is None: self.passengers = [] else: self.passengers = list(passengers) # Defensive programming style, won't modify the original object if it's mutable. def pick(self, name): self.passengers.append(name) def drop(self, name): if name in self.passengers: self.passengers.remove(name) else: print(name, 'is not in the passenger list of the bus.') bus1 = Bus(['A', 'B', 'C']) bus2 = copy.copy(bus1) bus3 = copy.deepcopy(bus1) print(id(bus1), id(bus2), id(bus3)) bus1.drop('B') print(bus2.passengers, ',', bus3.passengers) print(id(bus1.passengers), id(bus2.passengers), id(bus3.passengers)) bus1.drop('D')
true
75b1d9b79bf3253b2d1a5c0ff2d9bc3124c9b621
Alleinx/Notes
/Python/Book_Learning_python/python_crash_course/part2_data_visualization/random_walk.py
928
4.15625
4
from random import choice class RandomWalk(): """ A class that randomly generate data""" def __init__(self, num_points=5000): self.num_points = num_points self.x = [0] self.y = [0] def fill_walk(self): """Genereate walking path""" while len(self.x) < self.num_points: x_step = self.get_step() y_step = self.get_step() # Avoid going nowhere if x_step == 0 and y_step == 0: continue # get Next position based on last position next_x = self.x[-1] + x_step next_y = self.y[-1] + y_step self.x.append(next_x) self.y.append(next_y) def get_step(self): """get walking step""" direction = choice([1, -1]) distance = choice([i for i in range(5)]) step = direction * distance return step
false
6fd363f6a639b159cc6594901c716fd3415a5402
023Sparrow/Projects
/Classic_Algorithms/Collatz_Conjecture.py
420
4.28125
4
#**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. def collatz(n): k = 0 while n != 1: if n%2 == 0: n = n/2 else: n = 3*n+1 k = k+1 return k # test print(collatz(5)) print(collatz(19)) print(collatz(2))
true
8e5103a6f4fbae5ce65bcd0fed09a9ea0ad16fbe
JohnFoolish/DocumentationDemo
/src/basic_code.py
1,426
4.4375
4
# -*- coding: utf-8 -*- """ This first one is a basic function that includes the code you would need to add two numbers together! Why is this function useful? ---------------------------- * It can replace the '+' key! * It can cause you to bill more hours for less work since the import takes extra time to type! * It can serve as a helpful demo. Written by John Lewis Corker """ def basic_numpy(x, y): """A very basic addition numpy function. This function contains a basic numpy docstring that we should be able to look at and compare. Usage below: >>> basic(5, 8) >>> 13 Parameters ---------- x : int This is a basic variable that will be added to the y value. y : int This is a basic variable that will be added to the x value. Returns ------- int The value of x and y added together """ z = x + y return z def basic_google(x, y): """A basic addition google function. This function contains a basic google docstring that we should be able to look at and compare. Usage below: >>> basic(5, 8) >>> 13 Args: x (int): a basic variable that will be added to the y value y (int): a basic variable that will be added to the x value Returns: int: The value of x and y added together """ z = x + y return z if __name__ == '__main__': basic(5, 10)
true
82d0625e5bb5253652418abbe3fe947de76d4114
AlanStar233/Neusoft_Activity_coding
/basic.py
402
4.1875
4
# # Ctrl+'/' # # print('Hello Alan!') # # #int # age = 19 # # #string # name = "张三" # # #print with var & var_type # print(age) # print(type(age)) # # print(name) # print(type(name)) # if name = input("Please type your name:") age = input("Please type your age:") if int(age) >= 18: print('{} Your age {} >= 18 !'.format(name, age)) else: print('{} Your age {} < 18 !'.format(name, age))
false
bf8a718b87bd57002dfd3037c1ea6ceda4ab0261
TommyThai-02/Python-HW
/hw04.py
512
4.1875
4
#Author: Tommy Thai #Filename: hw04.py #Assignment: hw04 #Prompt User for number of rows rows = int(input("Enter the number of rows:")) #input validation while rows < 1: #Error message print("Number of rows must be positive.") #Prompt again rows = int(input("Enter the number of rows:")) #After valid input, start loop for printing stars. while rows > 0: columns = rows while columns > 0: print("*", end = "") columns -= 1 rows -= 1 print()
true
ef3b8d624346cfbc6516b8d44e8cc22001e88ce9
damodharn/Python_Week1
/Week1_Algo/Temp_Conversion.py
755
4.25
4
# ********************************************************************************************* # Purpose: Program for checking if two strings are Anagram or not. # Author: Damodhar D. Nirgude. # ************************************************************************************************ from Week1_Algo.Utility2 import Utility2 try: temp = int(input("Input Temperature")) except ValueError as e: print(e) else: while 1: print("Select Conversion:\n1: Celsius to Fahrenheit\n2: Fahrenheit to Celsius") choice = int(input()) if choice == 1 or choice == 2: converted = Utility2.tempconvert(choice, temp) print("Converted temp: ", converted) break else: print("Wrong I/p")
true
c93849ff244e494864be212fa94d97a591233291
damodharn/Python_Week1
/Week1_Functional/StopWatch.py
868
4.28125
4
# ********************************************************************************************* # Purpose: Program for measuring the time that elapses between # the start and end clicks. # Author: Damodhar D. Nirgude. # ************************************************************************************************ import time print("Enter to start Stopwatch") input() # Take i/p from User to Start the Stop watch. startTime = time.time() print("Enter to Stop Stopwatch") input() # Take i/p from User to Stop the Stop watch. stopTime = time.time() sec = int(stopTime - startTime) # Calculate elapsed time between start and stop in Sec. if sec < 60: # Checking if elapsed time is less than a minute print(sec, 'sec') else: mint = int(sec/60) # Calculating No. of Minutes sec = sec % 60 # Calculating remaining Sec print(mint, 'min', sec, 'sec')
true
a1808e94fd51c61a549a7131cf032eb3aa90c8f5
jsimonton020/Python_Class
/lab9_lab10/lab9-10_q1.py
642
4.125
4
list1 = input("Enter integers between 1 and 100: ").split() # Get user input, and put is in a list list2 = [] # Make an empty list for i in list1: # Iterate over list1 if i not in list2: # If the element is not in list2 list2.append(i) # Add the element to list2 (so we don't have to count it again) count = list1.count(i) # Count the element in list1 print(i, "occurs", count, "time" if count == 1 else "times") # Print the results ''' Enter integers between 1 and 100: 2 5 6 5 4 3 23 43 2 2 occurs 2 times 5 occurs 2 times 6 occurs 1 time 4 occurs 1 time 3 occurs 1 time 23 occurs 1 time 43 occurs 1 time '''
true
0dbdddafe5f0a2fad6b8778c78ec913561218eea
AndriyPolukhin/Python
/learn/ex02/pinetree.py
1,500
4.21875
4
''' how tall is the tree : 5 # ### ##### ####### ######### # ''' # TIPS to breakdown the problem: # I. Use 1 while loop and 3 for loops # II. Analyse the tree rules: # 4 spaces _ : # 1 hash # 3 spaces _ : # 3 hashes # 2 spaces _ : # 5 hashes # 1 space _ : # 7 hashes # 0 spaces _ : # 9 hashes # III. Save the first and the last as 1 hash # Need to do: # 1. Decrement spaces by 1 each time through the loop # 2. Increment the hashes by 2 each time through the loop # 3. Save spaces to the stump by calculating tree height - 1 # 4. Decrement from tree height until it equals 0 # 5. Print spaces and hashses for each row # 6. Print stump spaces and then 1 hash # 1. Ask for the tree height: # 2. Convert the height string into an integer: # 3. Variables # string = space+space+space+space+hash+space+space+space+space tree_height = input("How tall is the tree: ") tree_height = int(tree_height) numberOfSpaces = (tree_height - 1) hash = "#" space = " " string = "" spaces = "" hashes = "" numberOfHashes = (tree_height - numberOfSpaces) print("Starting number of space _ is {}".format(numberOfSpaces)) print("Starting number of hash # is {}".format(numberOfHashes)) while(tree_height != 0): for s in range(numberOfSpaces): spaces += space print(spaces) for h in range(numberOfHashes): hashes += hash print(hashes) numberOfSpaces = numberOfSpaces - 1 numberOfHashes += 2 tree_height = tree_height - 1
true
a2b98b45cc022cabeb8dd82c582fd1c2f37356fb
AndriyPolukhin/Python
/learn/ex01/checkage.py
805
4.5
4
# We'll provide diferent output based on age # 1- 18 -> Important # 21,50, >65 -> Important # All others -> Not Important # List # 1. Receive age and store in age age = eval(input("Enter age: ")) # and: If Both are true it return true # or : If either condition is true then it return true # not : Convert a true condition into a false # 2. If age is both greater than or equal to 1 and less than or equal to 18 Print Important if (age >= 1 and age <= 18): print("Important Birthday") # 3. If age is either 21 or 50 Important elif (age == 21 or age == 50): print ("Important Birthday") # 4. We check if age is less than 65 and then covnert true to false and vice versa elif not(age < 65): print("Not Important Birthday") # 5. Else Not Important else: print("Sorry Not Important")
true
06a522784b6f26abb7be62f6bfd8486ffd425db0
AndriyPolukhin/Python
/learn/ex01/gradeans.py
437
4.15625
4
# Ask fro the age age = eval(input("Enter age: ")) # Handle if age < 5 if age < 5: print("Too young for school") # Special output just for age 5 elif age == 5: print("Go to Kindergarden") # Since a number is the result for age 6 - 17 we can check them all with 1 condition elif (age > 5) and (age <= 17): grade = age - 5 print("Go to {} grade".format(grade)) # Handle everyone else else: print("Go to College")
true
25d6aada9d0ae475343ca02fa79a5969565a4b7b
RehamDeghady/python
/task 2.py
753
4.3125
4
print("1.check palindrome") print("2.check if prime") print("3.Exit") operation = int (input ("choose an operation:")) if operation == 1 : word = str(input("enter the word")) revword = word[::-1] print("reversed word is" ,revword) if word == revword : print("yes it is palindrome") else: print("No it is not palindrome") elif operation == 2: num = int(input("enter a positive number")) if num<=0: print(num,"is not a prime number") else: for i in range(2,num): if num%i == 0 : print(num , "is not a prime number") break else: print(num, "is a prime number") else: print("EXIT")
true
971f5ec8bb222bbfc91123e24bcccdaf3caece28
sidsharma1990/Python-OOP
/Inheritance.py
1,519
4.65625
5
######### Inheritance ###### #####Single inheritance###### ###### to inherit from only 1 class#### class fruits: def __init__(self): print ('I am a Fruit!!') class citrus(fruits): def __init__(self): super().__init__() print ('I am citrus and a part of fruit class!') obj1 = citrus() ##### Multiple inheritance###### ###### to inherit from more than 1 class#### class A: pass class B: pass class C(A,B): pass issubclass (C,A) and issubclass (C,B) '''Output --> True''' ##### Multilevel inheritance###### ###### One class from another and another from another #### ####### Grandparents to parents, from parents to you ###### class A: x = 10 class B(A): pass class C(B): pass obj1 = C() obj1.x '''Output --> 10''' ##### Hierarchical inheritance###### ###### More than one class inherits from a Class #### ####### Your parents have 3 children ###### class A: x = 10 class B(A): pass class C(A): pass obj1 = C() obj1.x issubclass (B,A) and issubclass (C,A) '''Output --> 10''' '''Output --> True''' ##### Hybrid inheritance###### ###### Combination of any two kinds of inheritance (Hierarchical inheritance and Multiple inheritance)#### ####### Class E inherits from Class B n D and both B n D inherits from class A###### class A: x = 10 class B(A): pass class C(A): pass class D(A): pass class E(B,D): pass obj2 = E() obj2.x '''Output --> 10'''
true
3c41155cbab16bb91e4387aa35d49e1832ce5b72
codedsun/LearnPythonTheHardWay
/ex32.py
525
4.25
4
#Exercise 32: Loops and List the_count = [1,2,3,4,5] fruits = ['apples','oranges','pears','apricots'] change = [1,'pennies',2,'dimes',3,'quaters'] #for loop in the list for number in the_count: print("This is %d count"%number) for fruit in fruits: print("A fruit of type %s"%fruit) for i in change: print("I got %r"%i) #Building empty list and then appending it element=[] for i in range(0,6): print("Adding the %d in the list"%i) element.append(i) for i in element: print("Element %d"%i)
true
8c3788b2fc95ce08c9dc6165b6f5de91e7d7d448
semihyilmazz/Rock-Paper-Scissors
/Rock Paper Scissors.py
2,933
4.40625
4
import random print "********************************************************" print "Welcome to Rock Paper Scissors..." print "The rules are simple:" print "The computer and user choose from Rock, Paper, or Scissors." print "Rock crushes scissors." print "Paper covers rock." print "and" print "Scissors cut paper." print "You will play the computer...the first to reach 3 wins wins the match." print "Good luck!" print "************************************************************""" user_win = 0 computer_win= 0 user_name= raw_input("Whats Your Name? ") while True: computer_choice = "" user_choice = raw_input("Please choose (R) Rock, (P) Paper, or (S) Scissors: ").upper() random_number = random.randint(1,3) if random_number == 1: computer_choice = "R" if random_number == 2: computer_choice = "P" if random_number == 3: computer_choice = "S" if computer_choice == "R": print(""" _______ ---' ____) (_____) (_____) (____) ---.__(___) The computer chose rock.""") elif computer_choice == "P": print(""" _______ ---' ____)____ ______) _______) _______) ---.__________) The computer chose paper.""") elif computer_choice == "S": print(""" _______ ---' ____)____ ______) __________) (____) ---.__(___) The computer chose scissors.""") print "" if (computer_choice == "R" and user_choice == "P") or \ (computer_choice == "P" and user_choice == "S") or \ computer_choice == "S" and user_choice == "R": print "You win!" user_win +=1 print user_name, user_win print "computer=", computer_win elif (computer_choice == "R" and user_choice == "S") or \ (computer_choice == "P" and user_choice == "R") or \ (computer_choice == "S" and user_choice == "P"): print "You lose!" computer_win +=1 print user_name, user_win print "computer=", computer_win else: print "Ties" print user_name, user_win print "computer=", computer_win if computer_win == 3: print user_name,"LOST" user_win =0 computer_win = 0 delay = raw_input("You want to play another game Y/N ? ") if delay == "y": continue else: break elif user_win == 3: print user_name,"WON" user_win = 0 computer_win = 0 delay = raw_input("You want to play another game Y/N ? ") if delay == "y": continue else: break
true
9a6fe2ffbb280d239d50001e637783520b8d4aef
songseonghun/kagglestruggle
/python3/201-250/206-keep-vowels.py
272
4.1875
4
# take a strign. remove all character # that are not vowels. keep spaces # for clarity import re s = 'Hello, World! This is a string.' # sub = substitute s2 = re.sub( '[^aeiouAEIOU ]+', #vowels and # a space '', #replace with nothing s ) print(s2)
true
b5363f3d6c5b6e55b3d7607d055a266b215c28ab
dianamenesesg/HackerRank
/Interview_Preparation_Kit/String_manipulation.py
2,979
4.28125
4
""" Strings: Making Anagrams Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number? Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings. For example, if and , we can delete from string and from string so that both remaining strings are and which are anagrams. Function Description Complete the makeAnagram function in the editor below. It must return an integer representing the minimum total characters that must be deleted to make the strings anagrams. makeAnagram has the following parameter(s): a: a string b: a string Input Format The first line contains a single string, . The second line contains a single string, . Constraints The strings and consist of lowercase English alphabetic letters ascii[a-z]. Output Format Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other. Sample Input cde abc Sample Output 4""" import math import os import random import re import sys # Complete the makeAnagram function below. def makeAnagram(a, b): for character_a in a: if character_a in b: a = a.replace(character_a,"",1) b = b.replace(character_a,"",1) num_deleted = len(a) + len(b) return num_deleted #print(makeAnagram("jxwtrhvujlmrpdoqbisbwhmgpmeoke", "fcrxzwscanmligyxyvym")) """ Alternating Characters A Shashank le gustan las cadenas donde los caracteres consecutivos son diferentes. Por ejemplo, le gusta , mientras que no le gusta. Dada una cadena que solamente contiene caracteres y , él quiere cambiarla a una cadena que le guste. Para hacerlo, solo se le permite borrar los caracteres en la cadena. Tu tarea es encontrar la mínima cantidad requerida de borrados. Formato de Entrada La primera linea contiene un enter que quiere decir el número de casos de prueba. Luego siguen lineas , con una cadena en cada linea. Formato de Salida Imprimie la mínima cantidad requerida de pasos en cada caso de prueba. Restricciones Ejemplo de Entrada 5 AAAA BBBBB ABABABAB BABABA AAABBB Ejemplo de Salida 00 3 4 0 0 4 """ def alternatingCharacters(s): #return len([1 for x in range(len(s)-1) if s[x]==s[x+1]]) case = 0 for i in range(len(s)-1): if s[i] == s[i+1]: case += 1 return case #alternatingCharacters('AAABBBAABB')
true
c5d1e2535e6e8d9ac0218f06a44e437b3358049b
michaelschung/bc-ds-and-a
/Unit1-Python/hw1-lists-loops/picky-words-SOLUTION.py
543
4.3125
4
''' Create a list of words of varying lengths. Then, count the number of words that are 3 letters long *and* begin with the letter 'c'. The count should be printed at the end of your code. • Example: given the list ['bat', 'car', 'cat', 'door', 'house', 'map', 'cyst', 'pear', 'can', 'spike'], there are exactly 3 qualifying words. ''' words = ['bat', 'car', 'cat', 'door', 'house', 'map', 'cyst', 'pear', 'can', 'spike', 'ace', 'cpe'] count = 0 for word in words: if len(word) == 3 and word[0] == 'c': count += 1 print(count)
true
c9a7bdeb85a94afc6b17c2b6ddf3be0d78de6206
yangju2011/udacity-coursework
/Programming-Foundations-with-Python/turtle/squares_drawing.py
755
4.21875
4
import turtle def draw_square(some_turtle): i = 0 while i<4: # repeat for squares some_turtle.forward(100) some_turtle.right(90) i=i+1 def draw_shape():#n stands for the number of edge windows = turtle.Screen()#create the background screen for the drawing windows.bgcolor("red") brad = turtle.Turtle() #move around, def __init__ stand for initialize brad.shape("turtle")#https://docs.python.org/2/library/turtle.html#turtle.shape brad.color("white","blue")#two color, first outline, second filled; can't do three colors brad.speed(5) for i in range(0,36): brad.right(10) draw_square(brad) windows.exitonclick() draw_shape()
true
ea34741f8866856bdee9702bc20184f57cf65271
onursevindik/GlobalAIHubPythonCourse
/Homework/HW2/HW2-Day3.py
843
4.15625
4
d = {"admin":"admin"} print("Welcome!") username = input("Enter your username: ") password = input("Enter your password: ") for k,v in d.items(): if (k != username and v == password): print(" ") print("xxXxx Wrong username! xxXxx") elif(k == username and v != password): print(" ") print("xxXxx Wrong password! xxXxx") elif(k != username and v != password): print(" ") print("xxXxx Wrong username and password! xxXxx") else: print(" ") print("Congratulations") print("Login successful!", u'\u2713') """ for k,v in d.items(): print("########################") print("#######--HINT--#########") print("########################") print(" username: ", k) print(" password: ", v) print("########################") """
false
1bb3d699d6d1e7ef8ea39a5cdc7d55f79ac4ed3d
theelk801/pydev-psets
/pset_lists/list_manipulation/p5.py
608
4.25
4
""" Merge Lists with Duplicates """ # Use the two lists below to solve this problem. Print out the result from each section as you go along. list1, list2 = [2, 8, 6], [10, 4, 12] # Double the items in list1 and assign them to list3. list3 = None # Combine the two given lists and assign them to list4. list4 = None # Replace the first 3 items in list 3 with the numbers 4, 3, 12. # Create a variable list5. Merge list3 and list4 to create a list containing no duplicates. list5 = None # Take a look at your printed statements to see the evolution of your lists with each step of this problem.
true
d7aa917a00b2f582c7b15c8b40de0462ca274a66
theelk801/pydev-psets
/pset_classes/fromagerie/p6.py
1,200
4.125
4
""" Fromagerie VI - Record Sales """ # Add an instance method called "record_sale" to the Cheese class. Hint: You will need to add instance attributes for profits_to_date and sales (i.e. number of items sold) to the __init__() method in your Cheese class definition BEFORE writing the instance method. # The record_sale method should do the following: ### Add the sale's profits to profits_to_date attribute. ### Add the number sold to the running total in the sales attribute. ### Subtract the number sold from the stock attribute. ### Check the stock (Hint: Call the check_stock method within the record_sale method.) # Once finished, call record_sale on each sale from the sales_today dict below and print out the name of the cheese, whether it has a low stock alert, the remaining stock value, the running total of units of that cheese sold, and the running total of your profits to date. It should look something like this: """ Parmigiano reggiano - Low stock alert! Order more parmigiano reggiano now. Remaining Stock: 14 Total Sales: 10 Profits to Date: 20 """ sales_today = {provolone: 8, gorgonzola: 7, mozzarella: 25, ricotta: 5, mascarpone: 13, parmigiano_reggiano: 10, pecorino_romano: 8}
true
1859b100bd9711dfa564f8d3a697202bc42d96c2
theelk801/pydev-psets
/pset_conditionals/random_nums/p2.py
314
4.28125
4
""" Generate Phone Number w/Area Code """ # import python randomint package import random # generate a random phone number of the form: # 1-718-786-2825 # This should be a string # Valid Area Codes are: 646, 718, 212 # if phone number doesn't have [646, 718, 212] # as area code, pick one of the above at random
true
278cfd9000b17eaf249eebad07b11d078e934c35
theelk801/pydev-psets
/pset_classes/bank_accounts/solutions/p2.py
1,377
4.21875
4
""" Bank Accounts II - Deposit Money """ # Write and call a method "deposit()" that allows you to deposit money into the instance of Account. It should update the current account balance, record the transaction in an attribute called "transactions", and prints out a deposit confirmation message. # Note 1: You can format the transaction records like this - "Deposit: <starting balance>, <ending balance>" # Note 2: You can format the deposit confirmation message like this - "$<amount> deposit complete." class Account(): def __init__(self, name, account_number, initial_amount): self.name = name self.acc_num = account_number self.balance = initial_amount self.transactions = {} int_rate = 0.5 def acc_details(self): print(f'Account No.: {self.acc_num}\nAccount Holder: {self.name}\nInterest Rate: {self.int_rate}\nBalance: ${self.balance}\n') def deposit(self, amount): start_amount = self.balance self.balance += amount end_amount = self.balance label = 'Deposit' self.transactions.update({label: [start_amount, end_amount]}) print(f'${amount} deposit complete.') alejandra = Account('Alejandra Ochoa', 554951, 20000) alejandra.deposit(500) print(f'${alejandra.balance}') # 20500 print(alejandra.transactions) # {'Deposit': [20000, 20500]} alejandra.acc_details()
true
9d9d044b0bff764cc3a8f4e31634f1138f05e2b4
Arin-py07/Python-Programms
/Problem-11.py
888
4.1875
4
Python Program to Check if a Number is Positive, Negative or 0 Source Code: Using if...elif...else num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") Here, we have used the if...elif...else statement. We can do the same thing using nested if statements as follows. Source Code: Using Nested if num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number") else: print("Negative number") The output of both programs will be the same. Output 1 Enter a number: 2 Positive number Output 2 Enter a number: 0 Zero A number is positive if it is greater than zero. We check this in the expression of if. If it is False, the number will either be zero or negative. This is also tested in subsequent expression.
true
5b428c1de936255d8a787f6939528031fa3ddc9b
Arin-py07/Python-Programms
/Problem-03.py
1,464
4.5
4
Python Program to Find the Square Root Example: For positive numbers # Python Program to calculate the square root # Note: change this value for a different result num = 8 # To take the input from the user #num = float(input('Enter a number: ')) num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) Output The square root of 8.000 is 2.828 In this program, we store the number in num and find the square root using the ** exponent operator. This program works for all positive real numbers. But for negative or complex numbers, it can be done as follows. Source code: For real or complex numbers # Find square root of real or complex numbers # Importing the complex math module import cmath num = 1+2j # To take input from the user #num = eval(input('Enter a number: ')) num_sqrt = cmath.sqrt(num) print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag)) Output The square root of (1+2j) is 1.272+0.786j In this program, we use the sqrt() function in the cmath (complex math) module. Note: If we want to take complex number as input directly, like 3+4j, we have to use the eval() function instead of float(). The eval() method can be used to convert complex numbers as input to the complex objects in Python. To learn more, visit Python eval() function. Also, notice the way in which the output is formatted. To learn more, visit string formatting in Python.
true
e6dead53cca8e5bef774435616a2dd02452e6389
ejoconnell97/Coding-Exercises
/test2.py
1,671
4.15625
4
def test_2(A): # write your code in Python 3.6 ''' Loop through S once, saving each value to a new_password When a numerical character is hit, or end of S, check the new_password to make sure it has at least one uppercase letter - Yes, return it - No, reset string to null and continue through S If new_password is empty, return -1 ''' current_password = "" new_password = "" has_upper = False password_length = 0 #loop through all of S for x in A: #if the current character is not a number if (x.isalpha()): current_password += x #update the new password if needed new_password, has_upper = update_string(current_password, new_password, has_upper) else: #update new_password if S ends with a number new_password, has_upper = update_string(current_password, new_password, has_upper) #otherwise, reset the current_password because you've reached a number current_password = "" if not new_password: return -1 print (new_password) password_length = len(new_password) return password_length #make sure that the current_password has at least one uppercase character and is longer than new_password before updating it def update_string(current, new, has_upper): for x in current: if x.isupper(): has_upper = True if (has_upper == True and (len(current) > len(new))): new = current has_upper = False return new, has_upper A = "a00000000000000aA9AAA" test_2(A)
true
0860ed14b0d55e8a3c09aeb9e56075354d1e1298
npandey15/CatenationPython_Assignments
/Task1-Python/Task1_Python/Q3.py
547
4.15625
4
Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> x=6 >>> y=10 >>> >>> Resultname=x >>> x=y >>> y=Resultname >>> print("The value of x after swapping: {}".format(x)) The value of x after swapping: 10 >>> print("The value of y after swaaping:{}".format(y)) The value of y after swaaping:6 >>> >>> >>> # without using third variable >>> >>> x=6 >>> y=10 >>> >>> x,y=y,x >>> print("x=",x) x= 10 >>> print("y=",y) y= 6 >>>
true
8a99191f6780e06be6e14501b671cc981f42bf0d
npandey15/CatenationPython_Assignments
/Passwd.py
1,188
4.34375
4
# Passwd creation in python def checker_password(Passwd): "Check if Passwd is valid" Specialchar=["$","#","@","*","%"] return_val=True if len(passwd) < 8: print("Passwd is too short, length of the password should be at least 8") return_val=False if len(passwd) > 30: print("Passwd is too long, length of the password should not be greater than 8") return_val=False elif len(passwd) > 8 and len(passwd) <= 30: print("Passwd OK") return_val=True if not any(char.isdigit() for char in passwd): print("Passwd should have atleast one numerical input") return_val=False if not any(char.isupper() for char in passwd): print("Passwd should have at least one UPPERCASE Letter") return_val=False if not any(char in Specialchar for char in passwd): print("Passwd should have at least one Special character $#@*%") return_val=False if return_val: print("OK") return return_val else: print("Invalid Passwd") print(checker_password.__doc__) passwd=input("Enter the password: ") print(checker_password(passwd))
true
2255001526278b22c7cb99594f4f5274b399371a
aparna-narasimhan/python_examples
/Matrix/sort_2d_matrix.py
1,281
4.28125
4
#Approach 1: Sort 2D matrix in place def sort_2d_matrix(A, m, n): t=0 for x in range(m): for y in range(n): for i in range(m): for j in range(n): if(A[i][j]>A[x][y]): print("Swapping %d with %d"%(A[i][j], A[x][y])) t=A[x][y] A[x][y]=A[i][j] A[i][j]=t for i in range(m): print(A[i]) A = [[8,3,4],[2,1,6],[5,9,7]] for i in range(3): print(A[i]) print("\n") sort_2d_matrix(A, 3, 3) #Approach 2: Saving the 2D Array into a 1D Array, sort the array and place it back in the 2D array int B[]=new int[m*n]; //creating a 1D Array of size 'r*c' int x = 0; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { B[x] = A[i][j]; x++; } } #Sorting the 1D Array in Ascending Order - Bubble sort int t=0; for(int i=0; i<(m*n)-1; i++) { for(int j=i+1; j<(m*n); j++) { if(B[i]>B[j]) { t=B[i]; B[i]=B[j]; B[j]=t; } } } #Saving the sorted 1D Array back into the 2D Array x = 0; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { A[i][j] = B[x]; x++; } }
false
6da25701a40c8e6fce75d9ab89aaf63a45e2ecfe
aparna-narasimhan/python_examples
/Strings/shortest_unique_substr.py
1,322
4.15625
4
''' Smallest Substring of All Characters Given an array of unique characters arr and a string str, Implement a function getShortestUniqueSubstring that finds the smallest substring of str containing all the characters in arr. Return "" (empty string) if such a substring doesn’t exist. Come up with an asymptotically optimal solution and analyze the time and space complexities. Example: input: arr = ['x','y','z'], str = "xyyzyzyx" output: "zyx" See here for more examples: https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/ TODO: This is a working brute force solution. Need to come up with an optimal solution ''' from collections import defaultdict def get_shortest_unique_substring(arr, str): arr_dict = defaultdict(int) max_count = len(arr) min_len = 32768 result = "" for c in range(len(str)): length = 0 count = 0 start = 0 for char in arr: arr_dict[char] = 1 for i,ch in enumerate(str[c:]): if arr_dict[ch] == 1: arr_dict[ch] -= 1 count += 1 if start == 0: start = c length += 1 if count == max_count: if length < min_len: min_len = length result = str[start:start+length] #print result break return result
true
0111fd00103f42a032074e0c3b4d40006f1029f9
aparna-narasimhan/python_examples
/Arrays/missing_number.py
866
4.28125
4
''' If elements are in range of 1 to N, then we can find the missing number is a few ways: Option 1 #: Convert arr to set, for num from 0 to n+1, find and return the number that does not exist in set. Converting into set is better for lookup than using original list itself. However, space complexity is also O(N). Option#2: Sum of all elements from 1 to N - Sum of all elements in the array = Missing number Adv: No space complexity Option#3: XOR all elements in the array + XOR all elements from 1 to N = Missing number Provided no duplicates? Adv: No space complexity XOR is fast operation ''' #[1,2,3,5,6,7,8] def find_missing_number(arr): n = len(arr) total_sum = sum(range(1,arr[-1]+1)) print(total_sum) arr_sum = sum(arr) print(arr_sum) missing_num = total_sum - arr_sum print(missing_num) find_missing_number([1,2,3,5,6,7,8])
true
8d401a11b4ea284f9bb08c2e2615b9414fd3d3ac
aparna-narasimhan/python_examples
/Misc/regex.py
2,008
4.625
5
#https://www.tutorialspoint.com/python/python_reg_expressions.htm import re line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!" ''' When the above code is executed, it produces following result − searchObj.group() : Cats are smarter than dogs searchObj.group(1) : Cats searchObj.group(2) : smarter ''' #!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'\D', "", phone) print "Phone Num : ", num ''' When the above code is executed, it produces the following result − Phone Num : 2004-959-559 Phone Num : 2004959559 ''' ''' Sr.No. Example & Description 1 [Pp]ython Match "Python" or "python" 2 rub[ye] Match "ruby" or "rube" 3 [aeiou] Match any one lowercase vowel 4 [0-9] Match any digit; same as [0123456789] 5 [a-z] Match any lowercase ASCII letter 6 [A-Z] Match any uppercase ASCII letter 7 [a-zA-Z0-9] Match any of the above 8 [^aeiou] Match anything other than a lowercase vowel 9 [^0-9] Match anything other than a digit Special Character Classes Sr.No. Example & Description 1 . Match any character except newline 2 \d Match a digit: [0-9] 3 \D Match a nondigit: [^0-9] 4 \s Match a whitespace character: [ \t\r\n\f] 5 \S Match nonwhitespace: [^ \t\r\n\f] 6 \w Match a single word character: [A-Za-z0-9_] 7 \W Match a nonword character: [^A-Za-z0-9_] Repetition Cases Sr.No. Example & Description 1 ruby? Match "rub" or "ruby": the y is optional 2 ruby* Match "rub" plus 0 or more ys 3 ruby+ Match "rub" plus 1 or more ys 4 \d{3} Match exactly 3 digits 5 \d{3,} Match 3 or more digits 6 \d{3,5} Match 3, 4, or 5 digits '''
true
ac26b98728ecf7d49aa79f70aa5dd5e3238ef10d
aparna-narasimhan/python_examples
/pramp_solutions/get_different_number.py
1,319
4.125
4
''' Getting a Different Number Given an array arr of unique nonnegative integers, implement a function getDifferentNumber that finds the smallest nonnegative integer that is NOT in the array. Even if your programming language of choice doesn’t have that restriction (like Python), assume that the maximum value an integer can have is MAX_INT = 2^31-1. So, for instance, the operation MAX_INT + 1 would be undefined in our case. Your algorithm should be efficient, both from a time and a space complexity perspectives. Solve first for the case when you’re NOT allowed to modify the input arr. If successful and still have time, see if you can come up with an algorithm with an improved space complexity when modifying arr is allowed. Do so without trading off the time complexity. Analyze the time and space complexities of your algorithm. Example: input: arr = [0, 1, 2, 3] output: 4 ''' #Approach1: It is enough to iterate only upto length of the list instead of up to MAX_INT. Use set instead of the array itself as lookup time of a set is O(1). Set is similar to dict and can be used when we don't need to store values. def get_different_number(arr): temp_set = set(arr) for i in range(len(arr)): if i not in temp_set: return i if i == (2 ** 31) - 1: return i else: return i + 1
true
93354f664979d327f700a7f5ed4a28d92b978b16
premraval-pr/ds-algo-python
/data-structures/queue.py
1,040
4.34375
4
# FIFO Structure: First In First Out class Queue: def __init__(self): self.queue = [] # Insert the data at the end / O(1) def enqueue(self, data): self.queue.append(data) # remove and return the first item in queue / O(n) Linear time complexity def dequeue(self): if self.is_empty(): return -1 data = self.queue[0] del self.queue[0] return data # returns the first element / O(1) def peek(self): return self.queue[0] # check if the queue is empty / O(1) def is_empty(self): return self.queue == [] # returns the size / O(1) def queue_size(self): return len(self.queue) queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print("Dequeue: %d" % queue.dequeue()) print("Size: %d" % queue.queue_size()) print("Peek: %d" % queue.peek()) print("Size: %d" % queue.queue_size()) print("Dequeue: %d" % queue.dequeue()) print("Dequeue: %d" % queue.dequeue()) print("Dequeue: %d" % queue.dequeue())
true
d73c7a9bec4f30251d31d42a17dfa7fde9a48f8e
danieltapp/fcc-python-solutions
/Basic Algorithm Scripting Challenges/caesars-cipher.py
848
4.21875
4
#One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount. #A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on. #Write a function which takes a ROT13 encoded string as input and returns a decoded string. def rot13(str): l = list(str.lower()) for i in range(0, len(l)): if l[i].isalpha(): if ord(l[i]) > 109: l[i] = chr(ord(l[i]) - 13) elif ord(l[i]) <= 109: l[i] = chr(ord(l[i]) + 13) return ''.join(l).upper() print(rot13("SERR PBQR PNZC")) print(rot13('SERR CVMMN!')) print(rot13("SERR YBIR?")) print(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."))
true
2248f6b4e815240d85ee37a6af3dc6c58d44d2d7
danieltapp/fcc-python-solutions
/Basic Algorithm Scripting Challenges/reverse-a-string.py
313
4.4375
4
#Reverse the provided string. #You may need to turn the string into an array before you can reverse it. #Your result must be a string. def reverse_string(str): return ''.join(list(reversed(str))) print(reverse_string('hello')) print(reverse_string('Howdy')) print(reverse_string('Greetings from Earth'))
true
759f39154fc321a20f84850be8482262b21b427e
oluwaseunolusanya/al-n-ds-py
/chapter_4_basic_data_structures/stackDS.py
967
4.375
4
class Stack: #Stack implementation as a list. def __init__(self): self._items = [] #new stack def is_empty(self): return not bool(self._items) def push(self, item): self._items.append(item) def pop(self): return self._items.pop() def peek(self): return self._items[-1] def size(self): return len(self._items) """ s = Stack() print(s.is_empty()) s.push('Olu') print(s.is_empty()) print(s.peek()) print(s.size()) s.push([1 ,2, 5]) print(s.size()) print(s) print(s.pop()) print(s.size()) """ #Function below uses Stack to reverse the characters in a string ''' def rev_string(my_str): my_str_stack = Stack() for i in my_str: my_str_stack.push(i) print(my_str_stack.peek()) reversed_string = "" while not my_str_stack.is_empty(): reversed_string += my_str_stack.pop() return print(reversed_string) rev_string('I want an apple') '''
true
6eeaf28db7712b70d7ada9c3632b832c0fdeec74
melany202/programaci-n-2020
/talleres/tallerCondicional.py
1,918
4.125
4
#Ejercicio 1 condicionales print('ejercicio 1') preguntaNumero1='Ingrese un numero entero : ' preguntaNumero2='Ingrese otro numero entero : ' numero1=int(input(preguntaNumero1)) numero2=int(input(preguntaNumero2)) if(numero1>numero2): print(f'el {numero1} es mayor que el {numero2}') elif(numero1==numero2): print('Los numeros son iguales') else: print(f'el {numero2} es mayor que el {numero1}') #Ejercicio 2 condicionales print('ejercicio 2') preguntaEdad='Ingrese por favor su edad : ' edad=int(input(preguntaEdad)) if(edad>=18 and edad<=25): print('Es usted una persona joven') elif(edad>=26 and edad<=60): print('Es usted un adulto') else: print('Es usted un adulto mayor') #Ejercicio 3 condicionales print('ejercicio 3') preguntAñoActual='por favor ingrese el año actual : ' preguntaAñoCualquiera='por favor ingrese un año cualquiera: ' añoActual=int(input(preguntAñoActual)) añoCualquiera=int(input(preguntaAñoCualquiera)) mensaje='{}{} años' if(añoCualquiera>añoActual): resta=añoCualquiera - añoActual print(mensaje.format('han pasado', resta)) elif(añoActual>añoCualquiera): resta=añoActual - añoCualquiera print(mensaje.format('faltan',resta)) else: print('los años son iguales') #Ejercicio 4 condicionales print('ejercicio 4') #---preguntas---# preguntaMedida='Ingrese por favor una distancia en centimetros : ' preguntaUnidades='''ingrese en que unidades desea transformar: K-Kilometros M-Metros mm-Milimetros ''' mensajeError='Entrada no valida,repita por favor' #---entradas---# medida=float(input(preguntaMedida)) Unidades=input(preguntaUnidades) #---conversiones---# Metros= medida/100 kilometos=medida*10**5 Milimetros=medida*10 if(Unidades=='K'): print(kilometos) elif(Unidades=='M'): print(Metros) elif(Unidades=='mm'): print(Milimetros) else: print(mensajeError)
false
12c60f5ae394f343056619738299f0d2a68e9bbb
userzz15/-
/力扣/Mysort.py
2,774
4.125
4
import random def bubble_sort(arr, size): """冒泡排序""" for i in range(size - 1): for j in range(size - 1 - i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] def select_sort(arr, size): """选择排序""" for i in range(size - 1): temp = i for j in range(i+1, size): if arr[temp] > arr[j]: temp = j if temp != i: arr[i], arr[temp] = arr[temp], arr[i] def insert_sort(arr, size): """插入排序""" for i in range(1, size): j = i while j-1 > -1 and arr[j] < arr[j-1]: arr[j], arr[j-1] = arr[j-1], arr[j] j -= 1 def quick_sort(arr, start, end): """快速排序""" if start >= end: return left = start right = end temp = arr[left] while left < right: while left < right and arr[right] > temp: right -= 1 arr[left] = arr[right] while left < right and arr[left] <= temp: left += 1 arr[right] = arr[left] arr[right] = temp quick_sort(arr, start, right) quick_sort(arr, right+1, end) def merge(arr, start, mid ,end): left = start right = mid + 1 temp = [] while left <= mid and right <= end: if arr[left] < arr[right]: temp.append(arr[left]) left += 1 else: temp.append(arr[right]) right += 1 while left <= mid: temp.append(arr[left]) left += 1 while right <= end: temp.append(arr[right]) right += 1 arr[start:end+1] = temp def merge_sort(arr, start, end): """归并排序""" if start >= end: return mid = (start + end)//2 merge_sort(arr, start, mid) merge_sort(arr, mid+1, end) merge(arr, start, mid, end) def heap(arr, start, end): i = start j = 2 * i + 1 temp = arr[i] while i <= (end-1)//2: if j+1 <= end and arr[j] < arr[j+1]: arr[j], arr[j+1] = arr[j+1],arr[j] if temp < arr[j]: arr[i] = arr[j] else: arr[i] = temp break i = j j = 2 * i + 1 arr[i] = temp def heap_sort(arr, size): """堆排序""" for i in range((size-1)//2, -1, -1): heap(arr, i, size) for i in range(size, 0, -1): arr[0], arr[i] = arr[i], arr[0] heap(arr, 0, i-1) def run(): arr = list(range(10)) size = len(arr) random.shuffle(arr) print(arr) # bubble_sort(arr, size) # select_sort(arr, size) # insert_sort(arr, size) # quick_sort(arr, 0, size-1) # merge_sort(arr, 0, size-1) heap_sort(arr, size - 1) print(arr) if __name__ == "__main__": run()
false
33c05d544f56bec9699add58b0a26673d41e974a
shubee17/Algorithms
/Array_Searching/search_insert_delete_in_unsort_arr.py
1,239
4.21875
4
# Search,Insert and delete in an unsorted array import sys def srh_ins_del(Array,Ele): # Search flag = 0 for element in range(len(Array)): if Array[element] == int(Ele): flag = 1 print "Element Successfully Found at position =>",element + 1 break else: flag = 0 if flag == 0: print "Element Not Found!!! " else: pass #Insert print "\n" flag = 0 position = int(raw_input("Enter the position which you want to be Insert element => ")) Element = int(raw_input("Enter the element => ")) for element in range(len(Array)): if (element + 1) == int(position): flag = 1 Array[element] = int(Element) print "Element Successfully Inserted =>",Array break else: flag = 0 if flag == 0: print "Position Does'nt Exists!!!" else: pass #Delete print "\n" flag = 0 position = int(raw_input("Enter the position which you want to be Delete element => ")) for element in range(len(Array)): if (element + 1) == int(position): flag = 1 del(Array[element]) print "Element Successfully Deleted =>",Array break else: flag = 0 if flag == 0: print "Position Does'nt Exists!!! " else: pass Array = sys.argv[1] Array = map(int, Array) Ele = sys.argv[2] srh_ins_del(Array,Ele)
true
5aca9da4c1d5edc7ab40f828cdbf9cc81a79894d
Foxcat-boot/Python_ym
/python_01/py_11_字符串查找和替换.py
797
4.125
4
# 判断是否以某字符串开头 str1 = "str123 321" print(str1.startswith("str")) print(str1.startswith("Str")) """ ⬆此方法区分大小写 """ # 判断是否以某字符串结尾 str2 = "hu1 mao" print(str2.endswith("mao")) print(str2.endswith("Mao")) """ 同样区分大小写 """ # 查找字符串 str3 = "123humao321159 xhm" print(str3.find("159")) print(str3.find("1")) print(str3.find("zzz")) """ 查找第一个符合要求的字符串 第一位为0 与index最大的区别: find没有查找到返回-1 index没有查找到会报错 rfind 可以从右边开始查找 """ # 替换字符串 str4 = "zxc123 asdqwe1 159" print(str4.replace("123","369")) print(str4) """ replace会返回一个新的字符串 不会修改原来的字符串 """
false
9ab2e315097803b322a0c57f4e3f33ee165807c9
Olishevko/HomeWork1
/operators.py
466
4.53125
5
# Арифметические операторы # + - * / % ** // #print(2+5) #print(3-5) #print(5 / 2) #print(5 // 2) #print(6 % 3) #print(6 % 5) #print(5 ** 2) #number = 3 + 4 * 5 ** 2 +7 #print(number) # Операторы сравнения # == != > < >= <= #print(1 == 1) #print(1 == 2) #print('One' == 'ONE') #print('One' != 'ONE') # Операторы присваивания # = += -= *= /= #number = 10 #number = 10 + 7 #number += 7 print(number)
false
0bacac4830fb2e7fa4edef9892ac255a4eed721e
SoliDeoGloria31/study
/AID12 day01-16/day04/day03_exercise/delete_blank.py
283
4.1875
4
# 2. 输入一个字符串,把输入的字符串中的空格全部去掉,打印出处理 # 后的字符串的长度和字符串的内容 s = input("请输入字符串: ") s2 = s.replace(' ', '') print('替换后的长度是:', len(s2)) print('替换后的内容是:', s2)
false
567c6e083ddbe7de37c7fc2be8e2126062197326
SoliDeoGloria31/study
/AID12 day01-16/day08/exercise/print_even.py
351
4.125
4
# 练习2 # 写一个函数print_even,传入一个参数n代表终止的整数,打印 # 0 ~ n 之间所有的偶数 # 如: # def print_even(n): # ..... 此处自己完成 # print_even(10) # 打印: # 0 # 2 # 4 # 6 # 8 def print_even(n): for x in range(0, n+1, 2): print(x) print_even(10)
false
cecaa8ff2d1ce042a9da127173ef3e292676a426
SoliDeoGloria31/study
/AID12 day01-16/day09/day08_exercise/student_info.py
1,393
4.125
4
# 3. 改写之前的学生信息管理程序: # 用两个函数来封装功能的代码块 # 函数1: input_student() # 返回学生信息字典的列表 # 函数2: output_student(L) # 打印学生信息的表格 def input_student(): L = [] # 创建一个列表,准备存放学生数据的字典 while True: n = input("请输入姓名: ") if not n: # 如果用户输入空字符串就结束输入 break a = int(input("请输入年龄: ")) s = int(input("请输入成绩: ")) d = {} # 一定要每次都创建一个新的字典 d['name'] = n d['age'] = a d['score'] = s L.append(d) # 把d加入列表中L return L def output_student(L): print("+---------------+----------+----------+") print("| 姓名 | 年龄 | 成绩 |") print("+---------------+----------+----------+") for d in L: name = d['name'] age = str(d['age']) # 转为字符串 score = str(d['score']) # 转为字符串 print("|%s|%s|%s|" % (name.center(15), age.center(10), score.center(10))) print("+---------------+----------+----------+") infos = input_student() print(infos) # 打印列表[{...}, {...}] output_student(infos) # 根据实参infos打印表格
false
a67330c5dc0ad81a9fac382ec8fdcb5c310d5750
SoliDeoGloria31/study
/AID12 day01-16/day01/exercise/circle.py
376
4.25
4
# 练习: # 指定一个圆的半径为 r = 3 厘米 # 1) 计算此圆的周长是多少? # 2) 计算此圆的面积是多少? # 圆周率: 3.1415926 # 周长 = 圆周率 * 半径 * 2 # 面积 = 圆周率 * 半径 * 半径 r = 3 pi = 3.1415926 length = pi * r * 2 print("周长是:", length) area = pi * r * r # r ** 2 print("面积是:", area)
false
b1ec062d544dfb65fbd8f09e67bb03dce65aeef6
betta-cyber/leetcode
/python/208-implement-trie-prefix-tree.py
784
4.125
4
#!/usr/bin/env python # encoding: utf-8 class Trie(object): def __init__(self): self.root = {} def insert(self, word): p = self.root for c in word: if c not in p: p[c] = {} p = p[c] p['#'] = True def search(self, word): node = self.find(word) return node is not None and '#' in node def startsWith(self, prefix): return self.find(prefix) is not None def find(self, prefix): p = self.root for c in prefix: if c not in p: return None p = p[c] return p # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
true
919a37ba58267ffe921c2485b317baca4d2f33d9
garymale/python_learn
/Learn/Learn04.py
1,096
4.3125
4
#创建数值列表 #使用函数 range()可以生成一系列数字,打印1-4 for value in range(1,5): print(value) #range()创建数字列表,使用函数list()将range()的结果直接转换为列表 numbers = list(range(1,6)) print(numbers) #使用函数range()时,还可指定步长,下列步长为2 enen_numbers = list(range(2,11,2)) print(enen_numbers) #例:创建一个列表,其中包含前 10个整数(即1~10)的平方,在Python中,两个星号(**)表示乘方运算 squares = [] for value in range(1,11): square = value**2 squares.append(square) print(squares) print('------------------------------') #不使用临时变量square,简洁 squares = [] for value in range(1,11): squares.append(value**2) print(squares) #对数字列表执行简单的统计计算 digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] #最小元素 min(digits) #最大元素 max(digits) #求元素和 sum(digits) #*列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素 squares = [value**2 for value in range(1,11)] print(squares)
false