blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
622b729bde772c0a296e1db8e9c6a84b6f3859e4
andrew-yt-wong/ITP115
/ITP 115 .py/Labs/ITP115_L6_2_Wong_Andrew.py
1,059
4.125
4
# Andrew Wong, awong827@usc.edu # ITP 115, Spring 2020 # Lab 6-2 def main(): # Get the words and convert them into various lists firstWord = input("Please enter a word or statement: ").replace(" ", "").lower() secondWord = input("Please enter a second word or statement: ").replace(" ", "").lower() firstWordList = list(firstWord) fRevCopy = firstWordList[:] fCopy = firstWordList[:] secondWordList = list(secondWord) sCopy = secondWordList[:] sRevCopy = secondWordList[:] fCopy.sort() sCopy.sort() fRevCopy.reverse() sRevCopy.reverse() # Compare all the lists if fCopy == sCopy: print("The two words you entered are anagrams") else: print("The two words you entered are not anagrams") if firstWordList == fRevCopy: print("The first word is a palindrome") else: print("The first word is not a palindrome") if secondWordList == sRevCopy: print("The second word is a palindrome") else: print("The second word is not a palindrome") main()
true
b22ff6b7640b969d1721193139810d2534d00298
banga19/TKinter-Tutorials
/mouse_click_events.py
443
4.1875
4
from tkinter import * # when you click the left mouse button it displays the "left" on the console # the same happens to when you click the right and middle mouse button root = Tk() def RightClick(event): print("Right") def LeftClick(event): print("Left") frame = Frame(root, width=500, height=300) frame.bind("<button-1>", RightClick) frame.bind("<button-2>", LeftClick) frame.pack() root.mainloop()
true
267f66a3f4e5cbedb9cc20533236f7a730a17a27
silverbowen/COSC-1330-Intro-to-Programming-Python
/William_Bowen_Lab5b.py
843
4.375
4
## I used global constants for ease of modding ## in case we return to this program later ## START, END,and INCREMENT set the ## dimensions of the pyramid START = 10 END = 1 INCREMENT = -1 ## SYMBOL sets what the pyramid is made of ## I added spaces on either side of ## the star, to make it nicer SYMBOL = ' * ' ## main is a nested loop that prints ## a pyramid of SYMBOLS def main(): ## first loop, sets terms for each row for count in range(START, END - 1, INCREMENT): ## second loop, nested ## sets number of stars in row, ## based on inverse column number for count in range(count, END - 1, INCREMENT): ## print each individual symbol print(SYMBOL , end='') ## back to first loop, new line ## to make it prettier print('\n') ## call main main()
true
959174c94e9050e2455c72f02567bab5a088a118
silverbowen/COSC-1330-Intro-to-Programming-Python
/William_Bowen_lab4a.py
2,417
4.40625
4
## Define main def main(): ## get measurements to convert, checking for useability miles = float(input('How many miles would you like to convert? ')) if miles < 0: print('\nError! You must enter a positive number of miles!\n') else: print('') fahren = float(input('How many fahrenheit degrees would you like to convert? ')) if fahren > 1000: print('\nError! You must enter fahrenheit degrees equal to or less than 1,000!\n') else: print('') gallon = float(input('How many gallons would you like to convert? ')) if gallon < 0: print('\nError! You must enter a positive number of gallons!\n') else: print('') lbs = float(input('How many pounds would you like to convert? ')) if lbs < 0: print('\nError! You must enter a positive number of pounds!\n') else: print('') inch = float(input('How many inches would you like to convert? ')) if inch < 0: print('\nError! You must enter a positive number of inches!\n') else: print('') ## call all the conversion/printing functions MilesToKm(miles) FahToCel(fahren) GalToLit(gallon) PoundsToKg(lbs) InchesToCm(inch) #calculate and print result for miles to km def MilesToKm(miles): kilos = miles * 1.6 print('It turns out that', miles, 'miles =', kilos, 'kilometers!\n') #calculate and print result for fahrenheit to celsius def FahToCel(fahren): celsi = (fahren - 32) * 5/9 print('It turns out that', fahren, 'fahrenheit =', celsi, 'celsius!\n') #calculate and print result for gallons to liters def GalToLit(gallon): liters = gallon * 3.9 print('It turns out that', gallon, 'gallons =', liters, 'liters!\n') #calculate and print result for pounds to kilograms def PoundsToKg(lbs): kgrams = lbs * .45 print('It turns out that', lbs, 'pounds =', kgrams, 'kilograms!\n') #calculate and print result for inches to centimeters def InchesToCm(inch): centi = inch * 2.54 print('It turns out that', inch, 'inches =', centi, 'centimeters!\n') main()
true
9a0cd7c3f79ad55ce32a7f771f4b146e8ef5aa8a
paripon123/DSC-430-Python
/Hw4/test.py
1,281
4.125
4
def random_list(i): """Random list of number from 0 - 100""" import random num_list = sorted(random.sample(range(0, 100), i)) return num_list def sum_pair_search(lst,number): # O(log N) Binary Search """This is the function that do the binary search and the prove the calculation""" # The list must be sorted!! Important!!!! #O(log N) num_lst = random_list(lst) low = 0 # index of the lowest number high = len(num_lst) - 1 # index of the highest number # Binary search while low <= high: mid = (low + high) // 2 if num_lst[low] + num_lst[high] == number: # Check if the pair are added up to the target number. print('Found It!') print(num_lst[low],'+',num_lst[high],'=',number) return True elif number < num_lst[mid]: # Adjust high : Go search lower half portion high = mid - 1 else: low = mid + 1 # Adjust low : Go search upper half portion print('No Pair Found in this Particular list of number.') return False def main(): while True: num = random_list(20) if sum_pair_search(num,20): break if __name__ == '__main__': main()
true
5170b1ccf7a5e61e25cb0211d1f3c52a08f67472
altareen/csp
/05Strings/asciicode.py
2,511
4.3125
4
# convert from a symbol to an ASCII number numcode = ord("P") print(numcode) # convert from ASCII to a symbol letter = chr(105) print(letter) # using the equality operator with strings password = "basketball" if password == "basketball": print("login successful") # digits come before lowercase letters if "999" < "thousand": print("access granted") # uppercase letters come before lowercase if "PIZZA" < "burger": print("dinner time") num = len("pizza") print(num) # using the capitalize method dinner = "pizza" result = dinner.capitalize() print(result) # applying the lower() method lunch = "CHEESEburger" result = lunch.lower() print(result) # puts all the letters into uppercase fruit = "strawberry" result = fruit.upper() print(result) # check that all characters are letters vegetable = "cauliflower" result = vegetable.isalpha() print(result) dessert = "423chocolates" result = dessert.isalpha() print(result) # check that all characters are numbers meter = "29387392" result = meter.isdigit() print(result) drink = "58waters" result = drink.isdigit() print(result) # remove whitespace from a string beverage = " coffee\n\n\n\n" result = beverage.strip() print(result) # remove whitespace from the right hand side soda = "sprite\n\n\n\n\n\n\n\n\n\n\n" result = soda.rstrip() print(result) # find a substring within another string candy = "chocolate" location = candy.find("cola") print(location) location = candy.find("pizza") print(location) pastry = "jampieapplepiekiwipieraspberrypie" location = pastry.find("pie", 13) print(location) dinner = "beefstewandburgerswithsalad" result = dinner.replace("burgers", "pizza") print(result) bakery = "strawberryjamorangejamkiwijam" result = bakery.count("jam") print(result) menu = "pizzaburgersfriessoda" result = menu.startswith("pizza") print(result) greetings = "hello\n\n\n\n\nworld\n\n\n" print(greetings) # inserting the double quotation mark prose = "She said, \"Hello\" to everyone." print(prose) # using the backslash character path = "C:\\Documents\\homework\\notes.py" print(path) # creating tables with the tab character print("Product\tWeight\tPrice") print("kiwi\t0.15kg\t2.95") # f-strings only work with Python 3.7 or greater #amount = 5 #food = "pizza" #result = f"I had {amount} servings of {food}." #print(result) # Exercise 6.14 score = "X-DSPAM-Confidence:0.8475" location = score.find(":") num = score[location+1:] num = float(num) print(location) print(num) print(type(num)) "hi".
true
dbf4427d8e35dfb7930df9a865c93603e2106255
altareen/csp
/05Strings/stringindexes.py
659
4.1875
4
# extracting a single letter from a string fruit = "watermelon" first = fruit[0] print(first) letter = fruit[5] print(letter) letter = "pizza"[1] print(letter) last = fruit[9] print(last) last = fruit[-1] print(last) letter = fruit[-10] print(letter) vegetable = "cauliflower" quantity = len(vegetable) print(quantity) last = vegetable[quantity-1] print(last) # string slicing dessert = "chocolate" drink = dessert[3:7] print(drink) breakfast = "pineapple" tree = breakfast[0:4] cone = breakfast[:4] print(tree) print(cone) flavor = "strawberry" snack = flavor[5:10] food = flavor[5:] print(snack) print(food) icecream = flavor[:] print(icecream)
true
a24a893b62dcf1015c15aaa3d18f92d1cdea35b6
silviu20/fzwork
/PythonWork/codeexer/reverse_integer.py
481
4.25
4
#! /usr/bin/python # -*- coding: utf-8 -*- """ Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 """ class Solution: # @return an integer def reverse(self, x): if x>0: y_str = str(x) y_str = y_str[::-1] return int(y_str) elif x<0: x = -x y_str = str(x) y_str = y_str[::-1] return -int(y_str) else: return 0
true
c263dcbc053d4e0ad67b8e898c559501723b964f
ChocolatePadmanaban/AlgosAndDs
/mit_6.0001/ps1/ps1c.py
1,415
4.15625
4
import random # Get the input annual_salary= float(input("Enter the starting annual salary: ")) monthly_salary= annual_salary/12 # Fixed Parameters semi_annual_raise=.07 r=0.04 portion_down_payment = .25 total_cost=1000000 down_payment = total_cost*portion_down_payment #set problem parameters epsilon = 100 bisection_search_steps = 0 max_portion = 10000 min_portion = 1 # Check if payment is possible if monthly_salary < down_payment/36: print("It is not possible to pay the down payment in three years.") else: while True: portion_saved = random.randint(min_portion,max_portion) monthly_salary= annual_salary/12 bisection_search_steps+=1 month_count=0 current_savings=0 while current_savings < down_payment: current_savings += current_savings*r/12 current_savings += monthly_salary*portion_saved/10000 month_count += 1 if month_count % 6 == 0: monthly_salary += monthly_salary*semi_annual_raise present_epsilon= current_savings - down_payment if month_count == 36 and abs(present_epsilon) < epsilon: break elif month_count > 36 : min_portion = portion_saved + 1 else : max_portion = portion_saved - 1 print("Best savings rate:", portion_saved/10000) print("Steps in bisection search:", bisection_search_steps)
true
94b55dc0a52f6788bf1649786a0f8a776c5697f3
mariocpinto/0008_MOOC_Getting_Started_with_Python
/Exercises/Week_07/assignment_5.1.py
702
4.21875
4
# Write a program that reads a list of numbers until "done" is entered. # Once done is entered, print count, total and avergae of numbers. # If the user enters anything other than a number, # print an error message and skip to the next number. # Initialize count & sum count = 0 sum = 0 while True : input_num = input('Enter a number: ') if input_num == 'done' : break try: num = float(input_num) except: print('Invalid Input') continue count = count + 1 sum = sum + num print('Count = ',count) print('Total = ',sum) if count != 0 : print('Average = ',sum/count) else: print('Average = 0')
true
7ef3e6b2bf9ed19c2853b541b16abadf1cc8b971
DynamicManish/Guessing_game
/guessing_game.py
1,448
4.15625
4
import random as r import time as t random_value = r.randint(2,9) guesses = 0 #user haven't made any guess yet! value = 0 user_name = input('Howdy?May I know your name? ').strip().capitalize() t.sleep(1) print("Hello,"+"{}!".format(user_name)) t.sleep(1) ques_choice = input('Are you ready to guess?[Y/N]:').strip() if ques_choice == 'y': print('Hello,'+"{}".format(user_name)) t.sleep(1) print("I am thinking of a number between 1 to 10!") t.sleep(1) elif ques_choice == 'n': print("We're sorry, Will meet you later!") t.sleep(1) exit() else: print("Wrong input!") t.sleep(1) exit() while not (random_value == value): number = int(input('Enter your guess here: ')) guesses = guesses+1 if number == random_value: t.sleep(0.75) print("Brilliant!") print("You guessed it correctly,the correct number is {}".format(random_value)) if guesses == 1: print("It took you {}".format(guesses)+" try in total!") t.sleep(1) else: print("It took you {}".format(guesses)+" tries in total!") t.sleep(1) exit() elif number < random_value: t.sleep(1) print("Guess higher") elif number > random_value: t.sleep(1) print("Guess lower") else: t.sleep(1) print("Wrong inputs!") exit()
true
a99e65bc94d699eedf234968d4d1d4b6fd70f2ad
Fractured2K/Python-Sandbox
/tuples_sets.py
1,029
4.34375
4
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # Simple tuple fruit_tuple = ('Apple', 'Orange', 'Mango') print(fruit_tuple) # Using constructor fruit_tuple_constructor = tuple(('Apple', 'Orange', 'Mango')) print(fruit_tuple_constructor) # Get value by index print(fruit_tuple[1]) # Can not change values in tuple # fruit_tuple[1] = 'Grape' # Tuples with one value should have a trailing comma fruit_tuple_trailing = ('Apple',) print(fruit_tuple_trailing) # Delete tuple del fruit_tuple_trailing # length print(len(fruit_tuple)) # A Set is a collection which is unordered and unindexed. No duplicate members. fruit_set = {'Apple', "Orange", 'Mango', 'Apple'} print(fruit_set) # Check if in set print('Apple' in fruit_set) # True print('Apples' in fruit_set) # False # Add to set fruit_set.add('Grape') print(fruit_set) # Remove from set fruit_set.remove('Grape') print(fruit_set) # Clear set fruit_set.clear() print(fruit_set) # Delete set # del fruit_set # print(fruit_set)
true
dc1b1e6fd9a2a88bdb48ab9ac21d806939640ed7
HyperPalBuddy/Rando-Python-Codes
/Python_stacks.py
1,090
4.21875
4
def createStack(): stack = [] return stack def isEmpty(stack): return len(stack) == 0 def push(stack, number): if len(stack) == size: print("Stack Overflow") return stack.append(number) def pop(stack): if isEmpty(stack): print("Stack Underflow") return return stack.pop() def peek(stack): if isEmpty(stack): print("Stack Is Empty") return else: n = len(stack) print("Peek Element is:", stack[n - 1]) def display(stack): print(stack) stack = createStack() size = int(input("Enter The Size Of Stack")) print("Menu\n1.push(p)\n2.pop(o)\n3.peek(e)") choice = 1 while choice != 'q': print("Enter Your Choice") ch = input() choice = ch.lower() if choice == 'p': push(stack, int(input("Enter Input Value"))) display(stack) elif choice == 'o': pop(stack) display(stack) elif choice == 'e': peek(stack) else: print("Enter Proper Choice Or q to Quit")
true
af3df83e40ec18a4433cbe8b3d35f86bf9d67655
PHOENIXTechVault/Beginner-Python-Codes
/functions.py
1,855
4.375
4
# Manually printig out hello welcome without the use of a function print("hello welcome") print("hello welcome") print("hello welcome") print("hello welcome") print("hello welcome") def print_welcome_messsage(): #definig a function to print out the welcome message 5 times print("Hello welcome\n"*5) def ask_name(): print("whats your name?") print_welcome_messsage() #calling the function ask_name() #calling the function # Built-in functions print(), str(), abs() # lambda functions out = lambda message : message*5 #writting the lambda function form of our previouse written function print(out("hello welcome\n")) # User defined functions def ask_name(person): #creating your own function thus user defined functions print("Welcome " + person) print("whats your name?" + person) # Arguments & Parameters ask_name("Janet") ask_name("Joe") ask_name("Kevin") ask_name("Josh") #calling each function and passing in an argument # return values and return statement def ask_name(age): new_age = age * 10 age2 = new_age + 100 if new_age > 50: return "Welcome Granny" elif new_age <= 40: return "hi you are welcomed" else: return "You are a youth" print(ask_name(80)) print(ask_name(10)) print(ask_name(8)) print(ask_name(4)) # local scopes and Global scopes a = 45 def ask_age(age): # Global statement. This helps declare a local variable as a global variable which then can be used outside of functions and in other functions global new_age global age2 new_age = age * a age2 = new_age + a print(new_age) print(age2) def greet(name): print("Hello " + name) print(new_age) print(age2) ask_age(5) greet("Sam") print(new_age) print(age2)
true
ee1b6cde06a6d04938042060fe2dade87224e5df
PHOENIXTechVault/Beginner-Python-Codes
/logical-operators.py
920
4.15625
4
# AND a = 5 b = 5 c = 7 print(a == b and c > b) #return True since both conditions are True print((a != b and c > b) and c > a) #return False since one of the conditions is False # OR print(a == b or c > a) #return True since both conditions are True print(a != b or c > b) #return True since one of the conditions is True print(a == c or c < b) #return False since both conditions are False # NOT a = False b = not a #will return the opposite value of False which is True print(b) c = True d = not c #will return the opposite value of True which is False print(d) sex = "male" age = 18 if sex == "male" and age >= 18: print("You are allowed to come to the party") else: print("You not allowed") if sex == "male" or age >= 18: print("You are allowed to come to the party") else: print("You not allowed")
true
f25e37f28903a6986791b7162058af0ed17dffe8
fredyulie123/Python-Programming
/Yifeng HE Exam2.py
2,532
4.125
4
# Exam 2 Yifeng He # Trip Planner planner_name = 'C:/Users/Yifeng He/Desktop/graduated/2nd graduate semester/Python/Trip Planner.txt' # create file path print('Welcome to the road trip planner!') ## recording trip details allstation = [] # prepare for append trip details gasprice = 3 # gas per gallon price mpg = 35 # mile per gallon total_cost = 0 ready = input('Are you ready for make a trip plan (Enter \'n\' for no)?\n>>') affirmative = ['Yes', 'Y', 'yes', 'y', 'yup', 'Yup', 'Sure', 'sure'] if ready in affirmative: # ask for starting location start_loc = str(input('Please enter your starting location:\n>>')) origin_loc = start_loc # departure place # ask for destination location desti_loc = str(input('From '+ start_loc + ', where will you travel?\n>>')) # ask for distance distance = float(input('How far away is ' + desti_loc + ' from ' + start_loc +'?\n>>')) # calculate the cost cost = (distance/mpg)*gasprice total_cost = total_cost + cost # append trip detail allstation.append([start_loc, desti_loc, round(distance,2), round(cost,2)]) # ask if have another plan ready = input('Will you be travelling beyond ' + desti_loc + ' (Enter \'n\' for no)?\n>>') # ask for another plan while ready in affirmative: start_loc = desti_loc desti_loc = str(input('From '+ start_loc + ', where will you travel?\n>>')) distance = float(input('How far away is ' + desti_loc + ' from ' + start_loc +'?\n>>')) cost = (distance/mpg)*gasprice total_cost = total_cost + cost # append trip detail allstation.append([start_loc, desti_loc, round(distance,2), round(cost,2)]) ready = input('Will you be travelling beyond ' + desti_loc + ' (Enter \'n\' for no)?\n>>') final_loc = desti_loc # destination place #write down overview overview = 'Your entire trip from ' + origin_loc + ' to ' + final_loc + ' will cost $' + str(round(total_cost,2)) + '\n' with open (planner_name,'w', encoding='utf-8') as pn: pn.write(overview) else: print('Please restart the trip planner when you\'re ready. ') # write down details for p in range(0,len(allstation)): start_station = allstation[p][0] desti_station = allstation[p][1] per_cost = allstation[p][3] detail = start_station + ' to ' + desti_station + ' will cost $' + str(round(per_cost,2)) + '\n' with open (planner_name,'a', encoding='utf-8') as pn: pn.write(detail)
true
696432da440dea2a60515d028a5e75fa1dc66528
kamit17/Python
/W3Resource_Exercises/Strings/6.py
733
4.625
5
#6. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Go to the editor #Sample String : 'abc' #Expected Result : 'abcing' #Sample String : 'string' #Expected Result : 'stringly' def string_end(given_string): length_given_string = len(given_string) if length_given_string > 2: if given_string[-3:] == 'ing': #if last 3 chars are ing given_string += 'ly' else: given_string += 'ing' return given_string print(string_end('ab')) print(string_end('string')) print(string_end('happily'))
true
25ee3fc42087fd87633e5b9bd84834716f7e4e0d
kamit17/Python
/AutomateTheBoringStuff/Chapter7/password_checker.py
764
4.125
4
''' A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength. ''' #Program to detect if password is strong or not import re #TODO: create Regex for password which mathes all the criteria above pass_regex= re.compile(r''' [a-zA-Z0-9@]{8,} ''',re.VERBOSE) #TODO: Function to test above password regex def pass_strength(pw): if re.match(pass_regex,pw): return True else: return False #check if password is strong or not if __name__ == '__main__': pw = input('Enter your password: ') if pass_strength(pw): print('Strong password!') else: print('Weak Password')
true
1d0d569f1d6d2693964cb452ebc2ef9b5628f1e7
kamit17/Python
/Think_Python/Chp7/Exercise/ex6.py
407
4.34375
4
#Count how many words occur in a list up to and including the first occurrence of the word “sam”. (Write your unit tests for this case too. What if “sam” does not occur?) def sam_count(names): counter = 0 for name in names: if name != 'sam': counter += 1 else: break return counter print(sam_count(['Harry','Bob','Dylan','Chris','sam','bill']))
true
45c70edbcf891323fca8d4fe90816adca83b4b1e
kamit17/Python
/Think_Python/Chp7/Examples/collatz_sequence_1.py
1,072
4.28125
4
def next_collatz(n): if n % 2 == 0: return n // 2 else: return 3 * n + 1 def collatz_sequence(n): """ assembles a list based on next collatz function and then prints that list. """ assert type(n) == int assert n > 0 sequence = [n] while n != 1: n = next_collatz(n) sequence.append(n) return sequence def collatz_steps(n): """For an integer n returns the number of steps before the Collatz function terminates at 1.""" steps = 0 while n !=1: n = next_collatz(n) steps +=1 return steps #for i in range(1,10): # print(collatz_sequence(i)) #for x in range (1,10): # print("{} takes {} steps to resolve.".format(x,collatz_steps(x))) for x in range(1,100): if collatz_steps(x) > 100: print("{} takes {} steps to resolve.".format(x,collatz_steps(x))) # print(collatz_steps(x)) break high = 0 for x in range(1,10**6): this_result = collatz_steps(x) if this_result > high: high = this_result print(x,"takes",high,"steps")
true
d0bb4429e990189944bb9550488f7f5bbfcf5fe1
kamit17/Python
/PCC/Chp8/pizza.py
536
4.4375
4
#Passing an aribitrary Number of Arguments def make_pizza(*toppings): # the * in the parameter tells python to make an empty tuple andpack #whatever value it receives into this tuple. #"""Print the list of toppings you have requested""" #print(toppings) """Summarize the pizza we are about to make""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese')
true
e659f051f0d0730bdd8e2c8f60271db08151a2bb
kamit17/Python
/PCC/Chp7/Super_powers.py
1,077
4.4375
4
""" 7-10. Dream Vacation: Write a program that polls users about superpowers . Write a prompt similar to if you could have one superpower then what would it be? Include a block of code that prints the results of the poll. """ #a place holder dictionary to store the responses superpowers= {} polling_active = True #Write the prompts #name_prompt = '\nWhat is your name? ' #question_prompt = '\nIf you could have one super power then what would it be ? ' while polling_active: #each pass through the while loop prompts for the user name and response name = input('\nWhat is your name? ') superpower= input('\nIf you could have one super power then what would it be ? ') #store the question in the dictionary superpowers[name] = superpower #find out if anyone else is going to take the quiz repeat = input('Would someone else take the quiz? (yes/no)') if repeat == 'no': polling_active = False #Showing the results for name,superpower in superpowers.items(): print(name + ' Would like to have this superpower: ' + superpower)
true
68e9fed9678b9c5996525d08c2d96df277844d0a
kamit17/Python
/W3Resource_Exercises/Strings/ex3.py
750
4.15625
4
""" Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Sample String : 'w3resource' Expected Result : 'w3ce' Sample String : 'w3' Expected Result : 'w3w3' Sample String : ' w' Expected Result : Empty String """ def stringcon(str1): if len(str1) < 2: return '' return str1[0:2] + str1[-2:] response = '' while True: test_string = input('Enter the string to be tested: ') print(stringcon(test_string)) print('Do you want another string to be tested? Yes to continue and No to exit ') response= input() if response == 'Yes': continue else: break print('Thank you!')
true
ec326316fb546cf8ebcd25e18e1a81cdf845ef70
kamit17/Python
/PCC/Chp8/cities.py
560
4.65625
5
""" 8-5. Cities: Write a function called describe_city() that accepts the name of a city and its country . The function should print a simple sentence, such as Reykjavik is in Iceland . Give the parameter for the country a default value . Call your function for three different cities, at least one of which is not in the default country . """ def describe_city(name,country = "iceland"): print(name.title() + " is the capital of " + country.title()) describe_city("reykjavik") describe_city("new delhi","india") describe_city("bucharest","romania")
true
c205b507ef49f227a8535774a0373e95357a78a9
kamit17/Python
/W3Resource_Exercises/Strings/ex8.py
385
4.40625
4
#Write a Python function that takes a list of words and returns the length of the longest one def length_longest(words_list): word_len = words_list[0] for i in words_list: if len(i) > len(word_len): word_len = i return len(word_len) a_list = ["Hello","Hi","Applebees","pineapple"] print("The lenght of the longest word is: ",length_longest(a_list))
true
b3d96325222b5bdb4866d55a6d7eb48c19ba8a55
kamit17/Python
/Think_Python/Chp3/Exercises/ex5.py
900
4.3125
4
# Use for loops to make a turtle draw these regular polygons(regular means all sides the same # # lengths,all angles the same): # • An equilateral triangle # • A square # • A hexagon (six sides) # • An octagon (eight sides) import turtle #Allows us to use turtles wn = turtle.Screen() # creates a playground for turtles tess = turtle.Turtle() # Create a turtle, assign to tess for _ in range(3): tess.left(120) # Move tess along tess.forward(90) tess.color("blue") tess.forward (20) # • A square for _ in range(4): tess.forward(40) tess.left(90) # Move tess along tess.right(120) tess.color("red") # • A hexagon for _ in range(6): tess.forward(90) tess.left(60) # Move tess along tess.forward(80) tess.color("yellow") # • An octagon (eight sides) for _ in range(8): # Move tess along tess.forward(90) tess.right(45) window.mainloop()
true
9da2414b95d9cf62789bc8fbecec341a686384b4
kamit17/Python
/PCC/Chp8/printing_models.py
868
4.3125
4
""" Consider a company that creates 3D printed models of designs that users submit. Designs that need to be printed are stored in a list, and after being printed they’re moved to a separate list. The following code does this without using functions: """ #Start with some designs that need to be printed unprinted_designs = ['iphone case','robot pendant','dodecahedron'] completed_models = [] #Simulate printing each design, until none are left #Move each design to completed_models after printing. while unprinted_designs: current_design = unprinted_designs.pop() #simulate creating a 3D print fromo the design. print("Printing model: " + current_design) completed_models.append(current_design) #Display all completed models. print("\nTHe following models have been printed.") for completed_model in completed_models: print(completed_model)
true
11fcf4fdd977a27405e64abbd6cfb89a1c266140
kamit17/Python
/W3Resource_Exercises/Strings/ex14.py
405
4.28125
4
# Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). Go to the editor #Sample Words : red, white, black, red, green, black #Expected Result : black, green, red, white,red sample_words = input('Enter a comma seperated list of words:') words = sample_words.split(",") words = sorted(words) print(",".join(words))
true
50ae04b492f9c9745132bbca770610cbd8f751bc
kamit17/Python
/W3Resource_Exercises/Strings/ex25.py
1,113
4.8125
5
#. Write a Python program to create a Caesar encryption. #c = (x -n ) % 26 where x is the ASCII key of the source message, n is the key, and 26 since there are 26 characters def encrypted(string,shift): #empty string to hold the cipher cipher = "" #traversing the plain text for char in string: # if char is empty if char == " ": cpiher = cipher + char # Encrpyt uppercase characters in plain text #note: The chr() function (pronounced “char”, short for “character”) takes an integer ordinal and returns a single-character string. The ord() function (short for “ordinal”) takes a single-character string, and returns the integer ordinal value. elif char.isupper(): cipher = cipher + chr((ord(char)+shift-65)%26 + 65) #Encrypt lower case characters in plain text else: cipher = cipher + chr((ord(char)+shift-97)%26 + 97) return cipher text = input("enter the text: ") s = int(input("Enter the shift key: ")) print("The original string is : ",text) print('The encrypted msg is : ',encrypted(text,s))
true
5fa4fc1436939b2fc55959ff69777aa79bf357f8
kamit17/Python
/AutomateTheBoringStuff/RegularExpressions/PhoneNumber.py
1,311
4.46875
4
#PhoneNumber.py - A simple program to find phone number in a string without regular expressions. def isPhoneNumber(text): #415 - 555- if len(text) !=12: #checks if string is exactly 12 characters return False #not phone number -sized for i in range(0,3): if not text[i].isdecimal(): #checks if area code consists of only numeric characters return False #no area code if text[3] !='-': #nneds to have a hyphen after the area code return False #missing - for i in range(4,7): if not text[i].isdecimal(): return False if text[7] !='-': return False for i in range(8,12): if not text[i].isdecimal(): return False return True #print('415-555-4242 is a phone number:') #print(isPhoneNumber('415-555-4242')) #print('Moshi moshi is a phone number:') #print(isPhoneNumber('Moshi moshi')) message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.' foundNumber = False for i in range(len(message)): chunk = message[i:i+12] if isPhoneNumber(chunk): print('Phone number found: '+ chunk) foundNumber = True if not foundNumber: print('Could not find any phone numbers.') print('Done')
true
5ea2af667b11e03c79aa1afd12dc28c5dfaa95ad
kamit17/Python
/AutomateTheBoringStuff/DataTypes/string_method2.py
1,161
4.53125
5
# -*- coding: utf-8 -*- #python code to demonstrate working of string methods str = '''Betty Botta bought a bit of butter.“But,” she said, “this butter's bitter!''' str2 = 'butter' #using startswith() to find if str starts with str2 if str.startswith(str2): print("str begins with str2") else: print('str does not begin with str2') #using endswith() to find if str ends with str2 if str.endswith(str2): print('str ends with str2') else: print('str does not end with str2') # checking if all characters in str are upper cased if str.isupper(): print('All characters in str are upper case') else: print('All characers in str are not upper case') # checking if all characters in str1 are lower cased if str2.islower() : print ("All characters in str1 are lower cased") else : print ("All characters in str1 are not lower cased") str =str.lower() print('The lower case converted string is : '+str) str2 = str2.upper() print('The upper case converted string is : '+str2) str3 = str.swapcase() print('The swapped case string is : '+str) str4 = str.title(); print ("The title case converted string is : " + str4)
true
ac016d41898a659d95df620ec23aa30d21a52a5a
kamit17/Python
/AutomateTheBoringStuff/DataTypes/deepcopyexample.py
761
4.71875
5
# Python code to demonstarate copy operation # importing "copy for copy Operations" import copy # initializing list 1 list1 = [1, 2, [3, 5], 4] # using deepcopy to deep copy list2 = copy.deepcopy(list1) # original elements of the list print("the original elements before deepcopy") for i in range(0, len(list1)): print(list1[i], end=' ') print("\r") # adding an element to the new list list2[2][0] = 7 # checking if the change is being reflected print('The new list of element after deep copy') for i in range(0, len(list2)): print(list2[i], end=' ') print('\r') # change not being reflected in Original list # as it is deep copy print('The original elements after deep copy are :') for i in range(0, len(list1)): print(list1[i], end=' ')
true
ac4e5aea1c303989bd665f2ea804827e50c5d7c3
kamit17/Python
/examples/myMadlib.py
1,879
4.25
4
""" Once upon a time, deep in an ancient jungle, there lived a {animal}. This {animal} liked to eat {food}, but the jungle had very little {food} to offer. One day, an explorer found the {animal} and discovered it liked {food}. The explorer took the {animal} back to {city}, where it could eat as much {food} as it wanted. However, the {animal} became homesick, so the explorer brought it back to the jungle, leaving a large supply of {food}. The End """ storyFormat ='''Once {people} went on a journey together. On their way there was a deep {place}. There was no {item}; so they swam across the {place}. They all got safely to the other bank. “Are we allsafe?” asked one of the Wise Men, “Let us count and see,” said the others. The first man counted, “One, two, three, four, five,” and said, “Look ! one of us is missing. There are only five of us here.” He counted only the others. “You are silly,” said a second Wise Man. “Let me count, ''' def tellStory(): userPicks = dict() addPick('people', userPicks) addPick('place', userPicks) addPick('item', userPicks) story = storyFormat.format(**userPicks) print(story) def addPick(cue, dictionary): '''Prompt for a user response using the cue string, and place the cue-response pair in the dictionary. ''' prompt = 'Fill the blank for ' + cue + ': ' response = input(prompt).strip() # 3.2 Windows bug fix dictionary[cue] = response tellStory() input("Press Enter to end the program.")
true
3f7eb92c2a6cd9ba73ab5dd3c9692528ce9e5316
kamit17/Python
/Think_Python/Chp13/Examples/read_whole_file.py
434
4.125
4
"""Another way of working with text files is to read the complete contents of the file into a string, and then to use our string-processing skills to work with the contents.""" # A simple example to count the number of words in a file f = open("/Users/maverick/GitHub/Python/Think_Python/Chp13/Examples/friends.txt") content = f.read() f.close() words = content.split() print("There are {0} words in the file.".format(len(words)))
true
f877f83d6e29bb5f104414ae48403ba91be76d0e
kamit17/Python
/W3Resource_Exercises/Strings/ex2.py
407
4.4375
4
#Write a Python program to count the number of characters (character frequency) in a string. def char_count(input_string): """Funciton to calculate the character frequency in a string""" frequency = {} for char in input_string: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 return frequency print(char_count('Data science'))
true
5efb695bfbc93a94fd87715af11c74efb748c25f
kamit17/Python
/W3Resource_Exercises/Loops and Conditionals/temperature_convert.py
718
4.1875
4
""" Write a Python program to convert temperatures to and from celsius, fahrenheit. [ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ] Expected Output : 60°C is 140 in Fahrenheit 45°F is 7 in Celsius """ def convert(temp,unit): unit = unit.lower() if unit == 'c': temp = 9.0/5.0 * temp +32 # return '%s degrees Farenheit'% temp if unit == 'f': temp =(temp-32) /9.0 * 5.0 return '%s degress Celcius'% temp intemp = int(input('What is the temperature?\n')) inunit = str(input('What is the measure of unit (f or c ):\n')) #print(convert(intemp,inunit)) print('The converted temperature is :',convert(intemp,inunit))
true
73ca90f6464b5b0d5c94006c89624062bd0510b2
kamit17/Python
/LPTHW/ex33_1.py
442
4.21875
4
""" Convert this while-loop to a function that you can call, and replace 6 in the test (i < 6) with a variable. """ def loop(max,step): i = 0 numbers = [] for i in range(0,max,step): print(f"At the top i is {i}") numbers.append(i) print("Numbers now: ",numbers) print(f"At the bottom i is {i}") return numbers numbers = loop(10,2) print('The numbers: ') for num in numbers: print(num)
true
24031668fb0e494eb7c1197a0a27060d8a2d10a6
Gonz8088/ITEC3312
/Homework/Homework04.py
1,883
4.15625
4
# PROGRAMMER: Paul Gonzales # DATE: month day, 2019 # ASSIGNMENT: Homework 04 # ALGORITHM: The StopWatch class is built according to the specification, # and uses a datetime object, and timedelta object from the datetime moduleself. # when a StopWatch object is created, the __startTime attribute is initialized # using the now().time() method. The for loop adds the sum of integers from 1 to # 1000000, and then the stopwatch.stop() method is called to get the current time # at the end of the loop. The elapsed time is then determined by creating timedelta # objects. One for the __startTime, and one for the __endTime. The __startTime # timedelta object is subtracted from the __endTime timedelta object, and the # result is returned as a string. from datetime import datetime as dt from datetime import timedelta as td class StopWatch: """docstring for StopWatch.""" def __init__(self): self.__startTime = dt.now().time() self.__endTime = None def get_startTime(self): return self.__startTime def get_endTime(self): return self.__endTime def get_ElapsedTime(self): self.__c = td(hours=self.__startTime.hour, minutes=self.__startTime.minute, \ seconds=self.__startTime.second, milliseconds=self.__startTime.microsecond) self.__d = td(hours=self.__endTime.hour, minutes=self.__endTime.minute, \ seconds=self.__endTime.second, milliseconds=self.__endTime.microsecond) return str(self.__d-self.__c) def start(self): self.__startTime = dt.now().time() return def stop(self): self.__endTime = dt.now().time() return def main(): stopwatch = StopWatch() for i in range(1000001): i += i stopwatch.stop() print("Sum:", i) print("Elapsed Time:", stopwatch.get_ElapsedTime()) return if __name__ == "__main__": main()
true
4a29a67f51e667bba2a0ab786253d0b7fe84e3cc
Alonski/superbootcamp
/sentence_statistics.py
626
4.4375
4
def word_lengths(s): # ==== YOUR CODE HERE === return [len(word) for word in s.split()] # ======================= result = word_lengths("Contrary to popular belief Lorem Ipsum is not simply random text") print("Result:", result) assert result == [8, 2, 7, 6, 5, 5, 2, 3, 6, 6, 4] print("OK") def max_word_length(s): # ==== YOUR CODE HERE === return max(word_lengths(s)) # return max([len(word) for word in s.split()]) # ======================= result = max_word_length("Contrary to popular belief Lorem Ipsum is not simply random text") print("Result:", result) assert result == 8 print("OK")
true
4cde5a8cead3d59d99b0030cd22b2f1cd2f93238
kevin-sooter/Intro-Python-I
/src/dictionaries.py
1,360
4.71875
5
#<<<<<<< master # Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. ======= #""" #Dictionaries are Python's implementation of associative arrays. #There's not much different with Python's version compared to what #you'll find in other languages (though you can also initialize and #populate dictionaries using comprehensions just like you can with #lists!). #The docs can be found here: #https://docs.python.org/3/tutorial/datastructures.html#dictionaries #For this exercise, you have a list of dictionaries. Each dictionary #has the following keys: # - lat: a signed integer representing a latitude value # - lon: a signed integer representing a longitude value # - name: a name string for this location """ #>>>>>>> master waypoints = [ { "lat": 43, "lon": -121, "name": "Spain" }, { "lat": 41, "lon": -123, "name": "Colombia" }, { "lat": 43, "lon": -122, "name": "Mexico" } ] # Write a loop that prints out all the field values for all the waypoints for item in waypoints: print(item.values()) # Add a new waypoint to the list waypoints.append({ "lat": 22, "lon": -181, "name": "Texas" }) print(waypoints)
true
3f191e135d45d0984a84ccec412cd5337b7772cd
OlehHnyp/Home_Work_7
/Home_Work_7_Task_1_implisit.py
1,396
4.3125
4
import math as m def triangle_area(): """ This function calculate an area of triangle Input parameters: Output: float """ while 1: try: triangle_side = float(input( "Insert side of triangle:" )) triangle_height = float(input( "Insert triangle height taken from that side:" )) return round(0.5 * triangle_side * triangle_height, 2) except ValueError: print("Try again!") def rectangle_area(): """ This function calculate an area of rectangle Input parameters: Output: float """ while 1: try: rectangle_lenght = float(input( "Insert rectangle lenght:" )) rectangle_height = float(input( "Insert rectangle height:" )) return round(rectangle_lenght*rectangle_height, 2) except ValueError: print("Try again!") def circle_area(): """ This function calculate an area of circle Input parameters: Output: float """ while 1: try: circle_radius = float(input( "Enter circle radius:" )) return round(m.pi * m.pow(circle_radius,2), 2) except ValueError: print("Try again!")
true
5abddd2980f17f30104ea41795c648bab8a5fc43
bennywinefeld/CodiacClub
/ttt1.py
2,276
4.15625
4
# Board is represented by an array with indexes from 0 to 0 # each array element can contain values: ' ','X','O' def drawBoard(board): print(board) print("+---+---+---+") for i in range(3): print("| {} | {} | {} |".format(board[3*i],board[3*i+1],board[3*i+2])) print("+---+---+---+") # Insert X or O to board, for ex: makeMove(myBoard,'X',3) def makeMove(board,X_or_O,position): if(board[position] != ' '): print("This cell is already taken, choose another") return False board[position] = X_or_O return True # Check if current player won by the last move # Variable b stands for board. Used one letter var name to make expressions look short def checkIfWon(b,X_or_O): w = X_or_O * 3 if ((b[0]+b[1]+b[2] == w) or (b[3]+b[4]+b[5] == w) or (b[6]+b[7]+b[8] == w) or (b[0]+b[3]+b[6] == w) or \ (b[1]+b[4]+b[7] == w) or (b[2]+b[5]+b[8] == w) or (b[0]+b[4]+b[8] == w) or (b[2]+b[4]+b[6] == w)): return True return False #===================================================================== # Main program starts here #===================================================================== # Initialize the global variables controlling the gamegame # Reset the board with all ' ', set gameOver flag to False, player 'X' starts first myBoard = [' ']*9 gameOver = False nowPlays = 'X' # Draw initial (empty) drawBoard(myBoard) # Start the game and continue until someone wins or board is full while (not gameOver): # Ask current player to make a move. Repeat asking if move is illegal position = int(input(nowPlays + " where do you want to go (1-9)? ")) - 1 while (not makeMove(myBoard,nowPlays,position)): position = int(input(nowPlays + " where do you want to go (1-9)? ")) - 1 # Draw the board to display all the cells filled so far drawBoard(myBoard) # Check if the last move has won the game if (checkIfWon(myBoard,nowPlays)): print(nowPlays + " , you have won!") gameOver = True # Check if board is full. If yes, it's a tie! if (not ' ' in myBoard): print("It's a tie!") gameOver = True # Switch current player if (nowPlays == 'X'): nowPlays = 'O' else: nowPlays = 'X'
true
3a45484bb82aa4f372c847992d2de7a2edf5c974
dr34mh4ck/lca-python
/node.py
1,949
4.28125
4
''' *** Binary tree structure is composed by Nodes (left and right) with a *** reference to its parent and the value the Node holds ''' class Node: value = None left = None right = None parent = None ''' *** empty initialization for the Node ''' def __init__(self): pass ''' *** Checks wether this node has value assigned or not ''' def is_empty(self): return self.value is None ''' *** Inserts a Node into the tree assigning the correct parent for the Node ''' def push_impl(self, _value, _parent): if self.value is None: self.value = _value self.parent = _parent elif self.value < _value: if self.right is None: self.right = Node() self.right.push_impl(_value, self) elif self.value > _value: if self.left is None: self.left = Node() self.left.push_impl(_value, self) ''' *** Inserts a Node into the tree ''' def push(self, _value): self.push_impl(_value, None) def print_pre_order(self): self.print_pre_order_impl('') ''' *** Prints the tree with preorder path ''' def print_pre_order_impl(self, prefix): if self.value is None: print('-') else: print(prefix + str(self.value)) if self.left is not None: self.left.print_pre_order_impl(prefix + ' ') if self.right is not None: self.right.print_pre_order_impl(prefix + ' ') def path_to(self, _value): path = '' if self.value is None: return '' else: if self.value > _value: path += self.left.path_to(_value) elif self.value < _value: path += self.right.path_to(_value) path += str(self.value) + '-' return path
true
d97b71f4e3a18bcc8d8dc325210b70bd605ecf37
AkshadaSayajiGhadge594/Serial-Programming
/SerialParallelProg.py
222
4.21875
4
print("----------Serial Parallel Programming-----------"); def square(n): return (n*n); #input list: arr=[1,2,3,4,5] #empty list to store result: result=[]; for num in arr: result.append(square(num)); print(result)
true
6ee4d8571be4770511c0e065d839ce17fb068e3d
aisha109/project-97
/guessingGame.py
202
4.15625
4
Question = "Guess a number between 1 and 9" print(Question) QuestionInput = input("Enter your guess") if(QuestionInput == 8 ): print("YOU ARE RIGHT") else: print("ANOTHER GUESS")
true
300636cb53b57670c93110ab7fce3f600f6f30ca
candopi-team1/Candopi-programming101
/7_data_structures_and_algorithms/sorts_python/merge_sort_dummies.py
2,018
4.46875
4
# Merge Sort def merge_sort(list): # Determine whether the list is broken into individual pieces. if len(list) < 2: return list # Find the middle of the list. middle = len(list)//2 # Break the list into two pieces. left = merge_sort(list[:middle]) right = merge_sort(list[middle:]) """ ku=[0,1,2,3,4,5] ku[0:2] or ku[2:] ==> [0, 1] position 2 not included ku[2:] ==> [2, 3, 4, 5] position 2 was included """ # Merge the two sorted pieces into a larger piece. print("Left side: ", left) print("Right side: ", right) merged = merge(left, right) print("Merged ", merged) return merged def merge(left, right): # When the left side or the right side is empty, # it means that this is an individual item and is already sorted. if not len(left): return left if not len(right): return right # Define variables used to merge the two pieces. result = [] leftIndex = 0 rightIndex = 0 totalLen = len(left) + len(right) # Keep working until all of the items are merged. while (len(result) < totalLen): # Perform the required comparisons and merge # the pieces according to value. if left[leftIndex] < right[rightIndex]: result.append(left[leftIndex]) leftIndex+= 1 else: result.append(right[rightIndex]) rightIndex+= 1 # When the left side or the right side is longer, # add the remaining elements to the result. if leftIndex == len(left) or rightIndex == len(right): result.extend(left[leftIndex:] or right[rightIndex:]) break return result data = [9, 5, 7, 4, 2, 8, 1, 10, 6, 3] data2 = [9, 5, 9, 5,9, 5,9, 5, 7, 4, 2, 8, 1, 10, 6, 7,7,7,7,7,7,3] print(merge_sort(data))
true
ef23474b4f89dae3b6933ad571e0b4067b6f07c9
kuzaster/python_training_2020
/HW7/task3/task03.py
1,267
4.1875
4
""" Given a Tic-Tac-Toe 3x3 board (can be unfinished). Write a function that checks if the are some winners. If there is "x" winner, function should return "x wins!" If there is "o" winner, function should return "o wins!" If there is a draw, function should return "draw!" If board is unfinished, function should return "unfinished!" Example: [[-, -, o], [-, x, o], [x, o, x]] Return value should be "unfinished" [[-, -, o], [-, o, o], [x, x, x]] Return value should be "x wins!" """ from itertools import chain from typing import List def tic_tac_toe_checker(board: List[List]) -> str: n = len(board) board = list(chain.from_iterable(board)) win_combs = [] for i in range(0, n ** 2, n): win_combs.append(slice(i, i + n)) # add win rows for i in range(n): win_combs.append(slice(i, n ** 2, n)) # add win columns win_combs.append(slice(0, n ** 2, n + 1)) # add win diagonal win_combs.append(slice(n - 1, n ** 2 - 1, n - 1)) # add second win diagonal for comb in win_combs: comb_slice = board[comb] if len(set(comb_slice)) == 1 and "-" not in comb_slice: return f"{comb_slice[0]} wins!" return "draw!" if "-" not in board else "unfinished!"
true
9e70185a45e593613d2c1e459ecf01b9fc4e4d2c
KFernandez1988/SSL
/rb_py_node/pygrader/grader.py
609
4.1875
4
# python grader file from grader_class import Grader name = raw_input(' Please Student enter your name ') assignment = raw_input('What was your test about ') grade = '' # checkting for the right data type while( grade is not int): try: grade = int(raw_input('Can you please enter your score ')) if(grade < 0 or grade > 100): print('Your score is either 0 or 100') grade = '' else: break except ValueError: print('Please enter a valid score') # intatiantion and printing student = Grader(name, assignment, grade) student.print_results()
true
23bc9f44eac6986b8a2f3326d8053feda2770650
stewartrowley/CSE111
/Week 8/convert_list_dictionaries.py
785
4.25
4
# Example 6 def main(): # Create a list that contains five student numbers. numbers = ["42-039-4736", "61-315-0160", "10-450-1203", "75-421-2310", "07-103-5621"] # Create a list that contains five student names. names = ["Clint Huish", "Michelle Davis", "Jorge Soares", "Abdul Ali", "Michelle Davis"] # Convert the numbers list and names list into a dictionary. student_dict = dict(zip(numbers, names)) # Print the entire student dictionary. print(student_dict) # Convert the student dictionary into # two lists named keys and values. keys = list(student_dict.keys()) values = list(student_dict.values()) # Print both lists. print(keys) print(values) # Call main to start this program. if __name__ == "__main__": main()
true
ac1acc7efa9872384ae7ec869fe853c4e8eff770
stewartrowley/CSE111
/Week 3/get_initials_organization.py
530
4.25
4
# the function gets initials for the code def get_initial(name): initial = name[0:1].upper() return initial # Ask for someones name and return the initials first_name = input("Enter your first name: ") first_name_initial = get_initial(first_name) middle_name = input("Enter your middle name: ") middle_name_initial = get_initial(middle_name) last_name = input("Enter your last name: ") last_name_initial = get_initial(last_name) print(f"Your initials are: {first_name_initial}{middle_name_initial}{last_name_initial} ")
true
3e43d7fd2a86300d241cbc7546322f92e14d0b87
zhaowangbo/python
/第一阶段/是否上班.py
443
4.1875
4
while True: day = input("enter a day from monday to sunday, and enter 'q' to quit") week = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] if day == 'q': break if day not in week: print("you must enter a day from monday to sunday") continue if day in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']: print("work") else: print("play")
true
cb5c23e7e270aead77e49ab266ed88dcbeb748ed
Krit-NameWalker/6230401848-oop-labs
/Krit-623040184-8-lab5/P4.py
587
4.15625
4
def fac(num): if num == 0: return 1 if num == 1: return 1 else: return num * fac(num-1) if __name__ == "__main__": try: num = input("Enter an integer:") num = int(num) if num < 0: print("Please enter a positive integer. {} is not a positive integer".format(num)) else: print("factorial {} is {}".format(num, fac(num))) except ValueError: num = str(num) print("Please enter a positive integer. invalid literal for int() with base 10: {} ".format(num))
true
9dfabf53905b32a03ef4d0fd4009ce606bf76000
Mistarcy/python-hello-world
/week6/high_low.py
1,012
4.28125
4
# Example by James Fairbairn <j.fairbairn@tees.ac.uk> # We wrote this together in class. # # **DO NOT REMOVE THIS HEADER** # # Notes: # + This file is for demonstration purposes only. # + You must use this example to guide your own solution. # **DO NOT SUBMIT THIS FILE AS IS FOR ASSESSMENT** import random MAX_GUESSES = 5 RANGE_START = 1 RANGE_END = 30 number = random.randint(RANGE_START,RANGE_END) name = input("Hello! What is your name? ") print(name, ", I am thinking of a number between ", RANGE_START, " and ", RANGE_END, ".", sep="") guesses_taken = 0 while guesses_taken < MAX_GUESSES: guess = int(input("Please enter a number: ")) guesses_taken += 1 if guess < number: print("Your guess is too low!") elif guess > number: print("Your guess is too high!") else: break # end while loop if guess == number: print("Awesome, ", name, "! You guessed correctly in ", guesses_taken, " attempts!", sep="") else: print("Nope. The number I was thinking of was", number)
true
2476b8db009ab4cf5c9dbed329b4a3de2fa45bcd
hunterad96/unbeatable_tic_tac_toe
/tic_tac_toe/display_functions.py
1,237
4.1875
4
import platform from os import system """ Functions to handle the rendering of the board in the terminal, and ensuring that the terminal doesn't become cluttered with boards other than the board representing the most recent state of the game. """ # Function that cleans up the terminal to avoid having too many boards # visible at the same time. # # Takes no parameters and returns nothing. Only cleans things up. def clean(): os_name = platform.system().lower() if 'windows' in os_name: system('cls') else: system('clear') # Function that handles printing the board representing the current state # of the game. # # @param board_state [2D array of ints] which is the current board. # @param player_choice an X or O representing which value the user chose. # @param computer_choice an X or O value representing the value with which # the computer is playing. # Returns nothing. Only prints the current board. def render(board_state, player_choice, computer_choice): chars = { -1: player_choice, +1: computer_choice, 0: ' ' } str_line = '---------------' print('\n' + str_line) for row in board_state: for cell in row: symbol = chars[cell] print(f'| {symbol} |', end='') print('\n' + str_line)
true
35e52395a0d1b999fd9696cc00955d3d1203ed49
simmihacks/python_projects
/hangmanpseudo.py
1,377
4.28125
4
#this is not code but a Pseudocode for an MIT coding challenge: #https://courses.edx.org/courses/course-v1:MITx+6.00.1x+2T2017_2/courseware/530b7f9a82784d0cb57de334828e3050/bfe9eb02884a4812883ff9e543887968/?child=first """ Hangman Pseudo Code 1. Load the words 2. Randomly Select a word 3. Save the word in a string: secretword 4. Ask the user to guess a letter from the 26 letters 5. Save the letter in string: guess 6. def check: See if the letter in variable guess is in secretword, return boolean 7. def show: If the guess letter is present in secretword, only show the letters in the string that has been guessed right. This should return all the letters with _ (for the one not yet guessed) and the guessed letters. 8. def available: Take out the correctly guessed letter from the alphabet, and show the ones remaining 9. Make a counter that only lasts up to 8 guesses, and do the following: a) Start a for-loop for the counter of 8 guesses b) Ask the user to guess a letter by calling the 3rd def available function c) Check secretword; call def check d) If you guessed the letter twice, print: Oops! You've already guessed that letter e) If the letter not in secretword, print: Oops! That letter is not in my word f) If it is correct, print: Good guess g) All of the above, call def show so that the use can see what s/he has gotten right """ #Hope this helps
true
8d631dfa7af78f6522855cc4914209c5009a8e79
EoinStankard/pands-problem-set
/ProblemFive-primes.py
2,097
4.3125
4
#Name: Eoin Stankard #Date: 28/03/2019 #Problem Five: Write a program that asks the user to input a positive integer and tells the user #whether or not the number is a prime. value=input("Please enter a positive integer: ") #This code will keep looping until the done variable is given 1. I used this as i will need to do multiple cycles #through each if statement to determine if it is a prime or not def printprimes(value): #initial number the input value will be divided by divisor = 1 #Count for how may numbers can divide into the input divisorCount = 0 #Variable that determines when the program finishes done =0 while done != 1: #This will look for the modulus of the input value divided by the divisor, I used this as the input value will always be divided by one to start #so this will always give a value equal to zero, I will then increment divisorCount as a prime number can only be divided by itself and one. #This means that once it enters the first if statement it already has 1/2 numbers #It will also increment the divisor. so the divisor will now go to 2 if value%divisor ==0 and divisorCount == 0: divisorCount = divisorCount +1 divisor = divisor+1 elif divisorCount ==1 and divisor == value and value%divisor==0: print("This is a prime") done = 1 #If the divisorCount is equal to one and the value divided by the divisor equals zero and #The divisor does not equal the input value then this number is not a prime elif value%divisor == 0 and divisorCount ==1 and divisor != value: print("This is not a prime") done=1 #For any other scenario, increment the divisor by one else: divisor=divisor+1 try: if int(value)>0: printprimes(int(value))#Call the function created above to calculate the output values elif int(value)<0:#if number is less than zero raise ValueError #raise exception except ValueError: print("Incorrect Input Given")# incorrect input
true
1e218f276764d53945e4a79b13bb35f615ca3ef8
Pnickolas1/Code-Reps
/AlgoExpert/Recursion/tail_call_optimization.py
1,254
4.125
4
""" Tail Call optimization: - tail call optimization is when the recursion call is the last thing in the function before it returns - hence the name "the recursive function call comes at the "tail" of the function - the call stack never grows in size - TCO prevents stack overflows - tail call optimzation is a compiler trick, - Cpython interpreter does not implement TCO, and it never will - its not pythonic - TCO is not used in python , its irrelevent - understand the call stack - a function call pushes a frame onto the call stack and a return pops a stack off leetcode def: Tail recursion is a recursion where the recursive call is the final instruction in the recursion function. And there should be only one recursive call in the function. """ def tail_call_optimizatin(n, accumulator=1): if n == 0: return accumulator else: return tail_call_optimizatin(n - 1, n * accumulator) print(tail_call_optimizatin(5)) def sum_non_tail_recursion(ls): if len(ls) == 0: return 0 return ls[0] + sum_non_tail_recursion(ls[1:]) def sum_tail_recursion(ls): def helper(ls, acc): if len(ls) == 0: return acc return helper(ls[1:], ls[0] + acc) return helper(ls, 0)
true
172bb99cf56fb5c77537340a1e9a1b00c9d103ff
Pnickolas1/Code-Reps
/Arrays/even_odd.py
570
4.125
4
# when working with arrays, take advantage of the fact you operate on both ends # efficiently # given an array of ints, sort evens first then odds x = [2, 3, 7, 5, 10, 14, 15, 22, 27, 31] print(len(x)) def even_odd(arr): next_even = 0 next_odd = len(arr) -1 while next_even < next_odd: if arr[next_even] % 2 == 0: next_even += 1 else: arr[next_even], arr[next_odd] = arr[next_odd], arr[next_even] next_odd -= 1 return arr if __name__ == "__main__": print(len(x)) print(even_odd(x))
true
f8b8a4c36802b6beb3a27326e7d05b204351ac4e
Pnickolas1/Code-Reps
/Algorithms/Bottom_Up_Algorithm.py
1,047
4.3125
4
# Bottom up algorithms offer another option in solving a problem. Bottom up algorithms are often used instead of a # recursive approach. While recursion offers highly readable, succinct code, it is succeptible to a high memory cost # O(n) and could lead to a stack overflow. # recursion starts from the "end and works it's way back" (hence the need for a base case) # bottom up algorithms start from the bottom (or start) and work their way up # going bottom up is a common strategy for dynamic programming # dynamic programming are coding problems where the solution is composed of solutions to the same problem with # smaller inputs # the other common strategy is memoization # recursive approach def product_1_to_n(n): # we assume n >= 1 return n * product_1_to_n(n - 1) if n > 1 else 1 # to avoid this we can use a bottom up approach def product_1_to_n_bottom_up(n): # we assume n >= 1 result = 1 for num in range(1, n + 1): result *= num print result product_1_to_n(15) product_1_to_n_bottom_up(15)
true
eca7a7ce6540b3979f21670b0aad8b9f676c7f6e
Pnickolas1/Code-Reps
/EOPI/array/check_if_decimal_integer_is_palindrome.py
797
4.21875
4
import math """ checking if a integer is a palindrome can be 2 waysL Optimal: space: O(1) time:: O(n) 1. way, reverse the integer, and then compare to the given parameter 2. iterate through through the param, popping off the most significant int, and the least significant digit, comparing, if they dont match, return false, if they do match, remove the most/least significant arg and continue edge case, if the given arg is less than 0 """ def is_number_palindrome(x): if x < 0: return False num_digits = math.floor(math.log10(x)) + 1 msd_mask = 10**(num_digits - 1) for i in range( num_digits // 2): if x // msd_mask != x % 10: return False x %= msd_mask x //= 10 msd_mask //= 100 return True print(is_number_palindrome(1234321))
true
d04d1642831395c1f8bed417c1138b4d8c89f804
gunnsa/Git_place
/git-python/sequence.py
349
4.15625
4
n = int(input("Enter the length of the sequence: ")) # Do not change this line sequence = 0 x1 = 1 x2 = 2 x3 = 3 if n > 0: print(1) if n > 1: print(2) if n > 2: print(3) if n > 3: for x in range(0,n-3): sequence = x1 + x2 + x3 print(sequence) x1 = x2 x2 = x3 x3 = sequence print(sequence)
true
16c36a6e26395be7996359701bd6373fc3036de5
himanig/py-path
/createmodule_circle.py
237
4.25
4
#creating my own module from math import pi radius = input('Enter the radius of circle: ') print(end='\n') print('The area of the circle is= ', float(radius) ** 2 * pi) print(end='\n') print('The circumference is= ', float(radius) * pi)
true
bf0b3dde8a51d60ca5326d99eb3b7217622e50d8
couple-star/python-study
/exercise/excercise22.py
201
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #Write a function that takes a string as input and returns the string reversed. string=raw_input('please in put one string: ') a=string[::-1] print a
true
fff1490edf893397e742018cb3519a579f1c27e5
choutos/winterchallenge_2019
/day01/day01.py
2,342
4.5625
5
''' Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For example: - For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2. - For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2. - For a mass of 1969, the fuel required is 654. - For a mass of 100756, the fuel required is 33583. The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values. ''' def calc_fuel(mass: int) -> int: return mass // 3 -2 assert calc_fuel(12) == 2 assert calc_fuel(14) == 2 assert calc_fuel(1969) == 654 assert calc_fuel(100756) == 33583 with open("input.txt") as f: masses = [int(line.strip()) for line in f] fuel_part1 = 0 for mass in masses: fuel_part1 += calc_fuel(mass) print(fuel_part1) ''' For each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example: A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2. At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966. The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346. ''' def calc_fuel2(mass: int) -> int: total = 0 new_fuel = calc_fuel(mass) while new_fuel > 0: total += new_fuel new_fuel = calc_fuel(new_fuel) return total assert calc_fuel2(14) == 2 assert calc_fuel2(1969) == 966 assert calc_fuel2(100756) == 50346 fuel_part2 = 0 for mass in masses: fuel_part2 += calc_fuel2(mass) print(fuel_part2)
true
dcf62d8f75a28a3c6de9cbc8800003e632f7cfc8
NitinJRepo/Linear-Algebra
/01-creating_vector.py
628
4.34375
4
import numpy as np # Create a vector as a row vector_row = np.array([1, 2, 3, 4, 5]) print("row vector: ", vector_row) # Create a vector as a column vector_column = np.array([[1], [2], [3], [4], [5]]) print("column vector: ", vector_column) # Selecting elements print("Select third element of vector:") print(vector_column[2]) print("Select all elements of a vector:") print(vector_row[:]) print("Select everything up to and including the third element:") print(vector_column[:3]) print("Select everything after the third element:") print(vector_column[3:]) print("Select the last element:") print(vector_column[-1])
true
d503bc0ac71fde9f617d693e3842e1572041a94b
bigplik/Python
/lesson_nana/functions.py
683
4.1875
4
#functions hours = 24 minutes = 24 * 60 seconds = 24 * 60 * 60 #calculation to units eg. to seconds, or hours calculation_to_units = seconds name_of_unit = "seconds" ''' def day_to_units(days): num_of_days = days print(f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}") day_to_units(176900) ''' #2nd eg. for function with parameters without defining extra variable like above def day_to_units(num_days, custom_message): print(f"{num_days} days are {num_days * calculation_to_units} {name_of_unit}") print(custom_message) day_to_units(104343, "custom_message") # common practice!!!! not to make too many parameters eg.10, better is use about two
true
3f09381843b9d724563344d5d36ceb7df27d177b
pndiwakar/python_hello_word
/radius.py
309
4.4375
4
#!bin/python # Impoort the required module for getting maths function PI from math import pi #assign the input to variable r = float(input("Input the radius of circle : ")) # To make it square of r either use "r * r" or "r**2" print ("Areas of circle with radius={} is : {}" .format(r, str(pi * (r * r))))
true
622beb7f9d24e18d9fd844c2c57ea3ef648f456a
marmst10/Python-Examples
/Basic Python Manipulations.py
1,832
4.125
4
#!/usr/bin/env python # coding: utf-8 # STAT 7900 – Python for Data Science<br> # Homework 3<br> # Connor Armstrong<br> # <br> # 1. Create a CSV (Comma Separated Values) file from the data below (copy and paste the data into Excel then save as a csv) and read in as a Pandas Dataframe. Then do the following using Pandas operations that we covered in class (10 points): <br> # In[5]: import numpy as np import pandas as pd data = pd.read_csv('C:/Users/conno/OneDrive/Desktop/STAT 7900 - Python for Data Science/Homework/HW3 Data.csv') # <br> # a. What percent of records represent flowers? <br> # The mean of the binary indicator variable is equivalent to the percentage of records which represent flowers. This parameter is calculated as follows:<br> # In[4]: percent_flowers = data['Flower'].mean() percent_flowers # Therefore, the percent of records which represent flowers is 45%.<br><br> # b. What is the average Costs by Color?<br> # In[24]: costbycolor = pd.DataFrame(data['Cost'].groupby(data['Color']).mean()) costbycolor # <br>c. Create a new column, that bins the Probability column into 4 equal frequency count bins (from low to high).<br> # In[25]: data['Bin'] = pd.qcut(data['Probability'], q=4) data # In[26]: data['Bin'].value_counts() # The column 'Bin' grouped the data into 4 equal frequency count bins as directed.<br><br> # d. Create a crosstab of color and flower that represents the total cost.<br> # In[31]: pd.crosstab(data['Color'], data['Flower'], values=data['Cost'], aggfunc='sum', rownames=['Cost'], colnames=['Flower']) # The dataframe above is a crosstab of color and flower which represents the total cost of each unique combination of the two.<br><br> # e. Create a dataframe that contains flowers, only.<br> # In[32]: flowersonly = data[(data['Flower']== 1)] flowersonly
true
f321231eb06846b84c88bcfcc274a875bbc16b6f
joyadas1999/calculator
/calculator.py
1,650
4.40625
4
#this function is an example of addition def calculator_addvalue(addvalue_x,addvalue_y): calc_add = addvalue_x + addvalue_y return calc_add add_x = calculator_addvalue(100,30) print(add_x) #this function is an example of subtraction def calculator_subtvalue(subtvalue_x,subtvalue_y): calc_subt = subtvalue_x - subtvalue_y return calc_subt subt_x = calculator_subtvalue(148,24) print(subt_x) #this function is an example of multiplication def calculator_multvalue(multvalue_x,multvalue_y): calc_mult = multvalue_x * multvalue_y return calc_mult mult_x = calculator_multvalue(247,35) print(mult_x) #this function is an example of squaring two numbers def calculator_squarevalue(squarevalue_x,squarevalue_y): calc_square_1 = squarevalue_x * squarevalue_x calc_square_2 = squarevalue_y * squarevalue_y return calc_square_1, calc_square_2 square_x, square_y = calculator_squarevalue(8,9) print("This prints the square of " +str(square_x)) print("This prints the square of " +str(square_y)) #this function does an example of division def division(div1,div2): calc_div = div1 / div2 return calc_div print(division(20,5)) print(division(30,10)) #this function gets a remainder def remainder (rem1,rem2): calc_rem = rem1 % rem2 return calc_rem print("The remainder is:" + str(remainder(9,8))) print("The remainder is:" + str(remainder(18,43))) #this function is testing to see if the math is done correctly def correctcheck(math1): if math1 == str(5+5): return " You are correct" if math1 == str(5): return " You are wrong" math1 = str(10) math1 = str(5) print(correctcheck(math1))
true
378e26693bc0fb641470307d5e6ed10dd9e0fc06
BryJC/LPtHW
/40-49/ex42.py~
2,203
4.28125
4
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a(n) animal class Dog(Animal): def __init__(self, name): ## class Dog has-a(n) attribute name set to name self.name = name ## Cat is-a(n) animal class Cat(Animal): def __init__(self, name): ## class Cat has-a(n) attribute name set to name self.name = name ## Person is-a(n) object class Person(object): def __init__(self, name): ## Person has-a(n) attribute name set to name self.name = name ## Person has-a(n) attribute pet of some kind self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): ## class Employee has-a(n) attribute name set to name (from Person class) ?? super(Employee, self).__init__(name) ## class Employee has-a(n) attribute salary set to salary self.salary = salary ## class Fish is-a(n) object class Fish(object): pass ## class Salmon is-a Fish class Salmon(Fish): pass ## class Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat ## set satan equal to an instance of class Cat that takes self, "Satan" parameters satan = Cat("Satan") ## Mary is-a Person ## set mary equal to an instance of class Person that takes self, "Mary" parameters mary = Person("Mary") ## mary has-a satan ## from (instance of class Person:) mary, get the pet attribute and set it to satan mary.pet = satan ## frank is-a Employee ## set frank equal to an instance of class Employee that takes self, "Frank", and 120000 arguments frank = Employee("Frank", 120000) ## frank has-a rover ## from (instance of class Employee:) frank, get the pet attribute (from superclass Person) and set it to rover frank.pet = rover ## flipper is-a Fish ## set flipper to an instance of class Fish that takes parameter self flipper = Fish() ## crouse is-a Salmon ## set crouse equal to an instance of class Salmon that takes parameter self crouse = Salmon() ## harry is-a Halibut ## set harry equal to an instance of class Halibut that takes parameter self harry = Halibut()
true
8fb7f09891f642640d0349410a84552fdb0a6098
balazsbarni/pallida-basic-exam-trial
/namefromemail/name_from_email.py
717
4.40625
4
# Create a function that takes email address as input in the following format: # firstName.lastName@exam.com # and returns a string that represents the user name in the following format: # last_name first_name # example: "elek.viz@exam.com" for this input the output should be: "Viz Elek" # accents does not matter #print(name_from_email("elek.viz@exam.com")) email_adress = str(input("Please enter ypur e-mail adress: ")) def name_from_email(entered_email_adress): forename =entered_email_adress[entered_email_adress.index(".") :entered_email_adress.index("@")] name =entered_email_adress[:entered_email_adress.index(".")] return forename[1].upper() +forename[2:] + " " + name[0].upper() +name[1:] print(name_from_email(email_adress))
true
15469c6b9eb1e92deadda1e6330bd8e0d54452ad
Shwibi/python-c11-stanselm
/marks.py
434
4.21875
4
# Practice: 18/8/2021 # Conditional Statements with calculation # Program 1 physics = int(input("Enter marks in physics: ")) chemistry = int(input("Enter marks in chemistry: ")) biology = int(input("Enter marks in biology: ")) total = physics + chemistry + biology percentage = total/3 print("Total marks: ", total) print("Total percentage: ", percentage) if percentage >= 40: print("You passed") else: print("You failed")
true
412fb126e7f325e85c8d67c1aefaac11f0e86655
Shwibi/python-c11-stanselm
/vote.py
201
4.21875
4
# Practice: 18/8/2021 # Conditional Statements, boolean # Program 2 age = int(input("Enter age: ")) if age >= 18: print("You are eligible to vote!") else: print("You are not eligible to vote!")
true
2c1876b25ba61af9e861f01199b49637fcaf9592
Elmurat01/ThinkPython
/Think Python - Chapter 04/ThinkPython4_flowers.py
754
4.25
4
import turtle, math bob = turtle.Turtle() def arc(t, r, angle): """Draws an arc length angle from a circle of radius r. t is a turtle. """ step = (2 * math.pi * r) / 360 for i in range(angle): t.fd(step) t.lt(1) def flower(t, no_petals, len_petals, angle): """Draws a flower-shaped pattern with the number of petals specified in no_petals. angle designates the width of the petal. The length of the petal is determined by angle and len_petals. t is a turtle. """ for i in range(no_petals): for i in range(2): arc(t, len_petals, angle) t.lt(180 - angle) t.lt(360/no_petals) flower(bob, 20, 300, 45) turtle.mainloop()
true
c7d44451340d31439de7278b1e802ab76a8e23a6
Elmurat01/ThinkPython
/Think Python - Chapter 15/draw_circle.py
963
4.3125
4
import turtle, math bob = turtle.Turtle() class Point: """Represents a point in 2-D space.""" class Circle: """ Represents a circle. Attributes: radius, center """ def draw_circle(t, circle, color = "black"): """ Takes a Circle object and a Turtle object and draws a circle. arguments: t: Turtle object circle: Circle object color: optional color of the Turtle pen. Default is black. """ t.penup() t.fd(circle.center.x) t.lt(90) t.fd(circle.center.y + circle.radius) t.rt(90) t.pendown() step = (math.pi * 2 * circle.radius)/360 for i in range(360): t.pencolor(color) t.fd(step) t.rt(1) roundy = Circle() roundy.radius = 75 roundy.center = Point() roundy.center.x = 150.0 roundy.center.y = 100.0 draw_circle(bob, roundy, color = "red") turtle.mainloop()
true
a84d8f35a45c7b9fe1b1c9706efc981a71b37f4e
annamariamistrafovic1994/SN-WD1-Lesson8
/mood_checker.py
515
4.1875
4
x = input("What mood are you in? ") print(x) operation = input("Choose one of the given solutions (happy, sad, relaxed, nervous, excited): ") print(operation) if operation == "happy": print("It is great to see you happy!") elif operation == "sad": print("Cheer up!") elif operation == "relaxed": print("Stay in ZEN.") elif operation == "nervous": print("Take a deep breath 3 times.") elif operation == "excited": print("Keep the adrenaline up!") else: print("I don't recognize this mood.")
true
3842011e556e7e0708ec652718d1daa099d7cade
mlr0929/FluentPython
/05FirstClassFunctions/any_and_all.py
707
4.21875
4
""" all(iterable) Return True if every element of the iterable is truthy; all([]) returns True >>> all([0, 1, 3]) False >>> all([1, 1, 3]) True >>> all([]) True # Equivalent to >>> def all(iterable): ... for element in iterable: ... if not element: ... return False ... return True any(iterable) Return True if any element of the iterable is true. If the iterable is empty, return False >>> any([0, 0, 1]) True >>> any([0, 0, 0]) False >>> any([]) False # Equivalent to >>> def any(iterable): ... for element in iterable: ... if not element: ... return True ... return False """ if __name__ == "__main__": import doctest doctest.testmod()
true
e42da9aa532f1dd148ea2f000846a3bace45eb24
sandyg05/cs
/[Course] Python for Everybody - University of Michigan/Course 2 - Python Data Structures/Chapter 6 - Strings.py
1,548
4.625
5
# Chapter 6 - Strings Quiz # 1. # What does the following Python Program print out? str1 = "Hello" str2 = 'there' bob = str1 + str2 print(bob) # Hellothere # 2. # What does the following Python program print out? x = '40' y = int(x) + 2 print(y) # 42 # 3. # How would you use the index operator [] to print out the letter q from the following string? x = 'From marquard@uct.ac.za' # print(x[8]) # 4. # How would you use string slicing [:] to print out 'uct' from the following string? x = 'From marquard@uct.ac.za' # print(x[14:17]) # 5. # What is the iteration variable in the following Python code? for letter in 'banana' : print(letter) # letter # 6. # What does the following Python code print out? print(len('banana')*7) # 42 # 7. # How would you print out the following variable in all upper case in Python? greet = 'Hello Bob' # print(greet.upper()) # 8. # Which of the following is not a valid string method in Python? # shout() # 9. # What will the following Python code print out? data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' pos = data.find('.') print(data[pos:pos+3]) # .ma # 10. # Which of the following string methods removes whitespace from both the beginning and end of a string? # strip() # ---------------------------------------------------------------------------------------------------------------------- # Chapter 6 - Strings Assignments # Assignment 6.5 text = "X-DSPAM-Confidence: 0.8475" colon_position = text.find(':') num = text[colon_position + 1:].strip() print(float(num))
true
c19dba940010c1d12eaab21bfe06e2479fcfe3ca
sandyg05/cs
/[Course] Python for Everybody - University of Michigan/Course 1 - Programming for Everybody (Getting Started with Python)/Chapter 1 - Why We Program.py
1,341
4.34375
4
# Chapter 1 - Why We Program Quiz # 1. # When Python is running in the interactive mode and displaying the chevron prompt (>>>) # what question is Python asking you? # What would you like to do? # 2. # What will the following program print out: x = 15 x = x + 5 print(x) # 20 # 3. # Python scripts (files) have names that end with: # .py # 4. # Which of these words are reserved words in Python ? # if # break # 5. # What is the proper way to say “good-bye” to Python? # quit() # 6. # Which of the parts of a computer actually executes the program instructions? # Central Processing Unit # 7. # What is "code" in the context of this course? # A sequence of instructions in a programming language # 8. # A USB memory stick is an example of which of the following components of computer # architecture? # Secondary Memory # 9. # What is the best way to think about a "Syntax Error" while programming? # The computer did not understand the statement that you entered # 10. # Which of the following is not one of the programming patterns covered in Chapter 1? # Random steps # ---------------------------------------------------------------------------------------------------------------------- # Chapter 1 - Why We Program Assignments # Assignment Write Hello World print("Hello, World!")
true
0db347081d9257b3b7fd0f8baeda34b5bf7e4b86
Tclack88/Scientific-Computing-Projects
/Basic/SineSeriesApprox.py
1,833
4.28125
4
#!/usr/bin/python3 import math pi = 3.1415926535897932384626433832795028841971 def factorial(n): num = 1 for i in range (1,n+1): num *= i return num # we are not allowed to import functions like # factorial or pi, so I have to define them here # Self explanatory definition I'd say angle= input("Give me an angle (in degrees): ") # Couldn't figure out how to make sure this is # either a float or integer... sorry angle = float(angle)*pi/180 numterms = input("How many terms do you want? ") while numterms.isdigit() is False or int(numterms)>=25: numterms = input("Don't be ridiculous. Only integers allowed" \ " below 25, try again: ") numterms = int(numterms) # The first while loop ensures only integer inputs are # accepted, the second keeps it below 25. Finally I # turn the string input into an integer def sind(angle,numterms): total = 0 for i in range(1,numterms+1): n = ((-1)**(i-1))*((angle)**(2*i-1))/factorial((2*i-1)) total += n return total # This is just the definition of sine as a taylor # expansion. Since we are adding terms up to a # specified input, the "for i in range" works perfectly # # Note: initially I tried doing this as an array, but # my factorial definition only acts on single inputs # I'm not sure how to make it operate on arrays, so I # had to change to a range function sind = sind(angle,numterms) sin = math.sin(angle) # assign these variable names to the corresponding # functions for simplicity print ("\nHere is sind():\n",sind) print ("\nHere is the math module's sine:\n",sin) print("\nTo compare:\n\n The absolute difference is:\n", \ math.sqrt((sin-sind)**2), \ "\n\nThe ratio is:(sind to sine)\n",sind/sin)
true
1c34a6302c82676ed500cd9407c39c944b6a1d0d
Tclack88/Scientific-Computing-Projects
/Basic/InfoAssist.py
2,868
4.46875
4
#!/usr/bin/python3 # The purpose of this program is to take info from a .csv file (csv.csv... very creative name) # and automate the process of finding specific information: import csv with open('csv.csv') as f: readCSV = csv.reader(f, delimiter=',') # "with open(file) as f" automatically closes after # the operation is complete. rename to f for ease # of typing. csv.reader returns an object in the file # (separated by commas) people = [] # create a blank list to while I will append dictionaries for person in readCSV: people.append({'last':person[0],'first':person[1],'color':person[2], \ 'food':person[3],'field':person[4],'physicist':person[5]}) # Creates a dictionary for each row in the file print("I have information here about a bunch of people:\n") response = 'y' while response == 'y': print(list(people[0].keys())) choice = input("What would you like to know about? ") print() # This while loop sets up the requirement to # continue to prompt the user for keys people_sort = [] for person in people: item =(person['last']+", "+person['first']+": "+person[choice]) people_sort.append(item) people_sort = sorted(people_sort) # blank list people_sort is for the alphabetizing # of the output. The key choice is will put the # string "Last, first: key" for each row and store # that into the blank list which is default sorted # alphabetically for i in people_sort: print(i) print() # Here we print the already sorted list response = input("Would you like to know more? <y,n> ") if response == 'n': break while response != 'n' and response !='y': print("That's not a valid response, try again") response = input("Would you like to know more? <y,n> ") # Here is where the user is prompted if they'd # like to continue. I do a few short while loops # to ensure only "y" or "n" is input """ THE FOLLOWING DOES PART OF THE TASK, BUT DOESN'T USE THE DICTIONARY AS REQUESTED... I'M KEEPING IT HERE BECAUSE I'M PROUD OF IT AND MAY WANT TO REFER BACK TO IT LATER import csv with open('csv.csv') as f: readCSV = csv.reader(f, delimiter=',') print("I have here a list of people, their first names, last names, \ favorite color, food, field of physics and physicist.\n") choice = input ("Which would you like to know? last, first, color, \ food, field.\n (type one):") last = [] first = [] color = [] food = [] field = [] physicist = [] for row in readCSV: last = row[0] first = row[1] color = row[2] food = row[3] field = row[4] physicist = row[5] print(last+","+first+":"+choice) """
true
3caa0f0153dbd76fd844262a24d75e3b851d28b2
Tclack88/Scientific-Computing-Projects
/Intermediate/lorenz_attractor.py
1,269
4.1875
4
#!/usr/bin/env python3 # plot of a lorentz attractor as apart of a solution to a nonlinear dynamics problem # strogatz import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def lorenz(x,y,z,r, a=10, b=8/3): x_dot = a*(y-x) y_dot = r*x-y-x*z z_dot = x*y-b*z return x_dot, y_dot, z_dot # Setup step size, number of iterations, and initial values. Make 3 separate # lists for the x,y and z values. First entry is the initial values # NOTE: with a stepsize of .01, there needs to be 5000 steps to get to t = 50 dt = 0.01 N = 5000 r = 24.5 xvals=[0] yvals=[10] zvals=[13] # By derivative definition: x(t) = x(t-1) + x_dot * dt # Use for loop to append to lists for i in range(1,N): x_dot, y_dot, z_dot = lorenz(xvals[i-1], yvals[i-1], zvals[i-1], r) xvals.append(xvals[i-1] + x_dot * dt) yvals.append(yvals[i-1] + y_dot * dt) zvals.append(zvals[i-1] + z_dot * dt) # Convert lists into arrays for ease of plotting xvals = np.asarray(xvals) yvals = np.asarray(yvals) zvals = np.asarray(zvals) fig = plt.figure() ax = fig.gca(projection='3d') ax.plot(xvals, yvals, zvals, linewidth=0.5) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.set_title("Lorenz Equations Strogatz 9.3.4 for r = 24.5") plt.show()
true
04cdb0bfddf2670ad3f4cc7de8f4bb849bdbcdf6
JunWonOh/Multimodal-Calculator
/Multi-modal Calculator/Calculator_Module/Calculator_Presentation.py
2,583
4.15625
4
from tkinter import * import tkinter.font as font from Calculator_Module import Calculator_Control # initialize the root root = Tk() # title of the window root.title("CSI 407 Project") # color of the window root.configure(bg="#606060") # disable resizing root.resizable(False, False) # the font of the buttons myFont = font.Font(size=15, family="Ubuntu") # The font of the text box myFont2 = font.Font(size=25, family="Ubuntu") # the text box e = Entry(root, width=26, borderwidth=2, font=myFont2) # at max, there can be 4 columns in the grid e.grid(row=0, column=0, columnspan=4) # asks user if they want to enter voice mode on init. Calculator_Control.access_initial_prompt() # behaves like EXIT_ON_CLOSE functionality on java swing, which is often included in Presentation def close_window_click(): print('Quitting Program..') root.quit() root.destroy() class Presentation: cc = Calculator_Control.access_input_controller() cc_fc = Calculator_Control.access_function_control() # buttons arranged by rows and columns. get button functions are called to retrieve them # from different modules cc_fc.get_button_clear(e, root, myFont).grid(row=6, column=0) cc.get_button_0(e, root, myFont).grid(row=6, column=1) cc_fc.get_button_equals(e, root, myFont).grid(row=6, column=2, columnspan=2) cc.get_button_1(e, root, myFont).grid(row=5, column=0) cc.get_button_2(e, root, myFont).grid(row=5, column=1) cc.get_button_3(e, root, myFont).grid(row=5, column=2) cc.get_button_plus(e, root, myFont).grid(row=5, column=3) cc.get_button_4(e, root, myFont).grid(row=4, column=0) cc.get_button_5(e, root, myFont).grid(row=4, column=1) cc.get_button_6(e, root, myFont).grid(row=4, column=2) cc.get_button_minus(e, root, myFont).grid(row=4, column=3) cc.get_button_7(e, root, myFont).grid(row=3, column=0) cc.get_button_8(e, root, myFont).grid(row=3, column=1) cc.get_button_9(e, root, myFont).grid(row=3, column=2) cc.get_button_mult(e, root, myFont).grid(row=3, column=3) cc.get_button_open_br(e, root, myFont).grid(row=2, column=0) cc.get_button_close_br(e, root, myFont).grid(row=2, column=1) cc.get_button_expo(e, root, myFont).grid(row=2, column=2) cc_fc.get_button_delete(e, root, myFont).grid(row=2, column=3) # formats voice button Calculator_Control.access_voice_button(e, root, myFont).grid(row=1, column=0, columnspan=2) # gives additional functionality to close button root.wm_protocol("WM_DELETE_WINDOW", close_window_click) root.mainloop()
true
d8a1213f4366ecd4985389b1e81d60bba23e893c
SMGuellord/Algorithms-and-data-structures-using-Python
/queue/QueueWithSinglyLinkedList.py
1,751
4.21875
4
class Node(object): def __init__(self, data): self.data = data self.next_node = None class Queue(object): def __init__(self): self.head = None self.size = 0 def enqueue(self, data): self.size += 1 new_node = Node(data) if not self.head: self.head = new_node else: new_node.next_node = self.head self.head = new_node def dequeue(self): if not self.head: return else: current = self.head previous = None while current.next_node is not None: previous = current current = current.next_node self.size -= 1 data = current.data previous.next_node = None return data def peek(self): if not self.head: return else: current = self.head while current.next_node is not None: current = current.next_node return current.data def traverse_list(self): if not self.head: return else: current_node = self.head while current_node is not None: print(" %d" % current_node.data) current_node = current_node.next_node def queue_size(self): return self.size queue = Queue() queue.enqueue(20) queue.enqueue(30) queue.enqueue(40) print("Queue size", queue.queue_size()) queue.traverse_list() print("Peeked: ", queue.peek()) print("Queue size", queue.queue_size()) queue.traverse_list() print("Dequeued:", queue.dequeue()) print("Dequeued:", queue.dequeue()) print("Queue size", queue.queue_size()) queue.traverse_list()
true
1831235ebe9dee4c75bccff6f62ad2afd8b3e8c4
Tanyaregan/daily_coding
/daily_1_13.py
1,093
4.40625
4
# Given an array of integers, find the first missing positive integer # in linear time and constant space. # In other words, find the lowest positive integer that does not exist in the array. # The array can contain duplicates and negative numbers as well. # For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. # You can modify the input array in-place. def missing_int(array): """Given an array of integers, find the lowest positive int that does not exist in the array. >>> missing_int([3, 4, -1, 1]) 2 >>> missing_int([1, 2, 0]) 3 """ positive_nums = [num for num in array if num > 0] positive_nums.sort() pos_num = 1 for num in positive_nums: if num != pos_num: return pos_num else: pos_num += 1 return pos_num ####################################################### if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "All tests passed, you super-genius, you." print
true
851c2de55b7ddbc0166c6a4c374a8cb1f7c72e9c
azizamukhamedova/Python-Thunder
/ArrangementOfLetters.py
588
4.21875
4
''' Backtracking is a form of recursion. But it involves choosing only option out of any possiblities. ######################## Arrangemt Of Letter Problem ########################## ###### Python ###### ''' def arrangement(num,s): if num == 1: return s else: return [ y + x for y in arrangement(1,s) for x in arrangement(num-1,s) ] letter = ['1','2', '3'] print(arrangement(2,letter))
true
19e65fde298f1f827b77865f5c49af233991cbe6
acneuromancer/algorithms-datastructures
/Python/most_frequent.py
421
4.15625
4
""" Given an array find out what the most frequent element is. """ def most_frequent(a_list): count = {} max_val = 0 max_key = None for key in a_list: count[key] = 1 if key not in count else count[key] + 1 if count[key] > max_val: max_key = key max_val = count[key] return max_key print(most_frequent([5, 0, 5, 1, 1, 5, -1, 5, 2, 3, 4]));
true
f251c542e7dd581c3223c2718352287820910ce5
mauriciosierrac/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
458
4.4375
4
#!/usr/bin/python3 ''' That Function print the first and last name''' def say_my_name(first_name, last_name=""): ''' funcion say my name Return: print the first and last name ''' if type(first_name) is not str: raise TypeError ('first_name must be a string') if type(last_name) is not str: raise TypeError ('last_name must be a string') print('My name is {} {}'.format(first_name, last_name))
true
5987f01590742617c2aaa36c27ad7def84d98967
ashokjain001/Coding_Practice
/problem-Solving/capitalization.py
332
4.3125
4
#write a function that accepts a string. The function should #capitalize the first letter of each word in the string then #return the capitalized string. def capitalization(string): array=string.split() newstr='' for i in array: newstr=newstr+' '+i[0].upper()+i[1:] return newstr print capitalization('a short sentence')
true
19d20dff0e99e6c54e024fbee301b8dc95ae8dbd
karakose77/udacity-cs101-intro-to-computer-science-exercises-and-projects
/mk005-is_symmetric.py
510
4.46875
4
# A list is symmetric if the first row is the same as the first column, # the second row is the same as the second column and so on. Write a # procedure, symmetric, which takes a list as input, and returns the # boolean True if the list is symmetric and False if it is not. def is_symmetric(L): """ Returns True if given list is symmetric. """ result = len(L) == len(L[0]) for i in range(len(L)): for j in range(len(L)): result *= L[i][j] == L[j][i] return result
true
296530e3cb3d06b42ff811d9c10ed8c82e6f6723
karakose77/udacity-cs101-intro-to-computer-science-exercises-and-projects
/mk009-is_palindrome_recursive.py
343
4.34375
4
# Define a procedure, that takes as input a string, and returns a # Boolean indicating if the input string is a palindrome. def is_palindrome_recursive(s): """ Returns true if input string is a palindrome. """ if len(s) == 0 or len(s) == 1: return True return (s[0] == s[-1]) and is_palindrome_recursive(s[1:-1])
true
6e8dd58f96b1748825260c3a3d8cedf1f62b2637
jzarazua505/the_matrix
/property.py
794
4.125
4
width = 5 height = 2 # This is where we calculate perimeter perimeter = 2 * (width + height) # This is where we calculate area area = width * height print("Perimeter is " + str(perimeter) + " and Area is " + str(area) + "!") print(f"Perimeter is {perimeter} and Area is {area}!") print(f"Area: {area}") # f(x) = y = 2x + 4 # f(input) = 2 * (input) + 4 = output def f(x): return 2 * x + 4 y = f(6) print(y) def get_area(width, height): return width * height print() area1 = get_area(5, 2) print(f"Area 1: {area1}") area2 = get_area(7, 8) print(f"Area 2: {area2}") print() test = "julian" def print_words(): print("words") print("stuff") print("thing") return "test" test = print_words() print(test) other = print_words() print_words() print_words() print_words()
true
94dd05b8a2370ab85db2412e2be93872d0fbce05
2281/unittest
/unittest/radius.py
494
4.15625
4
from math import pi def circle_area(radius): if radius < 0: raise ValueError("Radius can't be negative") if type(radius) not in [int, float]: raise TypeError("Type is not int or float") return pi*radius**2 #print(circle_area(-5)) # r_list = [1,0,-1,2+3j, True, [2], "seven"] # message = "Площадь окружности с радиусом {radius} --> {area}" # # for r in r_list: # s = circle_area(r) # print(message.format(radius = r, area = s))
true
75bafe1ecce74af6b790cc77007c9e184ae912be
Annapooraniqxf2/read-write-python-program
/finish-the-program/p008_finish.py
447
4.15625
4
# Python program to find the # sum of all digits of a number # function definition def sumDigits(<Finish the line>): if num == 0: return 0 else: return num % 10 + sumDigits(int(num / 10)) # main code x = 0 print("Number: ", x) print("Sum of digits: ", sumDigits(x)) print() x = 12345 print("Number: ", x) print("Sum of digits: ", sumDigits(x)) print() x = 5678379 print("Number: ", x) print("Sum of digits: ", sumDigits(x)) print()
true
2882485852aa333e90ae5a1677a967305918dceb
Annapooraniqxf2/read-write-python-program
/finish-the-program/p001_finish.py
305
4.21875
4
""" Input age of the person and check whether a person is eligible for voting or not in Python. """ # input age age = int(input("Enter Age : ")) # condition to check voting eligibility <Fill the line> status="Eligible" <Fill the line> status="Not Eligible" print("You are ",status," for Vote.")
true
f31ac167f2e8d70f19e58355b919395abaf878ea
Allegheny-Computer-Science-102-F2020/cs102-F2020-challenge2-starter
/iterator/iterator/iterate.py
1,166
4.53125
5
"""Calculate the powers of two, with iteration, from minimum to maximum values.""" # TODO: Add the required import statements for List and Tuple def calculate_powers_of_two_for_loop( minimum: int, maximum: int ) -> List[Tuple[int, int]]: """Calculate and return the powers of 2 from an inclusive minimum to an exclusive maximum.""" powers_list = [] # iterate through a sequence of numbers that range from # the minimum (inclusive) to the maximum (exclusive) for i in range(minimum, maximum): # TODO: save a two-tuple of the form (i, 2**i) # return the list of the tuples of the powers return powers_list def calculate_powers_of_two_while_loop( minimum: int, maximum: int ) -> List[Tuple[int, int]]: """Calculate and return the powers of 2 from an inclusive minimum to an exclusive maximum.""" powers_list = [] i = minimum # iterate through a sequence of numbers that range from # the minimum (inclusive) to the maximum (exclusive) while i < maximum: # TODO: save a two-tuple of the form (i, 2**i) i += 1 # return the list of the tuples of the powers return powers_list
true
2ca165947c741d4c65a75f3df950a38fa39a04bd
JosiahMc/python_stack
/python_fundamentals/coin_tosses.py
1,630
4.375
4
# Assignment: Coin Tosses # Write a function that simulates tossing a coin 5,000 times. Your function should # print how many times the head/tail appears. # # Sample output should be like the following: # # Starting the program... # Attempt #1: Thro1 head(s) so far and 0 tail(s) so far # Attempt #2: Throwing a coin... It's a head! ... Got 2 head(s) so far and 0 tail(s) so far # Attempt #3: Throwing a coin... It's a tail! ... Got 2 head(s) so far and 1 tail(s) so far # Attempt #4: Throwing a coin... It's a head! ... Got 3 head(s) so far and 1 tail(s) so far # ... # Attempt #5000: Throwing a coin... It's a head! ... Got 2412 head(s) so far and 2588 tail(s) so far # Ending the program, thank you! # Hint: Use the python built-in round function to convert that floating point number into an integer import random def heads_tails (): heads_so_far = 0 tails_so_far = 0 attempts_so_far = 0 print "Starting the program..." for i in range (0,5000): attempts_so_far = attempts_so_far + 1 coin_toss = random.randint (1,2) if coin_toss % 2 == 0: heads_so_far = heads_so_far + 1 print "Attempt #" + str(attempts_so_far) + " Throwing a coin... It's a head!... Got " + str(heads_so_far) + "head(s) so far and " + str(tails_so_far) + " tails so far" elif coin_toss % 2 == 1: tails_so_far = tails_so_far + 1 print "Attempt #" + str(attempts_so_far) + " Throwing a coin... It's a tail!... Got " + str(heads_so_far) + "head(s) so far and " + str(tails_so_far) + " tails so far" print "Ending the program, thank you!" heads_tails()
true
a3d18cc43f4ca22670598e60ba5b883f11c867b5
dexterka/coursera_files
/2_Python_data_structures/week4_lists/lists_testing.py
1,019
4.125
4
# Define list friends = ['Bob', 'Harry', 'Anne', 'Peter', 'Helen', 'Mary'] print(friends[2:4]) print(type(friends)) friends[1] = 'Susan' print(friends) print('Length of list:', len(friends)) # A counted loop with range for i in range(len(friends)): friend = friends[i] print('Index:', i) print('Happy New Year:', friend) # Manipulating lists lists = list() print(lists) lists.append(300) lists.append('red') lists.append(0.875) print(lists) print(type(lists)) friends.sort() # throws an error due to integers, string value and floating number = a mismatch print(friends) # sorts alphabetically numerals = [1,2,3,4,5,6] print(sum(numerals)) print(max(numerals)) print(min(numerals)) text = 'I have some breaking news!' splitted = text.split() # default is splitting by whitespaces print(splitted) print(len(splitted)) for word in splitted: print(word) sentence = 'first;second;third' splitted_delim = sentence.split(';') print(splitted_delim)
true
15119d609e7855b9330937e8d96e235dd900361e
vkmb/py101
/classes/classes and objects.py
853
4.125
4
# classes.py # - classes and objects class Employee: 'Common base class for all employees' empCount = 0 # This is a class variable def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary # Adding some members "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) # Check and display emp1.displayEmployee() emp2.displayEmployee() print "Total Employees %d" % Employee.empCount # Adding new attributes emp1.location="California" print emp1.location class Manager(Employee): # Manager is an employee
true
954070ef0bbdfc02dd030e2f7ab9a2abdf26d190
mjaw10/assignment
/Spot check pool.py
521
4.21875
4
print("This program will calculate the volume of a pool") width = float(input("Please enter the width of the pool: ")) length = float(input("Please enter te length of the pool: ")) depth = float(input("Please enter the depth of your pool: ")) main_section_volume = length * width * depth circle_radius = width/2 circle_area = 3.14 * (circle_radius ** 2) half_circle_volume = (circle_area / 2) * depth pool_volume = main_section_volume + half_circle_volume print("The pool volume is {0}m³".format(pool_volume))
true