blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b5b8ad763c493b7e79cd419bdc08170b1a11dd58
TranshumanSoft/quotient-and-rest
/modulexercises.py
268
4.15625
4
fstnumber = float(input("Introduce a number:")) scndnumber = float(input("Introduce another number:")) quotient = fstnumber//scndnumber rest = fstnumber%scndnumber print(f"Between {fstnumber} and {scndnumber} there's a quotient of {quotient} and a rest of {rest}")
true
b227542479f4396cb317fbb2a42e79ad0d90da31
JhonattanDev/Exercicios-Phyton-29-07
/ex7.py
586
4.28125
4
import math # Pra explicar o programa print("Digite um valor abaixo para ver seu dobro, triplo, e raíz quadrada dele! \n") # Input para o usuário inserir o valor valor = int(input("Digite o valor: ")) # Aqui será realizados os cálculos que definirão as variáveis dobro = valor * 2 triplo = valor * 3 raizQuadrada = math.sqrt(valor) # Para pular uma linha print("") # Imprimir/mostrar o resultado do programa print("O valor digitado foi {}, sendo o seu dobro {}, seu triplo {}," " e sua raíz quadrada {}.".format(valor, dobro, triplo, raizQuadrada))
false
bd6b8a39bd376c6bcf9a3a56a4a70453159e05f4
baixianghuang/algorithm
/python3/merge_linked_lists.py
2,215
4.3125
4
class ListNode: def __init__(self, val): self.val = val self.next = None def merge_linked_lists_recursively(node1, node2): """"merge 2 sorted linked list into a sorted list (ascending)""" if node1 == None: return node2 elif node2 == None: return node1 new_head = None if node1.val >= node2.val: new_head = node2 new_head.next = merge_linked_lists_recursively(node1, node2.next) else: new_head = node1 new_head.next = merge_linked_lists_recursively(node1.next, node2) return new_head def merge_linked_lists(head1, head2): """"merge 2 sorted linked list into a sorted list (ascending)""" node1 = head1 node2 = head2 if node1 == None: return head2 elif node2 == None: return head1 if node1.val >= node2.val: head_tmp = node2 node2 = node2.next else: head_tmp = node1 node1 = node1.next node_tmp = head_tmp while node1 and node2: # print(node1.val, node2.val) if node1.val >= node2.val: # insert node2 after head_new node_tmp.next = node2 node_tmp = node2 node2 = node2.next else: # insert node1 after head_new node_tmp.next = node1 node_tmp = node1 node1 = node1.next if node1 != None: while node1 != None: node_tmp.next = node1 node_tmp = node_tmp.next node1 = node1.next elif node2 != None: while node2 != None: node_tmp.next = node2 node_tmp = node_tmp.next node2 = node2.next return head_tmp # list 1: 1 -> 3 -> 5 # list 2: 2 -> 4 -> 6 node_1 = ListNode(1) node_2 = ListNode(2) node_3 = ListNode(3) node_4 = ListNode(4) node_5 = ListNode(5) node_6 = ListNode(6) node_1.next = node_3 node_3.next = node_5 node_2.next = node_4 node_4.next = node_6 test1 = merge_linked_lists(node_1, node_2) while test1: print(test1.val, " ", end="") test1 = test1.next print() # test2 = merge_linked_lists_recursively(node_1, node_2) # while test2: # print(test2.val, " ", end="") # test2 = test2.next
true
56bb2d591702c721ed9891e9c60e2fabb0cf80ff
danmorales/Python-Pandas
/pandas-ex19.py
358
4.125
4
import pandas as pd array = {'A' : [1,2,3,4,5,4,3,2,1], 'B' : [5,4,3,2,1,2,3,4,5], 'C' : [2,4,6,8,10,12,14,16,18]} df_array = pd.DataFrame(data=array) print("Arranjo original") print(df_array) print("\n") print("Removendo linhas cuja coluna B tenha valores iguais a 3") df_array_new = df_array[df_array.B != 3] print("Novo arranjo") print(df_array_new)
false
96133f56fdadf80059d2b548a3ae485dee91f770
suhaslucia/Pythagoras-Theorem-in-Python
/Pythagoras Theorem.py
1,114
4.40625
4
from math import sqrt #importing math package print(" ----------Pythagoras Theorem to Find the sides of the Triangle---------- ") print(" ------------ Enter any one side as 0 to obtain the result -------------- ") # Taking the inputs as a integer value from the user base = int(input("Enter the base of the Triangle: ")) perpendicular = int(input("Enter the perpendicular of the Triangle: ")) hypotenuse = int(input("Enter the hypotenuse of the Triangle: ")) # Calculating the Hypotenuse value and printing it if hypotenuse == 0: b = base ** 2 p = perpendicular ** 2 hyp = b + p result = sqrt(hyp) print(f'\n Hypotenuse of Triangle is {result}') # Calculating the Perpendicular value and printing it elif perpendicular == 0: b = base ** 2 hyp = hypotenuse ** 2 p = hyp - b result = sqrt(p) print(f'\n Perpendicular of Triangle is {result}') # Calculating the Base value and printing it else: p = perpendicular ** 2 hyp = hypotenuse ** 2 b = hyp - p result = sqrt(b) print(f'\n Base of Triangle is {result}')
true
68e32356ee24ab2bbfc87c4ca3508e89eacd3a0b
Kumar1998/github-upload
/scratch_4.py
397
4.25
4
d1={'Canada':100,'Japan':200,'Germany':300,'Italy':400} #Example 1 Print only keys print("*"*10) for x in d1: print(x) #Example 2 Print only values print ("*"*10) for x in d1: print(d1[x]) #Example 3 Print only values print ("*"*10) for x in d1.values(): print(x) #Example 4 Print only keys and values print ("*"*10) for x,y in d1.items(): print(x,"=>",y)
true
f38bd5b4882bd3787e78bcb653ca07d48b1f7093
Kumar1998/github-upload
/python1.py
573
4.3125
4
height=float(input("Enter height of the person:")) weight=float(input("Enter weight of the person:")) # the formula for calculating bmi bmi=weight/(height**2) print("Your BMI IS:{0} and you are:".format(bmi),end='') #conditions if(bmi<16): print("severly underweight") elif(bmi>=16 and bmi<18.5): print("underweight") elif(bmi>=18.5 and bmi>=25): print("underweight") elif(bmi>=18.5 and bmi<25): print("healthy") elif(bmi>=25 and bmi<30): print("overweight") elif(bmi>=30): print("severly overweight") import time time.sleep(30)
true
98f763bd336731f8fa0bd853d06c059dd88d8ca7
septhiono/redesigned-meme
/Day 2 Tip Calculator.py
316
4.1875
4
print('Welcome to the tip calculator') bill = float(input('What was the total bill? $')) tip= float(input('What percentage tip would you like to give? ')) people = float(input("How many people split the bill? ")) pay= bill*(1+tip/100)/people pay=float(pay) print("Each person should pay: $",round(pay,2))
true
fea4e23725b61f8dd4024b2c52065870bbba6da1
rugbyprof/4443-2D-PyGame
/Resources/R02/Python_Introduction/PyIntro_05.py
548
4.15625
4
# import sys # import os # PyInto Lesson 05 # Strings # - Functions # - Input from terminal # - Formatted Strings name = "NIKOLA TESLA" quote = "The only mystery in life is: why did Kamikaze pilots wear helmets?" print(name.lower()) print(name.upper()) print(name.capitalize()) print(name.title()) print(name.isalpha()) print(quote.find('Kamikaze')) print(quote.find('Kamikazsdfe')) new_name = input("Please enter a name: ") print(new_name) print(len(quote)) print(f"Hello {new_name}, you owe me 1 million dollars!") print(f"{quote.strip('?')}")
true
79d70dca2e86013310ae0691b9a8e731d26e2e75
nidhinp/Anand-Chapter2
/problem36.py
672
4.21875
4
""" Write a program to find anagrams in a given list of words. Two words are called anagrams if one word can be formed by rearranging letters to another. For example 'eat', 'ate' and 'tea' are anagrams. """ def sorted_characters_of_word(word): b = sorted(word) c = '' for character in b: c += character return c def anagram(list_of_words): a = {} for word in list_of_words: sorted_word = sorted_characters_of_word(word) if sorted_word not in a: d = [] d.append(word) a[sorted_word] = d else: d = a[sorted_word] d.append(word) a.update({sorted_word:d}) print a.values() anagram(['eat', 'ate', 'done', 'tea', 'soup', 'node'])
true
a1b103fb6e85e3549090449e71ab3908a46b2e9c
nidhinp/Anand-Chapter2
/problem29.py
371
4.25
4
""" Write a function array to create an 2-dimensional array. The function should take both dimensions as arguments. Value of element can be initialized to None: """ def array(oneD, twoD): return [[None for x in range(twoD)] for x in range(oneD)] a = array(2, 3) print 'None initialized array' print a a[0][0] = 5 print 'Modified array' print a
true
4cbcb6d66ee4b0712d064c9ad4053456e515b14b
SandipanKhanra/Sentiment-Analysis
/tweet.py
2,539
4.25
4
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] #This function is used to strip down the unnecessary characters def strip_punctuation(s): for i in s: if i in punctuation_chars: s=s.replace(i,"") return s # lists of words to use #As part of the project this hypothetical .txt file was given positive_words = [] with open("positive_words.txt") as pos_f: for lin in pos_f: if lin[0] != ';' and lin[0] != '\n': positive_words.append(lin.strip()) #This function returns number of positive words in the tweet def get_pos(s): count=0 s=s.lower() x=[] x=s.split() for i in x: i=strip_punctuation(i) if i in positive_words: count+=1 return count #As part of the project this hypothetical .txt file was given negative_words = [] with open("negative_words.txt") as pos_f: for lin in pos_f: if lin[0] != ';' and lin[0] != '\n': negative_words.append(lin.strip()) #This function returns number of negitive words in the tweet def get_neg(s): count=0 s=s.lower() x=[] x=s.split() for i in x: i=strip_punctuation(i) if i in negative_words: count+=1 return count #This hypothetical .csv file containing some fake tweets was given for analysi filedName = None file = open("project_twitter_data.csv") lines = file.readlines() fieldName = lines[0].strip().split(',') #print(fieldName) '''here we are iterating over each line, considering only the tweet then processing it with the previous functions storing positive word count, negative word count, net score(how much positiive or negative) ''' ans = [] for line in lines[1:]: tweet= line.strip().split(',') tempTweet = strip_punctuation(tweet[0]) posCount = get_pos(tempTweet) negCount = get_neg(tempTweet) net = posCount - negCount #Making a tuple containing Number of retweets,number of replies,posCount,negCount,Net score t = (int(tweet[1]),int(tweet[2]),posCount,negCount,net) ans.append(t) #print(ans[4]) #Making the header of the new csv file outputHeader = "{},{},{},{},{}".format('Number of Retweets','Number of Replies', 'Positive Score','Negative Score','Net Score') #writing data in the new csv file output = open('resulting_data.csv','w') output.write(outputHeader) output.write('\n') for i in ans: raw = '{},{},{},{},{}'.format(i[0],i[1],i[2],i[3],i[4]) output.write(raw) output.write('\n')
true
8c79d7caeb39a173173de7e743a8e2186e2cfc0a
osirisgclark/python-interview-questions
/TCS-tataconsultancyservices2.py
344
4.46875
4
""" For this list [1, 2, 3] return [[1, 2, 3], [2, 4, 6], [3, 6, 9]] """ list = [1, 2, 3] list1 = [] list2 = [] list3 = [] for x in range(1, len(list)+1): list1.append(x) list2.append(2*x) list3.append(3*x) print([list1, list2, list3]) """ Using List Comprehensions """ print([[x, 2*x, 3*x] for x in range(1, len(list)+1)])
true
7cc58e0ee75580bc78c260832e940d0fd07b9e2a
minerbra/Temperature-converter
/main.py
574
4.46875
4
""" @Author: Brady Miner This program will display a temperature conversion table for degrees Celsius to Fahrenheit from 0-100 degrees in multiples of 10. """ # Title and structure for for table output print("\nCelsius to Fahrenheit") print("Conversion Table\n") print("Celsius\t Fahrenheit") for celsius in range(0, 101, 10): # loop degrees celsius from 0 to 100 in multiples of 10 fahrenheit = (celsius * 9 / 5) + 32 # Formula to convert celsius to fahrenheit print("{}\t\t {}".format(celsius, round(fahrenheit))) # Format the data to display in the table
true
ec2ffda93473b99c06258761740065801e017162
saimkhan92/data_structures_python
/llfolder1/linked_list_implementation.py
1,445
4.28125
4
# add new node in the front (at thr root's side) import sys class node(): def __init__(self,d=None,n=None): self.data=d self.next=n class linked_list(node): def __init__(self,r=None,l=0): self.length=l self.root=r def add(self,d): new_node=node() new_node.data=d if (self.root==None): self.root=new_node new_node.next=None self.length=1 else: self.length+=1 new_node.next=self.root self.root=new_node def display(self): i=self.root while i: print(str(i.data)+" --> ",end="") i=i.next print("None") def delete(self,i): if self.root.data==i: self.root=self.root.next else: current_node=self.root.next previous_node=self.root while current_node: if current_node.data==i: previous_node.next=current_node.next return True print(2) else: previous_node=current_node current_node=current_node.next print("3") #lnk=linked_list() #lnk.add(10) #lnk.add(20) #lnk.add(30) #lnk.add(25) #lnk.display() #lnk.delete(30) #lnk.display()
true
d7fb7ba1b47eb9787dc45de53dd221d75d52a05f
catterson/python-fundamentals
/challenges/02-Strings/C_interpolation.py
1,063
4.78125
5
# Lastly, we'll see how we can put some data into our strings # Interpolation ## There are several ways python lets you stick data into strings, or combine ## them. A simple, but very powerful approach is to us the % operator. Strings ## can be set up this way to present a value we didn't know when we defined the ## string! s = 'this string is %d characters long' ## We can apply values to a string with an expression that goes: ## string % value(s) ## if there's more than one, put them in ()'s with commas between! ## Go ahead and compute the length of s and substitute it into the string: d = len(s) print s%d # conversion ## Adding a string and a number together doesn't make sense... for example, ## what's the right thing to do for '1.0' + 2? Let's explore both ways that ## could go. First, we need to do the conversion ourselves. Remember, you can ## use the type functions to do that, in this case, str() and float() - int() ## would lose the decimal point that is clearly there for a reason! print '1.0' + str(2) print float('1.0') + float(2)
true
7d2beba8951d3f799ebd1bdfce8cc7fc5dceac65
NataliVynnychuk/Python_Hillel_Vynnychuk
/Lesson/Lesson 9 - 17.07.py
1,655
4.25
4
# Стандартные библиотеки python # Функции, область видимости, параметры, параметры по умолчанию, типизация import string import random # import random as rnd # print(string.ascii_lowercase) value = random.randint(10, 20) my_list = [1, 2, 3, 10, 20, 30] # my_list = [True, False] my_str = 'qwerty' choice_from_list = random.choice(my_str) print(value, choice_from_list) from random import randint, choice my_str = 'qwerty' choice_from_list = choice(my_str) value = randint(100, 200) print(value, choice_from_list) new_list = random.shuffle(my_list) #стандартная ошибка!!! print(new_list) new_list = my_list.copy() #shuffle меняет объект!!! поэтому нужен copy random.shuffle(new_list) print(my_list, new_list) ######################################################################## #Dry point_A = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_B = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_C = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} triangle_ABC = {"A": point_A, "B": point_B, "C": point_C} print(triangle_ABC) point_M = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_N = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_K = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} triangle_MNK = {"M": point_M, "N": point_N, "K": point_K} print(triangle_MNK)
false
dc0755a55ce75ca7b9b98acb9d32c4c04663b834
glennlopez/Python.Playground
/SANDBOX/python3/5_loops_branches/break_continue.py
332
4.28125
4
starting = 0 ending = 20 current = starting step = 6 while current < ending: if current + step > ending: # breaks out of loop if current next step is larger than ending break if current % 2: # skips the while loop if number is divisible by 2 continue current += step print(current)
true
4f619614442506f1567eb9ecc0de6c989f0c2c21
ashburnere/data-science-with-python
/python-for-data-science/1-2-Strings.py
2,344
4.28125
4
'''Table of Contents What are Strings? Indexing Negative Indexing Slicing Stride Concatenate Strings Escape Sequences String Operations ''' # Use quotation marks for defining string "Michael Jackson" # Use single quotation marks for defining string 'Michael Jackson' # Digitals and spaces in string '1 2 3 4 5 6 ' # Special characters in string '@#2_#]&*^%$' # Assign string to variable name = "Michael Jackson" print(name, "length:", len(name)) # Print the first element in the string --> M print(name[0]) # Print the last element in the string --> n print(name[len(name)-1]) # Print the element on index 6 in the string --> l print(name[6]) # Print the element on the 13th index in the string --> o print(name[13]) # Print the last element in the string by using negativ indexing --> n print(name[-1]) # Print the first element in the string by using negativ indexing --> M print(name[-len(name)]) # Take the slice on variable name with only index 0 to index 3 --> Mich print(name[0:4]) # Take the slice on variable name with only index 8 to index 11 --> Jack print(name[8:12]) # Stride: Get every second element. The elments on index 0, 2, 4 ... print(name[::2]) # Stride: Get every second element in the range from index 0 to index 4 --> Mca print(name[0:5:2]) # Concatenate two strings statement = name + " is the best" print(statement) # Print the string for 3 times print(3*statement) # New line escape sequence print(" Michael Jackson \n is the best" ) # Tab escape sequence print(" Michael Jackson \t is the best" ) # Include back slash in string print(" Michael Jackson \\ is the best" ) # r will tell python that string will be display as raw string print(r" Michael Jackson \ is the best" ) ''' String operations ''' # Convert all the characters in string to upper case A = "Thriller is the sixth studio album" print("before upper:", A) B = A.upper() print("After upper:", B) # Replace the old substring with the new target substring is the segment has been found in the string A = "Michael Jackson is the best" B = A.replace('Michael', 'Janet') # Find the substring in the string. Only the index of the first elment of substring in string will be the output name = "Michael Jackson" # --> 5 print(name.find('el')) # If cannot find the substring in the string -> result is -1 print(name.find('Jasdfasdasdf'))
true
d86edccc25b0e5e6aebddb9f876afd3219c58a65
ashburnere/data-science-with-python
/python-for-data-science/4-3-Loading_Data_and_Viewing_Data_with_Pandas.py
2,038
4.25
4
'''Table of Contents About the Dataset Viewing Data and Accessing Data with pandas ''' '''About the Dataset The table has one row for each album and several columns artist - Name of the artist album - Name of the album released_year - Year the album was released length_min_sec - Length of the album (hours,minutes,seconds) genre - Genre of the album music_recording_sales_millions - Music recording sales (millions in USD) on SONG://DATABASE claimed_sales_millions - Album's claimed sales (millions in USD) on SONG://DATABASE date_released - Date on which the album was released soundtrack - Indicates if the album is the movie soundtrack (Y) or (N) rating_of_friends - Indicates the rating from your friends from 1 to 10 ''' import pandas as pd # read from file csv_path='D:/WORKSPACES/data-science-with-python/resources/data/top_selling_albums.csv' # read from url #csv_path='https://ibm.box.com/shared/static/keo2qz0bvh4iu6gf5qjq4vdrkt67bvvb.csv' df = pd.read_csv(csv_path) # We can use the method head() to examine the first five rows of a dataframe: print("top 5 rows\n", df.head()) #We use the path of the excel file and the function read_excel. The result is a data frame as before: # xlsx_path='https://ibm.box.com/shared/static/mzd4exo31la6m7neva2w45dstxfg5s86.xlsx' # df = pd.read_excel(xlsx_path) #df.head() # We can access the column "Length" and assign it a new dataframe 'x': x=df[['Length']] print(x) ''' Viewing Data and Accessing Data ''' # You can also assign the value to a series, you can think of a Pandas series as a 1-D dataframe. Just use one bracket: x=df['Length'] print(type(x)) # You can also assign different columns, for example, we can assign the column 'Artist': x=df[['Artist']] print(type(x)) y=df[['Artist','Length','Genre']] print(type(y)) # print value of first row first column print(df.iloc[0,0]) # --> Michael Jackson print(df.loc[0,'Artist']) # --> Michael Jackson # slicing print(df.iloc[0:2, 0:3]) print(df.loc[0:2, 'Artist':'Released'])
true
29383e08c12d57b53c61ae628026cb065957f9b7
anucoder/Python-Codes
/04_dictionaries.py
513
4.34375
4
my_stuff = {"key1" : "value1", "key2" : "value2"} print(my_stuff["key2"]) print(my_stuff) #maintains no order #multiple datatype with nested dictionaries and lists my_dict = {"key1" : 123, "key2" : "value2", "key3" : {'123' : [1,2,"grabme"]}} print(my_dict["key3"]['123'][2]) #accessing grabme print((my_dict["key3"]['123'][2]).upper()) #reassigning dictionaries my_diet = {'bfast' : "milk" , "lunch" : "oats"} my_diet['lunch'] = 'pizza' print(my_diet) #appending my_diet["dinner"] = "salad" print(my_diet)
false
a016c597b8fc5f70e2ab5d861b756d347282289d
jourdy345/2016spring
/dataStructure/2016_03_08/fibonacci.py
686
4.125
4
def fib(n): if n <= 2: return 1 else: return fib(n - 1) + fib(n - 2) # In python, the start of a statement is marked by a colon along with an indentation in the next line. def fastFib(n): a, b = 0, 1 for k in range(n): a, b = b, a+b # the 'a' in the RHS is not the one in the RHS. Python distinguishes LHS from RHS and does not mix them up. return a # For n = 1, the slower version of fib function is actually faster than the faster one. # In small values of n, the comparison between two functions is actually not revealing as much as we would expect it to be. # Thus, we introduce a new concept O(n) ("Big oh"): asymptotic time complexity. print(fastFib(45))
true
be9b1b682cc8b1f6190fead9c3441ce72f512cf4
Nathan-Dunne/Twitter-Data-Sentiment-Analysis
/DataFrameDisplayFormat.py
2,605
4.34375
4
""" Author: Nathan Dunne Date last modified: 16/11/2018 Purpose: Create a data frame from a data set, format and sort said data frame and display data frame as a table. """ import pandas # The pandas library is used to create, format and sort a data frame. # BSD 3-Clause License # Copyright (c) 2008-2012, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development from tabulate import tabulate # The tabulate library is used to better display the pandas data frame as a table. # MIT License Copyright (c) 2018 Sergey Astanin class DataFrameDisplayFormat: def __init__(self): pass # There is nothing to initialise so pass is called here. The pass statement is a null operation. @staticmethod # Method is static as it alters no values of the self object. def convertDataSetToDataFrame(data_set): """ Convert a data set to a pandas data frame. """ data_frame = pandas.DataFrame(data_set) # Convert the data set (List of dictionaries) to a pandas data frame. return data_frame @staticmethod # Method is static as it alters no values of the self object. def formatDataFrame(data_frame): """ Format and sort a data frame. """ data_frame = data_frame[['favorite_count', # Order and display only these three columns. 'retweet_count', 'text', ]] print("\nSorting data by 'favorite_count', 'retweet_count', descending.") # Sort the rows first by favorite count and then by retweet count in descending order. data_frame = data_frame.sort_values(by=['favorite_count', 'retweet_count'], ascending=False) return data_frame @staticmethod # Method is static as it neither accesses nor alters any values or behaviour of the self object. def displayDataFrame(data_frame, amount_of_rows, show_index): """ Display a data frame in table format using tabulate. """ # Print out an amount of rows from the data frame, possibly with showing the index, with the headers as the # data frame headers using the table format of PostgreSQL. # Tabulate can't display the word "Index" in the index column so it is printed out right before the table. print("\nIndex") print(tabulate(data_frame.head(amount_of_rows), showindex=show_index, headers=data_frame.columns, tablefmt="psql"))
true
8eba1f38d3e13306076467af0694dc65f7d6ed7f
englernicolas/ADS
/python/aula3-extra.py
1,934
4.1875
4
def pesquisar(nome) : if(nome in listaNome) : posicao = listaNome.index(nome) print("------------------------------") print("Nome: ", listaNome[posicao], listaSobrenome[posicao]) print("Teefone: ",listaFone[posicao]) print("-------------------------") else: print("-------------------------") print("Pessoa não encontrada") print("-------------------------") def excluir(nome): if(nome in listaNome) : posicao = listaNome.index(nome) listaNome.pop(posicao) listaSobrenome.pop(posicao) listaFone.pop(posicao) print("Exluido com sucesso!") else: print("-----------------------") print("Pessoa não encontrada") print("-----------------------") def listar(): for item in range(0, len(listaNome)): print("-----------------------") print( "Nome: ", listaNome[item, listaSobrenome[item]]) print("-----------------------") listaNome = [] listaSobrenome = [] listaFone = [] while True: print(" 1 - Cadastrar") print(" 2 - Pesquisar") print(" 3 - Excluir") print(" 4 - Listar todos") op = int(input("Digide a opção desejada: ")) if(op == 1): nome = input("Informe o Nome: ") sobrenome = input("Informe o Sobrenome: ") fone = input("Informe o Telefone: ") listaNome.append(nome) listaSobrenome.append(sobrenome) listaFone.append(fone) print("-----------------------") print("Cadastrado com Sucesso!") print("-----------------------") else: if(op == 2): pesquisa = input("Informe o nome a pesquisar: ") pesquisar(pesquisa) else: if(op == 3): pesquisa = input("Informe o nome a excluir: ") excluir(pesquisa) else: if(op == 4): listar()
false
aa5511e07cc866babfcd2ee3c7f7d6149ba1b740
520Coder/Python-Programming-for-Beginners-Hands-on-Online-Lab-
/Section 6/Student Resources/Assignment Solution Scripts/assignment_lists_02_solution_min_max.py
308
4.21875
4
# Lists # Assignment 2 numbers = [10, 8, 4, 5, 6, 9, 2, 3, 0, 7, 2, 6, 6] min_item = numbers[0] max_item = numbers[0] for num in numbers: if min_item > num: min_item = num if max_item < num: max_item = num print("Minimum Number : ", min_item) print("Maximum Number : ", max_item)
false
bfd6a6a1ce1a215bd6e698e732194b26fd0ec7b4
tjnelson5/Learn-Python-The-Hard-Way
/ex15.py
666
4.1875
4
from sys import argv # Take input from command line and create two string variables script, filename = argv # Open the file and create a file object txt = open(filename) print "Here's your file %r:" % filename # read out the contents of the file to stdout. This will read the whole # file, because the command ends at the EOF character by default print txt.read() # always close the file - like gates in a field! txt.close() # create a new string variable from the prompt print "Type the filename again:" file_again = raw_input("> ") # Create a new file object for this new file txt_again = open(file_again) # Same as above print txt_again.read() txt.close()
true
6b9281109f10fd0d69dfc54ce0aa807f9592109a
xy008areshsu/Leetcode_complete
/python_version/intervals_insert.py
1,267
4.125
4
""" Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. """ # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: # @param intervals, a list of Intervals # @param newInterval, a Interval # @return a list of Interval def insert(self, intervals, newInterval): if len(intervals) == 0: return [newInterval] intervals.append(newInterval) intervals.sort(key=lambda x: x.start) res = [intervals[0]] for i in range(1, len(intervals)): if intervals[i].start <= res[-1].end: # here needs <= instead of <, e.g. [1, 3], and [3, 5] should be merged into [1, 5] res[-1].end = max(res[-1].end, intervals[i].end) else: res.append(intervals[i]) return res
true
7e3a1b29b321ff31e6e635d825ddcfb1668aeb5c
xy008areshsu/Leetcode_complete
/python_version/dp_unique_path.py
1,531
4.15625
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 3 x 7 grid. How many possible unique paths are there? Note: m and n will be at most 100. """ class Solution: # @return an integer def uniquePaths(self, m, n): unique_paths_number = {} unique_paths_number[(0, 0)] = 1 unique_paths_number.update({(0, i) : 1 for i in range(n)}) unique_paths_number.update({(i, 0) : 1 for i in range(m)}) return self.solve(unique_paths_number, m - 1, n - 1) def solve(self, unique_paths_number, m, n): if m == 0 or n == 0: unique_paths_number[(m, n)] = 1 return 1 if (m - 1, n) in unique_paths_number: unique_paths_number_m_1_n = unique_paths_number[(m-1, n)] else: unique_paths_number_m_1_n = self.solve(unique_paths_number, m - 1, n) if (m, n - 1) in unique_paths_number: unique_paths_number_m_n_1 = unique_paths_number[(m, n - 1)] else: unique_paths_number_m_n_1 = self.solve(unique_paths_number, m , n - 1) unique_paths_number_m_n = unique_paths_number_m_1_n + unique_paths_number_m_n_1 unique_paths_number[(m, n)] = unique_paths_number_m_n return unique_paths_number_m_n
true
c20802ed076df2adc4c4b430f6761742487d37a7
samluyk/Python
/GHP17.py
900
4.46875
4
# Step 1: Ask for weight in pounds # Step 2: Record user’s response weight = input('Enter your weight in pounds: ') # Step 3: Ask for height in inches # Step 4: Record user’s input height = input('Enter your height in inches: ') # Step 5: Change “string” inputs into a data type float weight_float = float(weight) height_float = float(height) # Step 6: Calculate BMI Imperial (formula: (5734 weight / (height*2.5)) BMI = (5734 * weight_float) / (height_float**2.5) # Step 7: Display BMI print("Your BMI is: ", BMI) # Step 8: Convert weight to kg (formula: pounds * .453592) weight_kg = weight_float * .453592 # Step 9: Convert height to meters (formula: inches * .0254) height_meters = height_float * .0254 # Step 10: Calculate BMI Metric (formula: 1.3 * weight / height** 2.5 BMI = 1.3 * weight_kg / height_meters**2.5 # Step 11: Display BMI print("Your BMI is: ", BMI) # Step 12: Terminate
true
0448e9274de805b9dec8ae7689071327677a6abb
wxhheian/hpip
/ch7/ex7_1.py
641
4.25
4
# message = input("Tell me something, and I will repeat it back to you: ") # print(message) # # name = input("Please enter your name: ") # print("Hello, " + name + "!") # prompt = "If you tell us who you are,we can personalize the messages you see." # prompt += "\nWhat is your first name? " # # name = input(prompt) # print("\nHello, " + name + "!") # age = input("How old are you? ") # print(int(age)>= 18) number = input("Enter a number, and I'll tell you if it's even or odd:") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even") else: print("\nThe number " + str(number) + " is odd.")
true
856461a845a16813718ace33b8d2d5782b0d7914
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_3.py
1,891
4.40625
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.3 Description: A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome. The following are functions that take a string argument and return the first, last, and middle letters: def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] We’ll see how they work in Chapter 8. 1) Type these functions into a file named palindrome.py and test them out. What happens if you call middle with a string with two letters? One letter? What about the empty string, which is written '' and contains no letters? 2) Write a function called is_palindrome that takes a string argument and returns True if it is a palindrome and False otherwise. Remember that you can use the built-in function len to check the length of a string. """ from palindrome import * def is_palindrome(word): if len(word) <= 1: return True elif first(word) == last(word): return is_palindrome(middle(word)) else: return False print(first('Hello')) # H print(middle('Hello')) # ell print(last('Hello')) # o # What happens if you call middle with a string with two letters? print(middle('ab')) # empty string is returned # One letter? print(middle('a')) # empty string is returned # What about the empty string, which is written '' and contains no letters? print(middle('')) # empty string is returned print('Are palindromes?:') print('noon', is_palindrome('noon')) # Yes print('redivider', is_palindrome('redivider')) # Yes print('a', is_palindrome('a')) # Yes print('empty string', is_palindrome('')) # Yes print('night', is_palindrome('night')) # No print('word', is_palindrome('word')) # No
true
6ffba84aafcdb3a4491c8268cba8ea1e2adfdf1e
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_2.py
951
4.3125
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.2 Description: The Ackermann function, A(m,n), is defined: n + 1 if m = 0 A(m,n) = A(m-1, 1) if m > 0 and n = 0 A(m-1, A(m,n-1)) if m > 0 and n > 0 See http://en.wikipedia.org/wiki/Ackermann_function. Write a function named ack that evaluates the Ackermann function. Use your function to evaluate ack(3, 4), which should be 125. What happens for larger values of m and n? """ def ack(m, n): if m < 0 or n < 0: print('ack function called with invalid input, only positive integers are valid') return elif m == 0: return n + 1 elif n == 0: return ack(m-1, 1) else: return ack(m-1, ack(m, n-1)) print(ack(3, 4)) # 125 print(ack(1, 2)) # 4 print(ack(4, 3)) # RecursionError # For larger values of m and n python can proceed the operation because # the number of allow recursion call is exceeded
true
508a885f71292a801877616a7e8132902d1af6c5
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_4.py
643
4.3125
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.4 Description: A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case. """ def is_power(a, b): """Check if a integer 'a' is a power of a integer 'b'""" if a == 1 or a == b: # base case return True elif a % b != 0: return False else: return is_power(a / b, b) print(is_power(2,2)) # True print(is_power(1,2)) # True print(is_power(8,2)) # True print(is_power(9,2)) # False
true
8c5faf13fe2952f33dd45000bf56e87bd1a0747e
Shubham1304/Semester6
/ClassPython/4.py
711
4.21875
4
#31st January class #string operations s='hello' print (s.index('o')) #exception if not found #s.find('a') return -1 if not found #------------------check valid name------------------------------------------------------------------------------------- s='' s=input("Enter the string") if(s.isalpha()): print ("Valid name") else : print ("Not a valid name") #--------------------check a palindrome---------------------------------------------------------------------------------- s=input ("Enter a number") r=s[::-1] if r==s: print ("It is a palindrome") else: print("It is not a palindrome") s='abba' print (s.index('a')) s = input ("Enter the string") while i<len(s): if (s.isdigit()): if(
true
b896f3577f80daaf46e56a70b046aecacf2288cb
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
/17.py
718
4.375
4
''' Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored. ''' def palindrome(x): l=[] for i in x: if i.isalpha(): l.append(i.lower()) print ''.join(l) if l==l[::-1]: print 'palindrome' else: print 'Not a palindrome' palindrome("Go hang a salami I'm a lasagna hog.")
true
f18204d3dab48280b29808613a3e039eab72ec4b
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
/22.py
2,488
4.125
4
''' In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary: key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you will be able to read the following secret message: Pnrfne pvcure? V zhpu cersre Pnrfne fnynq! Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English. ''' def rot_decoder(x): new =[] d = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} for i in x: new.append(d.get(i,i)) print ''.join(new) rot_decoder('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!') # Our decoder function can also encode the message since we have 26 characters. But in case if isn't you can use below strategy. def rot_encoder(x): key_inverse = { v:k for k,v in d.items()} for i in x: new.append(d.get(i,i)) print ''.join(new) rot_decoder('Caesar cipher? I much prefer Caesar salad!')
false
40589034a276810b9b22c31ca519399df66bd712
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
/02.py
277
4.125
4
''' Define a function max_of_three() that takes three numbers as arguments and returns the largest of them. ''' def max_of_three(a,b,c): if a>b and a>c: print a elif b>c and b>a: print b else: print c print max_of_three(0,15,2)
true
fc24e9ff6df3c2d766e719892fae9426e33f81f6
Isonzo/100-day-python-challenge
/Day 8/prime_number_checker.py
460
4.15625
4
def prime_checker(number): if number == 0 or number == 1: print("This number is neither prime nor composite") return prime = True for integer in range(2, number): if number % integer == 0: prime = False break if prime: print("It's a prime number") else: print("It's not a prime number") n = int(input("Check this number: ")) prime_checker(number=n)
true
133c061729e061076793a84878ad0cb4347fc016
M0673N/Programming-Fundamentals-with-Python
/exam_preparation/final_exam/05_mock_exam/03_problem_solution.py
1,713
4.15625
4
command = input() map_of_the_seas = {} while not command == "Sail": city, population, gold = command.split("||") if city not in map_of_the_seas: map_of_the_seas[city] = [int(population), int(gold)] else: map_of_the_seas[city][0] += int(population) map_of_the_seas[city][1] += int(gold) command = input() command_2 = input() while not command_2 == "End": command_2 = command_2.split("=>") if command_2[0] == "Plunder": city = command_2[1] people = int(command_2[2]) gold = int(command_2[3]) map_of_the_seas[city][0] -= people map_of_the_seas[city][1] -= gold print(f"{city} plundered! {gold} gold stolen, {people} citizens killed.") if map_of_the_seas[city][0] <= 0 or map_of_the_seas[city][1] <= 0: print(f"{city} has been wiped off the map!") map_of_the_seas.pop(city) elif command_2[0] == "Prosper": city = command_2[1] gold = int(command_2[2]) if gold < 0: print("Gold added cannot be a negative number!") else: map_of_the_seas[city][1] += gold print(f"{gold} gold added to the city treasury. {city} now has {map_of_the_seas[city][1]} gold.") command_2 = input() if len(map_of_the_seas) == 0: print("Ahoy, Captain! All targets have been plundered and destroyed!") else: map_of_the_seas = dict(sorted(map_of_the_seas.items(), key=lambda x: (-x[1][1], x[0]))) print(f"Ahoy, Captain! There are {len(map_of_the_seas)} wealthy settlements to go to:") for city in map_of_the_seas: print(f"{city} -> Population: {map_of_the_seas[city][0]} citizens, Gold: {map_of_the_seas[city][1]} kg")
false
ba8907050af53baa67dcbbaba314ab151ea20d41
M0673N/Programming-Fundamentals-with-Python
/04_functions/exercise/04_odd_and_even_sum.py
261
4.28125
4
def odd_even_sum(num): odd = 0 even = 0 for digit in num: if int(digit) % 2 == 0: even += int(digit) else: odd += int(digit) print(f"Odd sum = {odd}, Even sum = {even}") num = input() odd_even_sum(num)
false
6e8ac25e465a4c45f63af8334094049c0b660c4b
IrisCSX/LeetCode-algorithm
/476. Number Complement.py
1,309
4.125
4
""" Promblem: Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. Note: 任何二进制数和1111按位异都是该数字的互补数字 比如 (101)表示5 (111) (010)得到5的互补数字是3 算法: 1.得到与n的位数相同的1111 2.与1111取异 """ def numComplement(n): # 1.得到与n的二进制位数相同的111 lenth = len(bin(n))-2 compareN = 2 ** lenth -1 # 2.让111与数字n取异 complementN = compareN ^ n return complementN def numComplement2(num): i = 1 while i <= num: i = i << 1 return (i - 1) ^ num def test(): n = 8 m = numComplement2(n) print(bin(n),"的互补的二进制数是:",bin(m)) if __name__ == '__main__': test()
true
124f02540d0b7712a73b5d2e2e03868ac809b791
anikaator/CodingPractice
/Datastructures/HashMap/Basic/Python/main.py
687
4.15625
4
def main(): # Use of dict contacts = {} contacts['abc'] = 81 contacts['pqr'] = 21 contacts['xyz'] = 99 def print_dict(): for k,v in contacts.items(): print 'dict[', k, '] = ', v print("Length of dict is %s" % len(contacts)) print("Dict contains:") print_dict() print("Deleting dict[key]:") del(contacts['abc']) print_dict() print("Checking if pqr key is present %r :" % ('pqr' in contacts)) print("Deleting non existant key \'lmn\'") try: del(contacts['lmn']) except KeyError: print("Caught error : KeyError:item does not exist") if __name__ == "__main__": main()
true
e2350657520b17cc90a0fb9406a4cc6f99cee53a
CookieComputing/MusicMaze
/MusicMaze/model/data_structures/Queue.py
1,532
4.21875
4
from model.data_structures.Deque import Deque class Queue: """This class represents a queue data structure, reinvented out of the wheel purely for the sake of novelty.""" def __init__(self): """Constructs an empty queue.""" self._deque = Deque() def peek(self): """Peek at the earliest entry in the queue without removing it. Returns: Any: the data of the front-most entry in the queue Raises: IndexError: If no data is in the queue.""" if not self._deque: raise IndexError("Queue is empty") return self._deque.peek_head() def enqueue(self, data): """Puts the given data into the queue. Args: data(Any): the data to be inserted into the back of the queue""" self._deque.push_tail(data) def dequeue(self): """Removes the earliest entry from the queue and returns it. Returns: Any: the data of the earliest entry in the queue Raises: IndexError: If the queue is empty""" if not self._deque: raise IndexError("Queue is empty") return self._deque.pop_head() def __len__(self): """Returns the size of the queue. Returns: int: the size of the queue""" return len(self._deque) def __bool__(self): """Returns true if the queue has an entry Returns: bool: True if len(queue) > 0, false otherwise""" return len(self) > 0
true
9bc3ae714f881fd44890ed63429dc9bc4de89b5c
codewithgauri/HacktoberFest
/python/Learning Files/10-List Data Type , Indexing ,Slicing,Append-Extend-Insert-Closer look at python data types.py
1,129
4.28125
4
l=[10,20,22,30,40,50,55] # print(type(l)) # 1 Lists are mutable = add update and delete # 2 Ordered = indexing and slicing # 3 Hetrogenous # indexing and slicing: # print(l[-1]) # print(l[1:3]) #end is not inclusive # reverse a Lists # print(l[::-1]) # if you want to iterate over alternate characters # for value in l[::2]: # print(value) # append # if u want to add single element in a list # it wont return any thing #memory location will be the same # l.append(60) # print(l) # extend # if u want to add multiple elements # it only take one agrument # it will iterate over give argument #l.extend("Python") # l.extend([500,600,700,800]) # print(l) # in case of append it will add the whole list as one element # insert # Both append and extend will add element at last but if you want to add at particular # position we use insert method # l.insert(1,1000) # print(l) # l = [ 10,20,30] # l2=l # l.append(40) # print(id(l),id(l2)) # print(l,l2) # if we modifiy the frist list it will also modifiy the second list # so we use some time copy l = [ 10,20,30] l2=l.copy() l.append(40) print(id(l),id(l2)) print(l,l2)
true
453eb80f8c7d3c8353c7288f4beea8e3f7e0c1c5
codewithgauri/HacktoberFest
/python/Cryptography/Prime Numbers/naive_primality_test.py
576
4.21875
4
##Make sure to run with Python3 . Python2 will show issues from math import sqrt from math import floor def is_prime(num): #numbers smaller than 2 can not be primes if num<=2: return False #even numbers can not be primes if num%2==0: return False #we have already checked numbers < 3 #finding primes up to N we just have to check numbers up to sqrt(N) #increment by 2 because we have already considered even numbers for i in range(3,floor(sqrt(num)),2): if num%i==0: return False return True if __name__ == "__main__": print(is_prime(99194853094755497))
true
51d1cb5a523fa102734d50143a3b9eab17faf2cb
codewithgauri/HacktoberFest
/python/Learning Files/13-Dictionary Data Types , Storing and Accessing the data in dictionary , Closer look at python data types.py.py
1,580
4.3125
4
# dict: # 1. mutable # 2.unordered= no indexing and slicing # 3.key must be unque # 4.keys should be immutable # 5. the only allowed data type for key is int , string , tuple # reason mutable data type is not allowed # for example # d={"emp_id":101 , [10,20,30]:100,[10,20]:200} # if we add an element into [10,20] of 30 we will be creating a duplicate key #d={"emp_id":101, "emp_name":"Uday Kiran", "email_id":"kiranu941@gmail.com"} # print(d) #d["email_id"]=102 #print(d) #d["contact_no"]=123456789 #print(d) # d["contact_no"]=1234567898 # it will update the value # get # setdeafult # get retrive a data from the key specified #print(d.get("emp_name")) # if we specified a key which doesnt exist it wont through an error # it will return None # if u want the function to return a value when the key doesnt exist # we can specify a second parameter #print(d.get("email","Key doesnt exist")) #setdeafult adds elemets if key doesnt exit else it will retrive data #print(d.setdefault("age")) # since age is not present it will add the age key and the assign a value of None # if we want to assign a value to it i inilization its self # print(d.setdefault("age",50)) #d["email_id"]="kiranu942@gmail.com" #print(d) #for x in d: # print(x) # defaultly it will iterate over the keys #for x in d: # print(x,d[x]) # if we also want the values #dic={} #for num in range(1,11): # dic[num]=num*num #print(dic) #keys #values #items # print(d.keys()) it is a list of all the keys # print(d.values()) it is a list of all the values # print(d.items()) it returns a tuple # for t in d.items(): # print(t)
true
2725b85849ce224e97685919f148cc9807e60d83
bdngo/math-algs
/python/checksum.py
1,155
4.21875
4
from typing import List def digit_root(n: int, base: int=10) -> int: """Returns the digital root for an integer N.""" assert type(n) == 'int' total = 0 while n: total += n % base n //= base return digit_root(total) if total >= base else total def int_to_list(n: int, base: int=10) -> List[int]: """Returns a list of the digits of N.""" digit_list = [] while n: digit_list += [n % base] n //= base return list(reversed(digit_list)) def check_sum(n: int) -> bool: """Checks if N is a valid bank card.""" digits, doubled_digits = int_to_list(n), [] for i in range(len(digits)): doubled_digits.append( digit_root(digits[i] * 2) if i % 2 == 0 else digits[i]) return sum(doubled_digits) % 10 == 0 def vat_check(n: int) -> bool: """Checks if N satisfies the old HMRC VAT number check.""" factor = 8 digits, last_two = int_to_list(n)[:-2], int_to_list(n)[-2:] for i in range(len(digits)): digits[i] *= factor factor -= 1 check_digit = sum(digits) + (last_two[0]*10 + last_two[1]) + 55 return check_digit % 97 == 0
true
e64687b9baaa75ae481ea65ed9e2cd26a203e41a
kimoror/python-practice
/practice1_extra/main.py
2,722
4.25
4
# Ответы на теоретические вопросы находятся в файле AnswersOnQuestions.md """ Попробуйте составить код для решения следующих задач. Из арифметических операций можно использовать только явно указанные и в указанном количестве. Входным аргументом является переменная x. """ def no_multiply(x): if x == 12: return 3 + 3 + 3 + 3 elif x == 16: return 4 + 4 + 4 + 4 elif x == 15: return 6 + 6 + 6 - 2 - 1 elif x == 29: return 5 + 5 + 5 + 5 + 5 + 5 - 1 print(f'Умножение 1 на {no_multiply(29)}: {no_multiply(29)}') """ # Некто попытался реализовать "наивную" функцию умножения с помощью сложений. К сожалению, в коде много ошибок. # Сможете ли вы их исправить? """ def naive_mul(x, y): r = 0 for i in range(y): r += x return r def naive_mul_test(): for x in range(101): for y in range(101): assert naive_mul(x, y) == x * y print("naive_mul_test is passed") naive_mul_test() """ # Реализуйте функцию fast_mul в соответствии с алгоритмом двоичного умножения в столбик. # Добавьте автоматическое тестирование,как в случае с naive_mul. """ def fast_mul(x, y): # if x == 1: # return y # if y == 1: # return x res = 0 while x >= 1: if x == 0 or y == 0: return 0 elif x % 2 == 0: y *= 2 x //= 2 elif x % 2 != 0: res += y y *= 2 x //= 2 return res def fast_mul_test(): for x in range(101): for y in range(101): assert fast_mul(x, y) == x * y print("fast_mull_test is passed") fast_mul_test() # Реализуйте аналогичную функцию для возведения в степень def fast_pow(base, degree, mul=1): if degree == 0 and base == 0: return 1 # elif degree == 1: # return base if degree == 0: return mul elif base == 0: return 0 elif base == 1: return 1 if degree % 2 != 0: mul *= base return fast_pow(base * base, degree // 2, mul) def fast_pow_test(): for x in range(101): for y in range(101): assert fast_pow(x, y) == x ** y print("fast_mull_test is passed") fast_pow_test()
false
52c44bf0aa15ba0bfcc1abda81fffefba6be075c
DistantThunder/learn-python
/ex33.py
450
4.125
4
numbers = [] # while i < 6: # print("At the top i is {}".format(i)) # numbers.append(i) # # i = i + 1 # print("Numbers now: ", numbers) # print("At the bottom i is {}\n{}".format(i, '-')) def count_numbers(count): count += 1 for i in range(0, count): numbers.append(i) return 0 count_numbers(int(input("Enter the number you want to count to: "))) print("The numbers: ") for num in numbers: print(num)
true
1fe48d3656b9437f43b79afa4ba5d9f2ffe13c2f
adamfitzhugh/python
/kirk-byers/Scripts/Week 1/exercise3.py
942
4.375
4
#!/usr/bin/env python """Create three different variables: the first variable should use all lower case characters with underscore ( _ ) as the word separator. The second variable should use all upper case characters with underscore as the word separator. The third variable should use numbers, letters, and underscores, but still be a valid variable Python variable name. Make all three variables be strings that refer to IPv6 addresses. Use the from future technique so that any string literals in Python2 are unicode. compare if variable1 equals variable2 compare if variable1 is not equal to variable3 """ from __future__ import print_function ipv_six_addr_1 = "2001:db8:1234::1" IPV_SIX_ADDR_2 = "2001:db8:1234::2" ipv_6_addr_3 = "2001:db8:1234::3" print("") print("Is var1 == var2: {}".format(ipv_six_addr_1 == IPV_SIX_ADDR_2)) print("Is var1 != var3: {}".format(ipv_six_addr_1 != ipv_6_addr_3)) print("")
true
d925d4b637199ad159b36b33dcb0438ccca0f95a
adamfitzhugh/python
/kirk-byers/Scripts/Week 5/exercise3.py
1,788
4.15625
4
""" Similar to lesson3, exercise4 write a function that normalizes a MAC address to the following format: 01:23:45:67:89:AB This function should handle the lower-case to upper-case conversion. It should also handle converting from '0000.aaaa.bbbb' and from '00-00-aa-aa-bb-bb' formats. The function should have one parameter, the mac_address. It should return the normalized MAC address Single digit bytes should be zero-padded to two digits. In other words, this: a:b:c:d:e:f should be converted to: 0A:0B:0C:0D:0E:0F Write several test cases for your function and verify it is working properly. """ from __future__ import print_function, unicode_literals import re def normal_mac_addr(mac_address): mac_address = mac_address.upper if ':' in mac_address or '-' in mac_address: new = [] octets = re.split(r"[-:]", mac_address) for octet in octects: if len(octet) < 2: octet = octet.zfill(2) new.append(octet) elif '.' in mac_address: mac = [] sec = mac_address.split('.') if len(sec) != 3: raise ValueError("This went wrong") for word in sec: if len(word) < 4: word = word.zfill(4) new.append(word[:2]) mac.append(word[:2]) return ":".join(mac) # Some tests assert "01:23:02:34:04:56" == normal_mac_addr('123.234.456') assert "AA:BB:CC:DD:EE:FF" == normal_mac_addr('aabb.ccdd.eeff') assert "0A:0B:0C:0D:0E:0F" == normal_mac_addr('a:b:c:d:e:f') assert "01:02:0A:0B:03:44" == normal_mac_addr('1:2:a:b:3:44') assert "0A:0B:0C:0D:0E:0F" == normal_mac_addr('a-b-c-d-e-f') assert "01:02:0A:0B:03:44" == normal_mac_addr('1-2-a-b-3-44') print("Tests passed")
true
2c9a6858ef76026d57e96ce85724e7c062e657d5
nileshmahale03/Python
/Python/PythonProject/5 Dictionary.py
1,487
4.21875
4
""" Dictionary: 1. Normal variable holds 1 value; dictionary holds collection of key-value pairs; all keys must be distinct but values may be repeated 2. {} - curly bracket 3. Unordered 4. Mutable 5. uses Hashing internally 6. Functions: 1. dict[] : returns value at specified index 2. len() : returns length of dictionary min() : returns min value in dictionary max() : returns max value in dictionary sum() : returns sum of values in dictionary 3. dict.reverse() : 'dict' object has no attribute 'reverse' 4. dict.sort() : 'dict' object has no attribute 'sort' 5. in : operator returns bool stating if specified value present in dictionary or not 6. dict[key] = value : add value with specified key 7. dict[key] : get value from dict with specified key dict.get(key) returns None if key dosen't exists 11. dict.pop(key) : dict.pop() dict.popitem() pop() will remove last value 12. del dict[key] : delete """ dict = {10:"abc", 20:"xyz", 30:"pqr"} print(dict) print(type(dict)) print(dict[10]) print(dict, len(dict), min(dict), max(dict), sum(dict)) dict[40] = "def" print(dict) print(dict[30], dict.get(30)) print(dict.get(50), dict.get(60, "Not Available")) #dict.reverse() #dict.sort() print(20 in dict, 80 in dict) dict.popitem() print(dict) dict.pop(10) print(dict) del dict[30] print(dict)
true
e3f5d349f45c8d01cd939727a9bbd644ddaa0bdd
changjunxia/auto_test_example1
/test1.py
228
4.125
4
def is_plalindrome(string): string = list(string) length = len(string) left = 0 right = length - 1 while left < right: if string[left] != string[right]: return False left += 1 right -= 1 return True
true
a1a7e5faad35847f22301b117952e223857d951a
nestorsgarzonc/leetcode_problems
/6.zigzag_convertion.py
1,459
4.375
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I """ """ 1158 / 1158 test cases passed. Status: Accepted Runtime: 88 ms Memory Usage: 13.9 MB """ # Solution brute force class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s arrResult = [[] for i in range(numRows)] counter = 0 numRows -= 1 reverse = False for i in s: if counter == numRows: reverse = True if counter == 0: reverse = False if counter < numRows and reverse == False: arrResult[counter].append(i) counter += 1 if counter > 0 and reverse == True: arrResult[counter].append(i) counter -= 1 myResult = '' for i in arrResult: myResult.join(i) return myResult
true
e2349b63116bb7f3e83aa436c41175efda4a8d9d
llNeeleshll/Python
/section_3/string_play.py
290
4.15625
4
text = "This is awesome." # Getting the substring print(text[8:]) print(text[0:4]) # text[start:end:step] print(text[0:14:2]) print(text[0::2]) # Reversing the string print(text[::-1]) # Print a word 10 times? print("Hello " * 10) print("Hello " * 10 + "World!") print("awe" in text)
true
2690856645451099474cbed49d688a0fecd653f4
KaviyaMadheswaran/laser
/infytq prev question.py
408
4.15625
4
Ex 20) 1:special string reverse Input Format: b@rd output Format: d@rb Explanation: We should reverse the alphabets of the string by keeping the special characters in the same position s=input() alp=[] #index of char ind=[] for i in range(0,len(s)): if(s[i].isalpha()): alp.append(s[i]) else: ind.append(i) rev=alp[::-1] for i in ind: #character value in s char=s[i] rev.insert(i,char) print(rev)
true
50e3bc5493956708bf1897a74600cd9639777bf8
KaviyaMadheswaran/laser
/w3 resource.py
403
4.1875
4
Write a Python program to split a given list into two parts where the length of the first part of the list is given. Go to the editor Original list: [1, 1, 2, 3, 4, 4, 5, 1] Length of the first part of the list: 3 Splited the said list into two parts: ([1, 1, 2], [3, 4, 4, 5, 1]) n=int(input()) l=list(map(int,input().split())) ans=[] l1=l[:n] l2=l[n:] ans.append(l1) ans.append(l2) print(tuple(ans))
true
fbcf1c36b34a8565e0153b403fbcb185782890ba
KaviyaMadheswaran/laser
/w3 resource6.py
392
4.15625
4
Write a Python program to flatten a given nested list structure. Go to the editor Original list: [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]] Flatten list: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] l=[0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]] l1=[] for i in l: if(isinstance(i,list)): for j in i: l1.append(j) else: l1.append(i) print(l1)
false
5539d4170fa7ecc1a9a97ba4aa3ed2f23650bd1a
KaviyaMadheswaran/laser
/Birthday Cake candle(Hackerrank).py
490
4.125
4
Output Format Return the number of candles that can be blown out on a new line. Sample Input 0 4 3 2 1 3 Sample Output 0 2 Explanation 0 We have one candle of height 1, one candle of height 2, and two candles of height 3. Your niece only blows out the tallest candles, meaning the candles where height = 3. Because there are 2 such candles, we print 2 on a new line. n=int(input()) l=list(map(int,input().split())) maxi=max(l) c=0; for i in l: if(i==maxi): c+=1 print(c)
true
a5ed73ac78f673fa965b551bef169860cd38a658
timclaussen/Python-Examples
/OOPexample.py
441
4.25
4
#OOP Example #From the simple critter example, but with dogs class Dog(object): """A virtual Dog""" total = 0 def _init_(self, name): print("A new floof approaches!") Dog.total += 1 #each new instance adds 1 to the class att' total self.name = name #sets the constructor input to an attribute def speak(self): print("Woof, I am dog.") def #main pup = Dog() pup.speak()
true
7ca7a468dcc8aea1cc45757f9430b5fa0c0d736f
JuanHernandez2/Ormuco_Test
/Ormuco/Strings comparator/comparator.py
1,188
4.25
4
import os import sys class String_comparator: """ Class String comparator to compare two strings and return which is greater, less or equal than the other one. Attributes: string_1: String 1 string_2: String 2 """ def __init__(self, s1, s2): """ Class constructor Params: s1: string 1 s2: string 2 """ self.string_1 = s1 self.string_2 = s2 def compare(self): """ This function compares if both strings are greater, less or equal to the other one """ if str(self.string_1) > str(self.string_2): return "{} is greater than {}".format(self.string_1, self.string_2) elif str(self.string_1) < str(self.string_2): return "{} is less than {}".format(self.string_1, self.string_2) else: return "{} is equal to {}".format(self.string_1, self.string_2) def check_strings(self): """ Checks if the two strings are valid """ if self.string_1 is None or self.string_2 is None: raise ValueError("One of the arguments is missing or NoneType")
true
1ed4ea179560b5feec261b094bdbe5b2848b4e03
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/flag.py
321
4.1875
4
active = True print("if you want to quit type quit") while active: message = input("Enter your message: ") if message == 'quit': # break # to break the loop here active = False #comtinue # to execute left over code exiting the if else: print(message)
true
0227e6263035a7b7e6cf67dadde3eb91576afc0b
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/deli.py
710
4.28125
4
user_want = {} # fistly define a dictonairy empty poll_active = True while poll_active: name = input('Enter your name: ') want = input('if you visit one place in the world where you visit? ') repeat = input('waant to know others wnats (yes,no)? ') # after input store the data at dictionary user_want user_want[name] = want # but user dont want to know about other if he/she type no so to stop the loop we can do: if repeat == 'no': poll_active = False # at last we take keys and values form the user_want dictionary and just print them for names,wants in user_want.items(): print(f'\tHi! {names} you want to visit {wants}')
true
8592b3147c28ef1b09589c048dfa30e0eb87aa5a
Sharmaanuj10/Phase1-basics-code
/python book/Python/password.py/password 1.5.py/password1.5.py
1,287
4.28125
4
name = input("Enter your username: ") passcode = input("Enter you password: ") # upper is used to capatilize the latter name = name.upper() # all the password saved def webdata(): webdata= input("Enter the key word : ") user_passwords = { 'youtube' : 'subscribe', # here now you can save infinte number of password 'twitter' : 'qwerty', # '' : '', # I created many string to store the data } print(user_passwords.get(webdata)) # here the attribute '.get' get the data from the names; # username and their passwords userdata = { 'ANUJ' : 'lol', 'ANUJ SHARMA' : 'use', '' : '' } # now we looped the dictonairy and get the keys and values or username and password to check for username , password in userdata.items(): # In this case if the name == username we enter so it check wether passcode is equal or not if name == username: if passcode == password: # now the user is verified so we import the webdata or passowords data webdata() # in this the the username and passowrd are linked so they are not going to mess with each other like older have # Note : still it have a problem can you find out what??🧐🧐
true
213ebf4489f815cf959de836a11e2339ca8bcfaa
rsleeper1/Week-3-Programs
/Finding Max and Min Values Recursively.py
2,148
4.21875
4
#Finding Max and Min Values #Ryan Sleeper def findMaxAndMin(sequence): #This method finds the max and min values of a sequence of numbers. if len(sequence) < 2: #This catches a sequence that doesn't have enough numbers to compare (less than 2) and returns the invalid sequence. print("Please create a sequence of at least 2 numbers.") minNum = sequence maxNum = sequence return minNum, maxNum elif len(sequence) == 2: #This is my base case. Once the sequence gets down to two numbers we have found the max and min. sequence.sort() return sequence[0], sequence[1] else: if sequence[0] <= sequence[1]: #This if statement initializes the minimum number and the maximum number. minNum = sequence[0] maxNum = sequence[1] else: minNum = sequence[1] maxNum = sequence[0] if minNum < sequence[2]: #Once we have a minimum and maximum, the method checks the next number and compares it to the if maxNum > sequence[2]: #minimum value and the maximum value. If it is less than the minimum, then it becomes the new sequence.remove(sequence[2]) #minimum value. If it is greater than the maximum value then it becomes the new max value. If return findMaxAndMin(sequence) #it is neither than it gets removed from the list. else: sequence.remove(maxNum) maxNum = sequence[1] return findMaxAndMin(sequence) else: sequence.remove(minNum) minNum = sequence[1] return findMaxAndMin(sequence) def main(): sequence = [54, 79, 8, 0, 9, 9, 23, 120, 40] #This is my sequence, feel free to change it to see different results. minNum, maxNum = findMaxAndMin(sequence) print("The minimum number is: {}".format(minNum)) #I had the program print out the results to make sure it was producing the correct answers. print("The maximum number is: {}".format(maxNum)) main()
true
d075b9df570b98066efa80959ee3d102bca91614
chigozieokoroafor/DSA
/one for you/code.py
259
4.28125
4
while True: name = input("Name: ") if name == "" or name==" ": print("one for you, one for me") raise Exception("meaningful message required, you need to put a name") else: print(f"{name} : one for {name}, one for me")
true
28e8f771a7968081d3ced6b85ddec657163ad7d1
avi527/Tuple
/different_number_arrgument.py
248
4.125
4
#write a program that accepts different number of argument and return sum #of only the positive values passed to it. def sum(*arg): tot=0 for i in arg: if i>0: tot +=i return tot print(sum(1,2,3,-4,-5,9))
true
711646003de502ae59915ebcd3fff47b56b0144d
Wh1te-Crow/algorithms
/sorting.py
1,318
4.21875
4
def insertion_sorting(array): for index in range(1,len(array)): sorting_part=array[0:index+1] unsorting_part=array[index+1:] temp=array[index] i=index-1 while(((i>0 or i==0) and array[i]>temp)): sorting_part[i+1]=sorting_part[i] sorting_part[i]=temp i-=1 array=sorting_part+unsorting_part return(array) def bubble_sorting(array): indicator_of_change=1 index_of_last_unsorted=len(array) while(indicator_of_change): indicator_of_change=0 for index in range(0,index_of_last_unsorted-1): if (array[index]>array[index+1]): temp=array[index] array[index]=array[index+1] array[index+1]=temp indicator_of_change+=1 index_of_last_unsorted-=1 return array def sorting_by_choice(array): sorting_array=[] while(len(array)>0): minimum = array[0] for index in range(1,len(array)): if minimum>array[index]: minimum=array[index] array.remove(minimum) sorting_array.append(minimum) return sorting_array print(insertion_sorting([1,2,3,8,9,0,-1,-5,0])) print(bubble_sorting([1,2,3,8,9,0,-1,-5,0])) print(sorting_by_choice([1,2,3,8,9,0,-1,-5,0]))
true
315bc09a11f42cd7b010bee38ac8fa52d06e172c
calazans10/algorithms.py
/basic/var.py
242
4.125
4
# -*- coding: utf-8 -*- i = 5 print(i) i = i + 1 print(i) s = '''Esta é uma string de múltiplas linhas. Esta é a segunda linha.''' print(s) string = 'Isto é uma string. \ Isto continua a string.' print(string) print('O valor é', i)
false
34ae06f5fea1a3886a7208998a729c3900280424
gugry/FogStreamEdu
/lesson1_numbers_and_strings/string_tusk.py
261
4.125
4
#5.Дана строка. Удалите из нее все символы, чьи индексы делятся на 3. input_str = input() new_str = input_str[0:3]; for i in range(4,len(input_str), 3): new_str = new_str + input_str[i:i+2] print (new_str)
false
358cd42a66be05b4606d01bcb525afa140181ccc
PRASADGITS/shallowcopyvsdeepcopy
/shallow_vs_deep_copy.py
979
4.5
4
import copy ''' SHALLOW COPY METHOD ''' old_list = [[1,2,3],[4,5,6],[7,8,9]] new_list=copy.copy(old_list) print ("old_list",old_list) print ("new_list",new_list,"\n") old_list.append([999]) print ("old_list",old_list) print ("new_list",new_list,"\n") old_list[1][0]="x" # both changes Because the refernce is same for nested objects in shallow copy, # poinsta to the same object in memory print ("old_list",old_list) print ("new_list",new_list,"\n") ''' Deep copy method ''' print ("Deep copy starts \n") old_list_1 = [[1,2,3],[4,5,6],[7,8,9]] new_list_1=copy.deepcopy(old_list_1) print ("old_list_1",old_list_1) print ("new_list_1",new_list_1,"\n") old_list_1.append([999]) print ("old_list_1",old_list_1) print ("new_list_1",new_list_1, "\n") old_list_1[1][0]="x" # Because the old list was recursively copied print ("old_list_1",old_list_1) print ("new_list_1",new_list_1)
false
ba0bf77d3202493747e94c0a686c739d6cb98e9f
srisreedhar/Mizuho-Python-Programming
/Session-18-NestedConditionals/nestedif.py
510
4.1875
4
# ask user to enter a number between 1-5 and print the number in words number=input("Enter a number between 1-5 :") number=int(number) # if number == 1: # print("the number is one") # else: # print("its not one") # Nested conditions if number==1: print("number is one") elif number==2: print("number is two") elif number==3: print("number is Three") elif number==4: print("number is Four") elif number==5: print("number is Five") else: print("The number is out of range")
true
04c4b07e6e7e980e7d759aff14ce51d38fa89413
davelpat/Fundamentals_of_Python
/Ch2 exercises/employeepay.py
843
4.21875
4
""" An employee’s total weekly pay equals the hourly wage multiplied by the total number of regular hours, plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee’s total weekly pay. Below is an example of the program inputs and output: Enter the wage: $15.50 Enter the regular hours: 40 Enter the overtime hours: 12 The total weekly pay is $899.0 """ # Get employee weekly data wage = float(input("Enter the wage: ")) regHours = float(input("Enter the regular hours: ")) overtime = float(input("Enter the overtime hours: ")) # Calculate the pay pay = wage * regHours + wage * overtime * 1.5 # and display it print("The total weekly pay is $"+str(pay))
true
d5367ee9332da2c450505cb454e4e8dac87b2bf8
davelpat/Fundamentals_of_Python
/Student_Files/ch_11_student_files/Ch_11_Student_Files/testquicksort.py
1,817
4.15625
4
""" File: testquicksort.py Tests the quicksort algorithm """ def quicksort(lyst): """Sorts the items in lyst in ascending order.""" quicksortHelper(lyst, 0, len(lyst) - 1) def quicksortHelper(lyst, left, right): """Partition lyst, then sort the left segment and sort the right segment.""" if left < right: pivotLocation = partition(lyst, left, right) quicksortHelper(lyst, left, pivotLocation - 1) quicksortHelper(lyst, pivotLocation + 1, right) def partition(lyst, left, right): """Shifts items less than the pivot to its left, and items greater than the pivot to its right, and returns the position of the pivot.""" # Find the pivot and exchange it with the last item middle = (left + right) // 2 pivot = swap(lyst, middle, right) # pivot = lyst[middle] # lyst[middle] = lyst[right] # lyst[right] = pivot # Set boundary point to first position boundary = left # Move items less than pivot to the left for index in range(left, right): if lyst[index] < pivot: swap(lyst, index, boundary) boundary += 1 # Exchange the pivot item and the boundary item swap(lyst, right, boundary) return boundary quicksortHelper(0, len(lyst) - 1) def swap(lyst, i, j): """Exchanges the items at positions i and j.""" # You could say lyst[i], lyst[j] = lyst[j], lyst[i] # but the following code shows what is really going on temp = lyst[i] lyst[i] = lyst[j] lyst[j] = temp return temp import random def main(size = 20, sort = quicksort): """Sort a randomly ordered list and print before and after.""" lyst = list(range(1, size + 1)) random.shuffle(lyst) print(lyst) sort(lyst) print(lyst) if __name__ == "__main__": main()
true
1a7183d7758f27abb21426e84019a9ceeb5da7c7
davelpat/Fundamentals_of_Python
/Ch3 exercises/right.py
1,344
4.75
5
""" Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides. Use "The triangle is a right triangle." and "The triangle is not a right triangle." as your final outputs. An example of the program input and proper output format is shown below: Enter the first side: 3 Enter the second side: 4 Enter the third side: 5 The triangle is a right triangle. """ # Get the side lengths sideA = float(input("Enter length of side 1 of the triangele: ")) sideB = float(input("Enter length of side 2 of the triangele: ")) sideC = float(input("Enter length of side 3 of the triangele: ")) # Determine which side is potentially the hypotenuse if sideA == max(sideA, sideB, sideC): hypot = sideA side2 = sideB side3 = sideC elif sideB == max(sideA, sideB, sideC): hypot = sideB side2 = sideA side3 = sideC else: hypot = sideC side2 = sideB side3 = sideA # Determinei if it is a right triangle using the Pythagorean theorem if hypot ** 2 == (side2 ** 2 + side3 ** 2): print("The triangle is a right triangle.") else: print("The triangle is not a right triangle.")
true
82808ac569c685a2b864fd668edebbb7264cd07d
davelpat/Fundamentals_of_Python
/Ch9 exercises/testshapes.py
772
4.375
4
""" Instructions for programming Exercise 9.10 Geometric shapes can be modeled as classes. Develop classes for line segments, circles, and rectangles in the shapes.py file. Each shape object should contain a Turtle object and a color that allow the shape to be drawn in a Turtle graphics window (see Chapter 7 for details). Factor the code for these features (instance variables and methods) into an abstract Shape class. The Circle, Rectangle, and Line classes are all subclasses of Shape. These subclasses include the other information about the specific types of shapes, such as a radius or a corner point and a draw method. Then write a script called testshapes.py that uses several instances of the different shape classes to draw a house and a stick figure. """
true
f9a84cff7e4e9c4a92167506a09fcf09726ecfc1
davelpat/Fundamentals_of_Python
/Ch3 exercises/salary.py
1,387
4.34375
4
""" Instructions Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2% increase over the preceding value. Write a program that displays a salary schedule, in tabular format, for teachers in a school district. The inputs are: Starting salary Annual percentage increase Number of years for which to print the schedule Each row in the schedule should contain the year number and the salary for that year An example of the program input and output is shown below: Enter the starting salary: $30000 Enter the annual % increase: 2 Enter the number of years: 10 Year Salary ------------- 1 30000.00 2 30600.00 3 31212.00 4 31836.24 5 32472.96 6 33122.42 7 33784.87 8 34460.57 9 35149.78 10 35852.78 """ salary = int(input("Please enter starting salary in dollars: ")) incr = float(input("Please enter the percent annual increase: ")) / 100 service = int(input("Please enter the years of service (max = 10): ")) print("%4s%10s" % ("Year", "Salary")) print("-"*14) for year in range(1, service + 1): print("%-6i%0.2f" % (year, salary)) salary += salary * incr
true
2ee467b7f70e740bce32e857df97bd311034e494
davelpat/Fundamentals_of_Python
/Ch4 exercises/decrrypt-str.py
1,106
4.5625
5
""" Instructions for programming Exercise 4.7 Write a script that decrypts a message coded by the method used in Project 6. Method used in project 6: Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. An example of the program input and output is shown below: Enter the coded text: 0010011 1001101 1011011 1011011 1100001 000011 1110001 1100001 1100111 1011011 1001011 000101 Hello world! """ DIST = 1 FIRST_ORD = 0 LAST_ORD = 127 SPACE = " " charList = input("Enter the coded text: ").split() eTxt = "" for bstring in charList: # Shift bit string 1 to the left bStrSize = len(bstring) bstring = bstring[-DIST:bStrSize] + bstring[0:bStrSize - DIST] # Convert ordinal bit string to decimal charOrd = 0 exponent = bStrSize - 1 for digit in bstring: charOrd = charOrd + int(digit) * 2 ** exponent exponent = exponent - 1 # Readjust ordinal value eTxt += chr(charOrd - 1) print(eTxt)
true
5b3f98828c1aa52309d9450094ecb3ab990bae91
davelpat/Fundamentals_of_Python
/Ch4 exercises/encrypt-str.py
1,246
4.53125
5
""" Instructions for programming Exercise 4.6 Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5 to code a new encryption algorithm. The algorithm should Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. An example of the program input and output is shown below: Enter a message: Hello world! 0010011 1001101 1011011 1011011 1100001 000011 1110001 1100001 1100111 1011011 1001011 000101 """ DIST = 1 FIRST_ORD = 0 LAST_ORD = 127 SPACE = " " txt = input("Enter a message: ") eTxt = "" for char in txt: # get and increment character's ASCII value charOrd = ord(char) + DIST # Not sure if the wrap around is required if charOrd > LAST_ORD: charOrd = FIRST_ORD + LAST_ORD - charOrd # Convert it to a bit string bstring = "" while charOrd > 0: remainder = charOrd % 2 charOrd = charOrd // 2 bstring = str(remainder) + bstring # Shift bit string 1 to the left bstring = bstring[DIST:len(bstring)]+bstring[0:DIST] eTxt += bstring + SPACE print(eTxt)
true
8b70613ee7350c54156a4eb076f11b82356055f7
davelpat/Fundamentals_of_Python
/Ch3 exercises/population.py
1,828
4.65625
5
""" Instructions A local biologist needs a program to predict population growth. The inputs would be: The initial number of organisms The rate of growth (a real number greater than 1) The number of hours it takes to achieve this rate A number of hours during which the population grows For example, one might start with a population of 500 organisms, a growth rate of 2, and a growth period to achieve this rate of 6 hours. Assuming that none of the organisms die, this would imply that this population would double in size every 6 hours. Thus, after allowing 6 hours for growth, we would have 1000 organisms, and after 12 hours, we would have 2000 organisms. Write a program that takes these inputs and displays a prediction of the total population. An example of the program input and output is shown below: Enter the initial number of organisms: 10 Enter the rate of growth [a real number > 0]: 2 Enter the number of hours to achieve the rate of growth: 2 Enter the total hours of growth: 6 The total population is 80 """ curPop = initPop = int(input("Enter the initial number of organisms: ")) growthRate = float(input("Enter the rate of growth [a real number > 0]: ")) growthCycle = float(input("Enter the number of hours to achieve the rate of growth: ")) period = float(input("Enter the total hours of growth: ")) fullCycles = int(period // growthCycle) # print("fullCycles =", fullCycles) partCycle = (period % growthCycle) / growthCycle # print("partCycle =", partCycle) for cycle in range(0, fullCycles): curPop = round(curPop * growthRate) # print("Population after", cycle + 1, "cycles is", curPop) # the Python course test is only looking for complete growth cycles # partPop = round((curPop * growthRate - curPop) * partCycle) # urPop = curPop + partPop print("The total population is", curPop)
true
a18806eeb1213b7fae5c963fdbf08a307d7d3fc2
palomaYPR/Introduction-to-Python
/CP_P21-1_TipoOperadores.py
418
4.125
4
# EUP que permita ingresar dos números y un operador, de acuerdo al operador ingresado se realizara la debida # operacion. num1 = int(input('Ingresa el 1er número: ')) num2 = int(input('Ingresa el 2do número: ')) ope = str(input('Ingresa el operador: ')) if ope == '*': res = num1 + num2 elif ope == '/': res = num1 / num2 elif ope == '+': res = num1 + num2 else: res = num1 - num2
false
f9c25e2e6239587a86696c5e868feca3ab8beac0
palomaYPR/Introduction-to-Python
/CP_P14_AreaCirculo.py
282
4.125
4
# Elabora un programa que calcule el area de un circulo # Nota: Tome en cuenta que la formula es A = (pi * r^2) import math message = input('Ingresa el radio del circulo: ') r = int(message) area = math.pi * r**2 #area = math.pi * math.pow(r,2) print('El area es: ',area)
false
d4a8cd543636b4375918bfe64430df051604c4da
nachoaz/Data_Structures_and_Algorithms
/Stacks/balanced_brackets.py
745
4.15625
4
# balanced_brackets.py """ https://www.hackerrank.com/challenges/balanced-brackets """ from stack import Stack def is_balanced(s): if len(s) % 2 == 1: return 'NO' else: stack = Stack() counterparts = {'{':'}', '[':']', '(':')'} for char in s: if char in counterparts: stack.push(char) elif stack.is_empty() or counterparts[stack.pop()] != char: return 'NO' return 'YES' if stack.is_empty() else 'NO' def main(): n = int(input()) for _ in range(n): bracket_string = input() output = is_balanced(bracket_string) print(output) if __name__ == '__main__': main()
true
71e18ee05051d083fa00285c9fbc116eca7fb3f3
bayl0n/Projects
/stack.py
794
4.25
4
# create a stack using a list class Stack: def __init__(self): self.__stack = list() def __str__(self): return str(self.__stack) def push(self, value): self.__stack.append(value) return self.__stack[len(self.__stack) -1] def pop(self): if len(self.__stack) > 0: temp = self.__stack[len(self.__stack) - 1] self.__stack.pop(len(self.__stack) - 1) return temp else: return None def top(self): if len(self.__stack) > 0: return self.__stack[len(self.__stack) - 1] else: return None if __name__ == "__main__": myStack = Stack() print(myStack.push("Banana")) print(myStack.pop()) print(myStack.top()) print(myStack)
false
15198370140d3b04074d6647eda200767cc2479d
rahulpawargit/UdemyCoursePractice
/Tuples.py
290
4.1875
4
""" Tuples are same as list. The diffferance between list and tuples. Tuples are unmutalble. Tuples add using parenthesis """ my_tuple=(1, 2, 3, 4,3, 3, 3) print(my_tuple) print(my_tuple[1]) print(my_tuple[1:]) print(my_tuple[::-1 ]) print(my_tuple.index(3)) print((my_tuple.count(3)))
true
186ea3c70994726a8b6fe9ea2d00c44e116cbc16
zaochnik555/Python_1_lessons-1
/lesson_02/home_work/hw02_easy.py
2,044
4.125
4
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() print("Задача 1") fruit_list=["яблоко", "банан", "киви", "арбуз"] for x in range(0, len(fruit_list)): print('%d.'%(x+1), '{:>6}'.format(fruit_list[x].strip())) # Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке и выведите результат. print("\nЗадача 2") list1=[i**2 for i in range(10)] list2=[i**2 for i in range(0,20,2)] print('Список 1:',list1) print('Список 2:',list2) i=0 while i<len(list1): if list1[i] in list2: list1.pop(i) i-=1 i+=1 print('Решение 1:',list1) #другое решение list1=[i**2 for i in range(10)] list2=[i**2 for i in range(0,20,2)] print('Решение 2:',list(set(list1) - set(list2))) # Задача-3: # Дан произвольный список из целых чисел. # Получите НОВЫЙ список из элементов исходного, выполнив следующие условия: # если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два. # и выведите результат print("\nЗадача 3") list4=[i**2 for i in range(0,25,3)] list5=[] print('Исходный список:',list4) for el in list4: if el%2==0: list5.append(el/4) else: list5.append(el*2) print('Результат:',list5)
false
f7ec1c0eca2e27e733473040f284640f75c37a80
flahlee/Coding-Dojo
/pythonFundamentals/string_list.py
586
4.125
4
#find and replace words = "It's thanksgiving day. It's my birthday, too!" day = 'day' print words.find(day) print words.replace(day, "month") #min and max x = [2,54,-2,7,12,98] print min(x) print max(x) #first and last x = ["hello", 2, 54, -2, 7, 12, 98, "world"] newX= [x[0],x[7]] print newX #new list '''sort list first- split list in half- push the list created from the first half to position O of the list created from the second half''' x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() print x first_half= x[len(x)/2] second_half= x[len(x)/2:] print first_half print second_half
true
75f2c8f77f19883b41af604e0bb70318243efcd5
Sameer19A/Python-Basics
/HelloWorld.py
243
4.28125
4
#Compulsory Task 3 name = input("Enter your name: ") age = input("Enter your age: ") print(name) #prints user entered name print(age) #prints user entered age print("") #prints a new empty line print("Hello World!")
true
286cb30b15f984cb922dc229773e6e2eda569ddd
Shreyasi2002/CODE_IN_PLACE_experience
/Section2-Welcome to python/8ball.py
954
4.1875
4
""" Simulates a magic eight ball. Prompts the user to type a yes or no question and gives a random answer from a set of prefabricated responses. """ import random RESPONSES = ["As I see it, yes.", "Ask again later.", "Better not to tell you now." , "Cannot predict now.", "Concentrate and ask again.", "Don't count on it." , "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no." , "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again." , "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes." , "Yes - definitely.", "You may rely on it."] TOTAL_RESPONSES = 19 def main(): question = input("Ask a yes or no question: ") num = 0 # to represent the index of the RESPONSES list while question != "": num = random.randint(0, TOTAL_RESPONSES) print(RESPONSES [num]) question = input("Ask a yes or no question: ") if __name__ == "__main__": main()
true
91cc4ff7b8e7e275ba61d799d81c8eecb7587b7c
Shreyasi2002/CODE_IN_PLACE_experience
/CoreComplete/leap.py
930
4.4375
4
""" Example of using the index variable of a for loop """ def main(): pass def is_divisible(a, b): """ >>> is_divisible(20, 4) True >>> is_divisible(12, 7) False >>> is_divisible(10, 10) True """ return a % b == 0 def is_leap_year(year): """ Returns Boolean indicating if given year is a leap year. It is a leap year if the year is: * divisible by 4, but not divisible by 100 OR * divisible by 400 Doctests: >>> is_leap_year(2001) False >>> is_leap_year(2020) True >>> is_leap_year(2000) True >>> is_leap_year(1900) False """ # if the year is divisible by 400, it is a leap year! if is_divisible(year, 400): return True # other wise its a leap year if its divisible by 4 and not 100 return is_divisible(year, 4) and not is_divisible(year, 100) if __name__ == '__main__': main()
true
d3c9754c8666e8bf95f191e7e4bba9249a10df59
Maryam200600/Task2.2
/4.py
299
4.21875
4
# Заполнить список ста нулями, кроме первого и последнего элементов, которые должны быть равны единице for i in range(0,101): if i==0 or i==100: i='1' else: i='0' print(i, end=' ')
false
edf4a58d87d2c5cef9a6e06e2ace05ad5096268d
djoo1028/Euler
/euler01.py
1,636
4.3125
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' def findSum(arg1): a = arg1 # input value will be range for the summation arr3 = [] # multiple of 3 for i in range(1,x+1): # Remove 0 and include the last spot if 3 * i > x: # If the value is greater than range than break for loop break else: arr3.append(3 * i) # add in to the list print(list(arr3)) arr5 = [] # multiple of 5 for i in range(1,x+1): if 5 * i >= x: break else: arr5.append(5 * i) print(list(arr5)) arr = arr3 + arr5 # Add two list which have multiple of 3 and 5 noDup = [] for i in arr: # Remove duplicate numbers if i not in noDup: # If a number does not exist add and if number is exist move to next index noDup.append(i) print(list(noDup)) # checke SSum = sum(noDup) # Sum all numbers in list print(SSum) #Second idea(shorter version) def findSumShort(arg1): a = arg1 sum = 0 for i in range(a): if (i % 3 == 0) or (i % 5 == 0): # I do not have to think about duplicates because this statement check element at the same time. # For example, if i = 15 then T or T is True so 15 will be added sum. sum += i print(sum) x = int(input()) findSum(x) findSumShort(x)
true
f0b39ddce7802ef09e39599f494c3461fc18007f
rati90/mjeraarmjera
/service/trustorNot.py
2,590
4.15625
4
def hands_table_clear(table, said_cards): """ for some decisions clears table and say lists :param tuple player_hands_table_say not cleared table and say :return tuple player_hands_table_say cleared table and say """ table.clear() said_cards.clear() return table, said_cards def do_you_trust(player_hands_table_say: tuple, player: int): """ The function takes next players choices Yes, No, or Add and depend on it give cards to players and removes :param player_hands_table_say tuples that included three lists :param player the player that made previous decision :return player_hands_table_say tuple modified depend on choices """ all_players_cards = player_hands_table_say[0] table = player_hands_table_say[1] said_cards = player_hands_table_say[2] next_player = player + 1 while True: choice = input( f"Player N {player + 2} Do you trust? choice \"Yes\" or \"No\" or \"Add\" to add more cards:") if choice == "Yes": print(table, said_cards) if sorted(table[len(said_cards)-1:]) == sorted(said_cards): hands_table_clear(table, said_cards) break else: if len(all_players_cards) > next_player: all_players_cards[next_player].extend(table) hands_table_clear(table, said_cards) break elif len(all_players_cards) == next_player: all_players_cards[0].extend(table) hands_table_clear(table, said_cards) break elif choice == "No": if sorted(table[len(said_cards)-1:]) == sorted(said_cards): if len(all_players_cards) > next_player: all_players_cards[next_player].extend(table) hands_table_clear(table, said_cards) break elif len(all_players_cards) == next_player: all_players_cards[0].extend(table) hands_table_clear(table, said_cards) break else: all_players_cards[player].extend(table) hands_table_clear(table, said_cards) break elif choice == "Add": said_cards.clear() return player_hands_table_say else: print("Please write right answer, Yes, No, or add\n") continue print("print here2") return player_hands_table_say
true
573ed22b1e142cdb4e136d7b6c39e697bfe6b917
dosdarwin/BMI
/bmi.py
410
4.21875
4
height = (float(input('what is your height(in cm):')))/100 weight = float(input('what is your weight(in kg):')) BMI = float(weight/(height*height)) if BMI < 18.4: print('your BMI is',BMI, ',too light!') elif 18.5 <= BMI <= 23.9: print('your BMI is', BMI, ',perfect!') elif 24 <= BMI <= 26.9: print('your BMI is', BMI, ',a little too heavy!') else: print('your BMI is',BMI, ',too heavy!!!!!!!!')
false
d999688c971c11599747b52a8f1630c1f56e3542
Ryandalion/Python
/Repetition Structures/Distance Travelled/Distance Travelled/Distance_Travelled.py
777
4.4375
4
# Function that asks the user to input the number of hours they have driven and the speed at which they were driving, the program will then calculate the total distance travelled per hour distanceTravelled = 0; numHours = int(input("Please enter the number of hours you drove: ")); speed = int(input("Please enter the average speed of the vehicle: ")); while (numHours < 0): numHours = int(input("Hours cannot be negative. Please enter the number of hours you drove: ")); while(speed < 0): speed = int(input("Speed cannot be negative. Please enter the average speed of the vehicle: ")); print("HOUR ---------- DISTANCE TRAVELLED") for x in range (1, numHours+1, 1): distanceTravelled = x * speed; print(x, " ", distanceTravelled,"miles");
true
3d9f49a20ba365934e8a47255bde04df1db32495
Ryandalion/Python
/Dictionaries and Sets/File Analysis/File Analysis/File_Analysis.py
1,525
4.1875
4
# Program will read the contents of two text files and determine a series of results between the two, such as mutual elements, exclusive elements, etc. def main(): setA = set(open("file1.txt").read().split()); # Load data from file1.txt into setA setB = set(open("file2.txt").read().split()); # Load data from file2.txt into setB mutualElements = setA.intersection(setB); # Mutual Elements - Intersection between the two sets. The values found in both sets. unionElements = setA.union(setB); # Union Elements - The total array of elements between the two sets exclusiveElements = unionElements - mutualElements; # Exclusive Elements - List of elements that are exclusive to set A and exclusive to set B, combined setAelements = unionElements-setB; # Set A Elements - All elements exclusive to set A only setBelements = unionElements-setA; # Set B Elements - All elements exclusive to set B only print("Here is some data about the text files"); # Display the data to the user print("\nMutual Elements: ", mutualElements); # Mutual elements print(); print("\nExclusive Elements: ", exclusiveElements); # Exclusive elements print(); print("\nAll Elements: ", unionElements); # Union of set A and set B print(); print("\nElements of Set A (exclusive): ", setAelements); # Exclusive elements of set A print(); print("\nElements of Set B (exclusive): ", setBelements); # Exclusive elements of set B print("Set A and Set B Analysis\n"); main(); # Execute main
true
564b68912dd8b44e4001a22d92ff18471a55fbe4
Ryandalion/Python
/Decision Structures and Boolean Logic/Age Calculator/Age Calculator/Age_Calculator.py
568
4.4375
4
# Function takes user's age and tells them if they are an infant, child, teen, or adult # 1 year old or less = INFANT # 1 ~ 13 year old = CHILD # 13 ~ 20 = TEEN # 20+ = ADULT userAge = int(input('Please enter your age: ')); if userAge < 0 or userAge > 135: print('Please enter a valid age'); else: if userAge <= 1: print('You are an infant'); elif userAge > 1 and userAge < 13: print('You are a child'); elif userAge >= 13 and userAge <= 20: print('You are a teen'); elif userAge >= 20: print('You are an adult');
true
8a4d3456f828edb3893db4e6dd836873344b91e9
Ryandalion/Python
/Functions/Future Value/Future Value/Future_Value.py
1,862
4.59375
5
# Program calculates the future value of one's savings account def calculateInterest(principal, interestRate, months): # Function calculates the interest accumulated for the savings account given the arguments from the user interestRate /= 100; # Convert the interest rate into a decimal futureValue = principal * pow(1 + interestRate, months); # Assign the projected balance to the future value variable return futureValue; # Return future value def main(): # Function is responsible for user input and validation, calling required functions, and displaying the project account balance to the user principal = float(input("Enter the current savings account balance: ")); # Collect current balance of savings account while(principal < 0): principal = float(input("Account balance must be greater than zero. Enter the current savings account balance: ")); interestRate = float(input("Enter the current interest rate: ")); # Collect the interest rate for the savings account while(interestRate < 0): interestRate = float(input("Interest rate must be greater than zero. Enter the current interest rate: ")); months = int(input("Enter the number of months you wish to find the projection for: ")); # Collect the number of months the balance will stay in savings while(months < 0): months = int(input("Months be greater than zero. Enter the number of months you wish to find the projection for: ")); account_value = calculateInterest(principal, interestRate, months); # Send the user's inputs as parameters to the calculate interest function and assign the return value to account_value print("The account will be worth $", format(account_value,'.2f'),"in",months,"months"); # Display the projected account balance to the user print("Savings Account Future Value Calculator"); print(); main();
true
39cd605853421bafc6abaeda2b905e3bf06b6c6e
Ryandalion/Python
/Functions/Rock, Paper, Scissors!/Rock, Paper, Scissors!/Rock__Paper__Scissors_.py
2,151
4.46875
4
# Program is a simple rock paper scissors game versus the computer. The computer's hand will be randomly generated and the user will input theirs. Then the program will determine the winner. If it is a tie, a rematch will execute import random; # Import random module to use randint def generate_random(): # Generate a random number that corresponds to either rock,paper, or scissors randNum = random.randint(1,3); return randNum; # Return the generated number to caller def calculate_winner(userHand, computerHand): # Function calculates the winner between computer and user if(userHand == 1 and computerHand == 3): print("User Wins"); elif(userHand == 2 and computerHand == 1): print("User Wins"); elif(userHand == 3 and computerHand == 2): print("User Wins"); elif(userHand == 3 and computerHand == 1): print("Computer Wins"); elif(userHand == 1 and computerHand == 2): print("Computer Wins"); elif(userHand == 2 and computerHand == 3): print("Computer Wins"); else: # If it is a draw then we set tie status to true and return to caller print("It is a tie"); tieStatus = 0; return tieStatus; def main(): # Function is responsible for getting user input and calling the appropriate functions and handling the while loop status = 1; while(status != -1): # Keep looping until status equals -1 computerHand = generate_random(); # Generate a random number and assign it to computer hand print("Select your move"); print("1. Rock"); print("2. Paper"); print("3. Scissors"); userHand = int(input()); # Get user's selection status = calculate_winner(userHand, computerHand); # Send the user's and the computer's hand as arguments to the calculate_winner function if(status == 0): # If the return value from calculate_winner is 0, a tie has occured and we execute another round status = 1; else: # There was a winner and we assign status -1 to exit the while loop and program status = -1; print("Rock, Paper, or Scissors"); print(); main();
true
c19b84caf9895177da8ccbcbd845ef5f03653e4d
Ryandalion/Python
/Functions/Fat and Carb Calorie Calculator/Fat and Carb Calorie Calculator/Fat_and_Carb_Calorie_Calculator.py
1,465
4.34375
4
# Function that gathers the carbohyrdates and fat the user has consumed and displays the amount of calories gained from each def fatCalorie(fat): # Function calculates the calories gained from fat calFat = fat * 9; print("The total calories from",fat,"grams of fat is", calFat,"calories"); def carbCalorie(carbs): # Function calculates the calories gained from carbs carbFat = carbs * 4; print("The total calories from", carbs,"grams of carbs is", carbFat, "calories"); def main(): # Function gathers user information and validates it. Then sends the arguments to their respective functions` fat = int(input("Enter the amount of fat in grams consumed today: ")); # Gather fat consumed from user while(fat < 0): # Validate user input fat = int(input("Input must be greater than zero. Enter the amount of fat in grams consumed today: ")); carbs = int(input("Enter the amount of carbs consumed today: ")); # Gather carbs consumed from user while(carbs < 0): # Validate user input carbs = int(input("Input must be greater than zero. Enter the amount of carbs consumed today: ")); print(); # All inputs have passed validation so we pass the variables to their respective functions fatCalorie(fat); # Call fatCalorie function and pass fat as argument print(); carbCalorie(carbs); # Call carbCalorie function and pass carbs as argument print("Fat and Carb to Calorie Calculator"); print(); main();
true