blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
154cf1ad66e4d8fab9b523676935b615ef831d3d
arun-p12/project-euler
/p0001_p0050/p0038.py
2,093
4.125
4
''' 192 x 1 = 192 ; 192 x 2 = 384 ; 192 x 3 576 str(192) + str(384) + str(576) = '192384576' which is a 1-9 pandigital number. What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (2, ... , n) digits? Essentially n > 1 to rule out 918273645 (formed by 9x1 9x2 9x3 ...) ''' ''' Cycle thru each number, get the multiples, and keep appending the string of numbers. When length of the string goes above 9, move onto the next number. If the length of the string is 9, check if it is pandigital. If yes, check if it is maximum ''' def pandigital_multiple(): target = [1, 2, 3, 4, 5, 6, 7, 8, 9] max_str = "" #for x in range(9876, 0, -1): # start from top, and decrement for x in range(1, 9877): i, pand_len = 1, 0 pand_list = [] # sort and test against target pand_str = "" # this is our actual string while (pand_len < 9): next_num = x * i # take each number, and multiply by the next i pand_str += str(next_num) for c in str(next_num): # append new number to our list pand_list.append(int(c)) pand_len = len(pand_list) i += 1 #print("test : ", x, pand_len, i, pand_list, pand_str, pand_cont) if pand_len == 9: pand_list.sort() if pand_list == target: if(pand_str > max_str): max_str = pand_str print("start_num = ", "{:4d}".format(x), "mult_upto = ", "{:1d}".format(i - 1), "result = ", "{:10s}".format(pand_str), "max = ", "{:10s}".format(max_str)) import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# pandigital_multiple() ########## end of main routine ########### t = time.time() - t # and now, after the routine print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
true
4cbef49ee1fd1c6b4a15eae4d2dee12be49475a8
arun-p12/project-euler
/p0001_p0050/p0017.py
2,376
4.125
4
''' If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? Ignore spaces ''' def number_letter_count(number=1000): # number of letters in the word form, for each value dict = {0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6, 30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6, 100:7, 1000:8, 'and':3} # numeric representation of the word dict2 = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand', 'and':'and', 0:''} def word_filler(word): if(word): return(' ') else: return('') word = '' while(number): t = number // 1000 h = (number - t*1000) // 100 d = (number - t*1000 - h*100) // 10 u = int(number - t*1000 - h*100 - d*10) if(t): word += dict2[t] + ' ' + dict2[1000] if(h): word += word_filler(word) + dict2[h] + ' ' + dict2[100] if(((t | h) > 0) & ((d | u) > 0)): word += word_filler(word) + dict2['and'] if(d >= 2): word += word_filler(word) + dict2[d*10] if(d == 1): word += word_filler(word) + dict2[d*10 + u] else: word += word_filler(word) + dict2[u] number -= 1 #print("nlc_2 = ", num, "[[ ", t, h, d, u, word, " ]]") w_len = [len(x) for x in word.split()] return(sum(w_len)) import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# num = 1000 result = number_letter_count(num) ########## end of main routine ########### t = time.time() - t # and now, after the routine print("Letter count in numbers upto {} = {}".format(num, result)) print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
true
c891fec31546ed93374bc833e0bb4870c7e3e188
rmrodge/python_practice
/format_floating_point_in_string.py
800
4.4375
4
# Floating point number is required in programming for generating fractional numbers, # and sometimes it requires formatting the floating-point number for programming purposes. # There are many ways to exist in python to format the floating-point number. # String formatting and string interpolation are used in the following script to format a floating-point number. format() method with format width is used in string formatting, # and ‘%” symbol with the format with width is used in string interpolation. # According to the formatting width, 5 digits are set before the decimal point, and 2 digits are set after the decimal point. # Use of String Formatting float1 = 563.78453 print("{:5.2f}".format(float1)) # Use of String Interpolation float2 = 563.78453 print("%5.2f" % float2)
true
b82b3928481d538244ec70a34fecb0b7ed761f3c
Jeff-ust/D002-2019
/L2/L2Q6v1.py
1,387
4.375
4
#L2 Q6: Banana Guessing game #Step 1: Import necessary modules import random #Step 2: Welcome Message print('''Welcome to the Banana Guessing Game Dave hid some bananas. Your task is to find out the number of bananas he hid.''') #Step 3: Choose a random number between 1-100 n = random.randint(1,100) print ("shhh, Dave hides %s bananas" % n) # define a flag for found/not found and counter on how many trials found = False count = 0 #Step 4: Give three chances to the players p = int(input("Guess a number between 1 and 100.")) while found == False: if p < 1 or p > 100: print("Your guess is out-of-range!") count = count + 1 elif p > n: print("Your guess is too high!") count = count + 1 elif p < n: print("Your guess is too low!") count = count + 1 elif p == n: found = True count = count + 1 if count == 3 and found == False: print("Game over.") break else: #Step 5: Display a message if found == True: print('You got the correct guess in %d trials' % count) print('Dave\'s banana are now all yours!') else: print("You failed to find the number of bananas Dave hid! Try again next") p = int(input("Guess a number between 1 and 100."))
true
fbf0406858a0b3cdb529472d4642b2acea5fa3d2
shouryacool/StringSlicing.py
/02_ strings Slicing.py
820
4.34375
4
# greeting="Good Morning," # name="Harry" # print(type(name)) # # Concatining Two Strings # c=greeting+name # print(c) name="HarryIsGood" # Performing Slicing print(name[0:3]) print(name [:5]) #is Same as [0:4] print(name [:4]) #is Same as [0:4] print(name [0:]) #is Same as [0:4] print(name [-5:-1]) # is same as name [0:4] print(name[-4:-2]) # is same as name [1:3] # Slicing with skip value d=name[1::2] print(d) # The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the following syntax: # We can acess any Characters Of String but cant change it # Negative Indices: Negative indices can also be used as shown in the figure above. -1 corresponds to the (length-1) index, -2 to (length-2). # Q Why To use Negative indices??? # # # #
true
d8f89c6f971a5378300db593da07310ed7dfa31d
AlexanderIvanofff/Python-OOP
/defending classes/programmer.py
2,311
4.375
4
# Create a class called Programmer. Upon initialization it should receive name (string), language (string), # skills (integer). The class should have two methods: # - watch_course(course_name, language, skills_earned) # o If the programmer's language is the equal to the one on the course increase his skills with the given one and # return a message "{programmer} watched {course_name}". # o Otherwise return "{name} does not know {language}". # - change_language(new_language, skills_needed) # o If the programmer has the skills and the language is different from his, change his language to the new one and # return "{name} switched from {previous_language} to {new_language}". # o If the programmer has the skills, but the language is the same as his return "{name} already knows {language}". # o In the last case the programmer does not have the skills, so return "{name} needs {needed_skills} more skills" # and don't change his language class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if self.language == language: self.skills += skills_earned return f"{self.name} watched {course_name}" return f"{self.name} does not know {language}" def change_language(self, new_language, skill_needed): if self.skills >= skill_needed and not self.language == new_language: old_language = self.language self.language = new_language return f"{self.name} switched from {old_language} to {new_language}" elif self.skills >= skill_needed and self.language == new_language: return f"{self.name} already knows {self.language}" return f"{self.name} needs {abs(self.skills - skill_needed)} more skills" programmer = Programmer("John", "Java", 50) print(programmer.watch_course("Python Masterclass", "Python", 84)) print(programmer.change_language("Java", 30)) print(programmer.change_language("Python", 100)) print(programmer.watch_course("Java: zero to hero", "Java", 50)) print(programmer.change_language("Python", 100)) print(programmer.watch_course("Python Masterclass", "Python", 84))
true
6847b974bfa860f4dcec26f502a5b7c6c307e7e8
learn-co-curriculum/cssi-4.8-subway-functions-lab
/subway_functions.py
1,870
4.625
5
# A subway story # You hop on the subway at Union Square. As you are waiting for the train you # take a look at the subway map. The map is about 21 inches wide and 35 inches # tall. Let's write a function to return the area of the map: def map_size(width, height): map_area = width * height return "The map is %d square inches" % (map_area) # Now you give it a shot! It takes about 156 seconds to go between stops and # you'll be taking the train for 3 stops. Write a function that calculates how # long your trip will take. def trip_length(...): # put your code here # The train arrives and you hop on. Guess what time it is? It's showtime! There # are 23 people on the train and each person gives the dancers 1.5 dollars. # Write a function that returns how much money they made. # There is one grumpy lady on the train that doesn't like the dancing though. # Write a function called stop_dancing that returns a message to the dancers in # all caps. # There is also a really enthusiastic rider who keeps shouting "Everything is # awesome!" Write a function that returns everything is awesome 5 times. # You are almost at your stop and you start thinking about how you are going to # get home. You have $18 left on your metro card. Write a function that returns # how many trips you have left. # Call your functions below: print "How big is that subway map?" # Call your function here - like this: map_size(21, 35) # ... but that doesn't output anything. Hmm. See if you can fix it. print "This is how long the trip will take" trip_length(...) print "How much money did the train dancers make?" # call your function here print "That lady told the train dancers to" # call your function here print "That guy kept shouting" # call your function here print "This is how many trips I have left on my metrocard" # call your function here
true
1c832205ec93dc322ab47ed90c339a9d81441282
nyu-cds/asn264_assignment3
/product_spark.py
590
4.1875
4
''' Aditi Nair May 7 2017 Assignment 3, Problem 2 This program creates an RDD containing the numbers from 1 to 1000, and then uses the fold method and mul operator to multiply them all together. ''' from pyspark import SparkContext from operator import mul def main(): #Create instance of SparkContext sc = SparkContext("local", "product") #Create RDD on the list of numbers [1,2,...,1000] nums = sc.parallelize(range(1,1000+1)) #Use fold to aggregate data set elements by multiplicaton (ie multiply them all together) print(nums.fold(1,mul)) if __name__ == '__main__': main()
true
9723db9bc6f9d411d0ae62f525c33a410af9f529
george-ognyanov-kolev/Learn-Python-Hard-Way
/44.ex44.py
981
4.15625
4
#inheritance vs composition print('1. Actions on the child imply an action on the parent.\n') class Parent1(object): def implicit(self): print('PARENT implicit()') class Child1(Parent1): pass dad1 = Parent1() son1 = Child1() dad1.implicit() son1.implicit() print('2. Actions on the child override the action on the parent.\n') class Parent2(object): def override(self): print('PARENT override()') class Child2(Parent2): def override(self): print('CHILD override()') dad2 = Parent2() son2 = Child2() dad2.override() son2.override() print('3. Actions on the child alter the action on the parent.\n') class Parent3(object): def altered(self): print('PARENT3 altered()') class Child3(Parent3): def altered(self): print('CHILD BEFORE PARENT altered()') super(Child3, self).altered() print('CHILD AFTER altered()') dad3 = Parent3() son3 = Child3() dad3.altered() son3.altered()
true
e5663cb79ea48d897aacc4350443c713dee27d5e
jejakobsen/IN1910
/week1/e4.py
773
4.15625
4
""" Write a function factorize that takes in an integer $n$, and returns the prime-factorization of that number as a list. For example factorize(18) should return [2, 3, 3] and factorize(23) should return [23], because 23 is a prime. Test your function by factorizing a 6-digit number. """ def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes def factorize(n): P = get_primes(n) ls = [] while n > 1: for p in P: if n%p == 0: ls.append(p) n = n/p break return ls print(factorize(921909)) """ C:\\Users\\jensj\\OneDrive\\Skrivebord\\IN1910\\week1>python e4.py [3, 23, 31, 431] """
true
8e1f774d2d8748ae9f0a7707208ebf6e77ca8f7a
Yousab/parallel-bubble-sort-mpi
/bubble_sort.py
981
4.1875
4
import numpy as np import time #Bubble sort algorithm def bubble_sort(nums): # We set swapped to True so the loop looks runs at least once swapped = True while swapped: swapped = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: # Swap the elements nums[i], nums[i + 1] = nums[i + 1], nums[i] # Set the flag to True so we'll loop again swapped = True # Verify it works random_list_of_nums = [5, 2, 1, 8, 4] #User input size arraySize = input("Please enter array size: ") #Generate numbers of size n numbers = np.arange(int(arraySize)) np.random.shuffle(numbers) print("Generated list of size " + str(arraySize) + " is:" + str(numbers)) #start script with parallel processes start_time = time.time() bubble_sort(numbers) print("\n\n Sorted Array: " + str(numbers)) #End of script print("\n\n Execution Time --- %s seconds ---" % (time.time() - start_time))
true
0791a754b6620486dd07026672d3e27dd533da7f
helpmoeny/pythoncode
/Python_labs/lab09/warmup1.py
2,104
4.34375
4
## ## Demonstrate some of the operations of the Deck and Card classes ## import cards # Seed the random number generator to a specific value so every execution # of the program uses the same sequence of random numbers (for testing). import random random.seed( 25 ) # Create a deck of cards my_deck = cards.Deck() # Display the deck (unformatted) print( "===== initial deck =====" ) print( my_deck ) print() # Display the deck in 13 columns print( "===== initial deck =====" ) my_deck.pretty_print( column_max=13 ) # Shuffle the deck, then display it in 13 columns my_deck.shuffle() print( "===== shuffled deck =====" ) my_deck.pretty_print( column_max=13 ) # Deal first card from the deck and display it (and info about the deck) card1 = my_deck.deal() print( "First card dealt from the deck:", card1 ) print() print( "Card suit:", card1.get_suit() ) print( "Card rank:", card1.get_rank() ) print( "Card value:", card1.get_value() ) print() print( "Deck empty?", my_deck.is_empty() ) print( "Number of cards left in deck:", my_deck.cards_count() ) print() # Deal second card from the deck and display it (and info about the deck) card2 = my_deck.deal() print( "Second card dealt from the deck:", card2 ) print() print( "Card suit:", card2.get_suit() ) print( "Card rank:", card2.get_rank() ) print( "Card value:", card2.get_value() ) print() print( "Deck empty?", my_deck.is_empty() ) print( "Number of cards left in deck:", my_deck.cards_count() ) print() # Compare the two cards if card1.equal_suit( card2 ): print( card1, "same suit as", card2 ) else: print( card1, "and", card2, "are from different suits" ) if card1.equal_rank( card2 ): print( card1, "and", card2, "of equal rank" ) elif card1.get_rank() > card2.get_rank(): print( card1, "of higher rank than", card2 ) else: print( card2, "of higher rank than", card1 ) if card1.equal_value( card2 ): print( card1, "and", card2, "of equal value" ) elif card1.get_value() > card2.get_value(): print( card1, "of higher value than", card2 ) else: print( card2, "of higher value than", card1 )
true
4983ce5f51d32706025dead611acdbfdea92594c
Ramtrap/lpthw
/ex16.py
1,284
4.125
4
from sys import argv print "ex16.py\n" script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." # target.write(line1) # target.write("\n") # target.write(line2) # target.write("\n") # target.write(line3) # target.write("\n") # Above is too long, this is truncated below target.write(line1 + "\n" + line2 + "\n" + line3 + "\n") print "Now let's take a look at what it says!" raw_input("Press ENTER to continue:") print "Here's your file %r:" % filename print "\n" target = open(filename, 'r') print target.read() print "And finally, we close it." target.close() # print "Type the filename again:" # file_again = raw_input("> ") # # txt_again = open(file_again) # # print txt_again.read() # txt.close # txt_again.close # print "Your files, %r and %r, have been closed." % (filename, file_again)
true
ef3e1712df8cf28034c6ab2fc8d3fd46b4683783
shivsun/pythonappsources
/Exercises/Integers/accessing elements in the list with messages.py
1,294
4.4375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 25 21:09:17 2020 @author: bpoli """ #Accessing Elements in a List #Lists are ordered collections, so you can access any element in a list by #telling Python the position, or index, of the item desired. To access an element #in a list, write the name of the list followed by the index of the item #enclosed in square brackets. #For example, let’s pull out the first bicycle in the list bicycles: bikes = ["Royal Enfield", "Rajdoot", "Bajaj Chetak", "TVS Super"] name = 'kishore' name2 = 'vidya' name3 = 'Sam' print (bikes[3].title()) print (bikes[2]) print (bikes[-1]) message = "my first bike was " + bikes[2].title().upper() + "\t\nThen i bought" + bikes [0].lower() message = "I have 2 friends, and both" + name.title() + "," + name2.title() + "comes to school on the bikes" print (message + "They ride" + bikes[2]+ "," + bikes [0] + "respectively!") print (message) #Python has a special syntax for accessing the last element in a list. By asking #for the item at index -1, Python always returns the last item in the list: #Tvs Super #Bajaj Chetak #TVS Super #I have 2 friends, and bothKishore,Vidyacomes to school on the bikesThey rideBajaj Chetak,Royal Enfieldrespectively! #I have 2 friends, and bothKishore,Vidyacomes to school on the bikes
true
0b111a4e7f476a46248db5680d9c0ab9d1aebc1d
miffymon/Python-Learning
/ex06.py
1,210
4.40625
4
#Python function pulls the value although its not announced anywhere else #string in a string 1 x = "There are %d types of people." % 10 #naming variable binary = "binary" #naming variable do_not = "don't" #assigning sentence to variable and calling other assigned variables #string in a string 2 y = "Those who know %s and those who %s." % (binary, do_not) #printing sentences by their variables print x print y #prints left side of sentence, calls a format and assignes variable which completes the rest of the sentence #string in a string 3 print "I said: %r" % x print "I also said: '%s'" % y #names variable hilarious to false hilarious = False #names variable to rep a sentence and include the ref to another variable to be named #string in a string 4 joke_evaluation = "Isn't that joke so funny?! %r" #calls upon 2 variables and puts them side-by-side #string in a string 5 print joke_evaluation % hilarious #calls variables rep by parts of a sentence w = "This is the left side of ..." e = "a string with a right side." #adds the first variable's value to the other in the same order #w+e makes a longer string because the two assigned sentences assigned to the variables are long print w + e
true
f533dddb9e2ba1ecb1d1a7b0a4a6ceb20976d022
ferisso/phytonexercises
/exercise7.py
893
4.21875
4
# Question: # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. # Note: i=0,1.., X-1; j=0,1,¡­Y-1. # Example # Suppose the following inputs are given to the program: # 3,5 # Then, the output of the program should be: # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # Hints: # Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. first_input = input("> ") dimensions = [int(x) for x in first_input.split(',')] numero_de_linhas = dimensions[0] numero_de_colunas = dimensions[1] matriz = [[0 for col in range(numero_de_colunas)] for row in range(numero_de_linhas)] for row in range(numero_de_linhas): for col in range(numero_de_colunas): matriz[row][col]= row*col print (matriz)
true
5cf93df98db5fb6fe7444fffbbd1fa79559607cd
lavalio/ChamplainVRSpecialist-PythonAlgorithms
/Week4/Class1/Homework.py
1,080
4.25
4
#Create a list of numbers, randomly assigned. #Scan the list and display several values:The minimum, the maximum, count and average #Don`t use the “min”, “max”, “len ” and “sum” functions #1. Len : gives the number of elements in array. #2. Min, max: Gives the highest highestor lowest number in the array. #3. Sum: Adds all the numbers in array. import random mylist = [] for a in range(10): mylist.append(random.randint(1,101)) print(mylist) # Length of the list len = 0 for x in mylist: len += 1 print('len = ',len) # Sum of the list sum=0 for x in mylist: sum += x print('sum = ',sum) # Average of the list print('ave = ',sum/len) # Max Value maxValue = mylist[0] for y in mylist: if y > maxValue: maxValue = y print ('max = ',maxValue) # Min Value minValue = mylist[0] for y in mylist: if y < minValue: minValue = y print ('min = ',minValue) #print('len = ',len(mylist)) #print('max = ',max(mylist)) #print('min = ',min(mylist)) #print('sum = ',sum(mylist)) #print('ave = ',sum(mylist)/len(mylist))
true
e8cf2f63f38c417981c670689bbb649ccb1f296d
annikaslund/python_practice
/python-fundamentals/04-number_compare/number_compare.py
301
4.15625
4
def number_compare(num1, num2): """ takes in two numbers and returns a string indicating how the numbers compare to each other. """ if num1 > num2: return "First is greater" elif num2 > num1: return "Second is greater" else: return "Numbers are equal"
true
91e08c304bdf2dcade4f00ad513711d7cadde116
annikaslund/python_practice
/python-fundamentals/18-sum_even_values/sum_even_values.py
235
4.15625
4
def sum_even_values(li): """ sums even values in list and returns sum """ total = 0 for num in li: if num % 2 == 0: total += num return total # return sum([num for num in li if num % 2 == 0])
true
4a5ffb428059845f0761201c602942bb964f0e55
19doughertyjoseph/josephdougherty-python
/TurtleProject/Turtle Project.py
939
4.125
4
import turtle turtle.setup(width=750, height=750) pen = turtle.Pen() pen.speed(200) black_color = (0.0, 0.0, 0.0) white_color = (1.0, 1.0, 1.0) red_color = (1.0, 0.0, 0.0) green_color = (0.0, 1.0, 0.0) blue_color = (0.0, 0.0, 1.0) def basicLine(): moveTo(-50, 0) pen.forward(100) #The origin on the screen is (0,0) def basicSquare(): pen.pencolor(blue_color) moveTo(-100, -100) for x in range(4): pen.forward(200) pen.left(90) def basicCircle(): pen.pencolor(red_color) moveTo(0, -300) pen.circle(300) def basicTriangle(): pen.pencolor('#33cc8c') moveTo(-200, -150) for x in range(3): pen.forward(400) pen.left(120) def moveTo(x, y): pen.penup() pen.setpos(x, y) pen.pendown() #Between drawings we have to pick up the pen and move it to the desired location basicLine() basicSquare() basicCircle() basicTriangle() turtle.exitonclick()
true
0ed3044556e7faa1464a480dbe0550b2a22e20c5
leobyeon/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
360
4.28125
4
#!/usr/bin/python3 def append_write(filename="", text=""): """ appends a string at the end of a text file and returns the number of chars added """ charCount = 0 with open(filename, "a+", encoding="utf-8") as myFile: for i in text: charCount += 1 myFile.write(i) myFile.close() return charCount
true
828a52fcf979bb4c8dc3793babbfcf41a71efa2b
Nipuncp/lyceaum
/lpthw/ex3.py
479
4.25
4
print ("I'll now count my chickens") print ("Hens:", 25 +30 / 6) print ("Roosters", 100-25 *3%4) print ("I'll now count the eggs:") print (3 +2 + 1 - 5 + 4 % 2-1 % 4 + 6) print ("Is it true that 3 + 2 < 5 - 7") print (3 + 2 < 5 -7) print ("What is 3 + 2", 3 + 2) print ("What is 5 - 7", 5 - 7) print ("THat is why, it is false") print ("HOw about some more?") print ("Is it greater?", 5 >= -2) print ("Is it greater or equal?", 5 >= -2) print ("Is it lesser or equal",5 <= -2)
true
fefe99ae80decc1c40885d81430a651ddbcd3541
anupam-newgen/my-python-doodling
/calculator.py
281
4.15625
4
print('Add 2 with 2 = ', (2 + 2)) print('Subtract 2 from 2 = ', (2 - 2)) print('Multiply 2 with 2 = ', (2 * 2)) print('2 raise to the power 2 = ', (2 ** 2)) print('2 divide by 2 = ', (2 / 2)) # This is a comment. # You can use above concept to solve complex equations as well.
true
4df2e2270df04452ca0403b08547f2bebad70504
selva86/python
/exercises/concept/guidos-gorgeous-lasagna/.meta/exemplar.py
1,640
4.28125
4
# time the lasagna should be in the oven according to the cookbook. EXPECTED_BAKE_TIME = 40 PREPARATION_TIME = 2 def bake_time_remaining(elapsed_bake_time): """Calculate the bake time remaining. :param elapsed_bake_time: int baking time already elapsed :return: int remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME' Function that takes the actual minutes the lasagna has been in the oven as an argument and returns how many minutes the lasagna still needs to bake based on the `EXPECTED_BAKE_TIME`. """ return EXPECTED_BAKE_TIME - elapsed_bake_time def preparation_time_in_minutes(number_of_layers): """Calculate the preparation time. :param number_of_layers: int the number of lasagna layers made :return: int amount of prep time (in minutes), based on 2 minutes per layer added This function takes an integer representing the number of layers added to the dish, calculating preparation time using a time of 2 minutes per layer added. """ return number_of_layers * PREPARATION_TIME def elapsed_time_in_minutes(number_of_layers, elapsed_bake_time): """Calculate the elapsed time. :param number_of_layers: int the number of layers in the lasagna :param elapsed_bake_time: int elapsed cooking time :return: int total time elapsed (in in minutes) preparing and cooking This function takes two integers representing the number of lasagna layers and the time already spent baking and calculates the total elapsed minutes spent cooking the lasagna. """ return preparation_time_in_minutes(number_of_layers) + elapsed_bake_time
true
0a7def488ed51a9d0b3e3a1a5ccc8a29efa89a23
selva86/python
/exercises/concept/little-sisters-vocab/.meta/exemplar.py
1,648
4.3125
4
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ return 'un' + word def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words with prefix applied, separated by ' :: '. """ prefix = vocab_words[0] joiner = ' :: ' + prefix return joiner.join(vocab_words) def remove_suffix_ness(word): """ :param word: str of word to remove suffix from. :return: str of word with suffix removed & spelling adjusted. This function takes in a word and returns the base word with `ness` removed. """ word = word[:-4] if word[-1] == 'i': word = word[:-1] + 'y' return word def noun_to_verb(sentence, index): """ :param sentence: str that uses the word in sentence :param index: index of the word to remove and transform :return: str word that changes the extracted adjective to a verb. A function takes a `sentence` using the vocabulary word, and the `index` of the word once that sentence is split apart. The function should return the extracted adjective as a verb. """ word = sentence.split()[index] if word[-1] == '.': word = word[:-1] + 'en' else: word = word + 'en' return word
true
3db5a554acc92051d4ec7a544a4c922fcad49309
PradipH31/Python-Crash-Course
/Chapter_9_Classes/C2_Inheritance.py
1,094
4.5625
5
#!./ENV/bin/python # ---------------------------------------------------------------- # Inheritance class Car(): """Class for a car""" def __init__(self, model, year): """Initialize the car""" self.model = model self.year = year def get_desc_name(self): """Get the descriptive name of the car""" return (str(self.year) + self.model) # Child class is initialized by super().__init__(paramters(without self)) # Child class iherits the methods from the parent. # Override the parent methods class ElectricCar(Car): """Class from car class""" def __init__(self, model, year, batt_size): """initialize the electric car""" super().__init__(model, year) self.batt_size = batt_size def get_batt(self): """returns the battery""" return self.batt_size def get_desc_name(self): """Get the descriptive name of the car""" return ("Electric " + str(self.year) + self.model) my_tesla = ElectricCar("Audi", 1990, 90) print(my_tesla.get_desc_name()) print(my_tesla.get_batt())
true
c684cf0f8d15e4e684b2668eaf0bfadd8b30306a
PradipH31/Python-Crash-Course
/Chapter_9_Classes/C1_Book.py
959
4.4375
4
#!./ENV/bin/python # ---------------------------------------------------------------- # # Classes class Book(): """Class for a book""" def __init__(self, name, year): """Initialize the book with name and year""" self.name = name self.year = year def get_name(self): """Returns the name of the book""" return self.name my_book = Book("NOSP", "2012") print(my_book.get_name()) class Car(): """Car class""" def __init__(self, name, year): self.name = name self.year = year self.met_traveled = 0 def set_met(self, m): if m > self.met_traveled: self.met_traveled = m def upd_met(self, m): self.met_traveled += m my_car = Car("Toyota", "1999") # Modifying attributes of an object directly through the variable my_car.met_traveled = 20 # through a method my_car.set_met(11) # adding new value to the current value my_car.upd_met(19)
true
9a76041b4f7465fc6061ed4ee3efb65899a258db
alexugalek/tasks_solved_via_python
/HW1/upper_lower_symbols.py
374
4.46875
4
# Task - Count all Upper latin chars and Lower latin chars in the string test_string = input('Enter string: ') lower_chars = upper_chars = 0 for char in test_string: if 'a' <= char <= 'z': lower_chars += 1 elif 'A' <= char <= 'Z': upper_chars += 1 print(f'Numbers of lower chars is: {lower_chars}') print(f'Numbers of upper chars is: {upper_chars}')
true
fea598032ae2a1c7676e6b0286d2fae1362bdfa3
alexugalek/tasks_solved_via_python
/HW1/task_5.py
418
4.40625
4
def add_binary(a, b): """Instructions Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. """ return bin(a + b)[2:] if __name__ == '__main__': a = int(input('Enter 1 number: ')) b = int(input('Enter 2 number: ')) print(add_binary(a, b))
true
6889e39e73935e704d91c750b3a13edb36133afc
alexugalek/tasks_solved_via_python
/HW1/task_23.py
1,327
4.4375
4
def longest_slide_down(pyramid): """Instructions Imagine that you have a pyramid built of numbers, like this one here: 3 7 4 2 4 6 8 5 9 3 Here comes the task... Let's say that the 'slide down' is a sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest 'slide down' is 3 + 7 + 4 + 9 = 23 """ for line in range(len(pyramid) - 2, -1, -1): for column in range(len(pyramid[line])): pyramid[line][column] += max(pyramid[line + 1][column], pyramid[line + 1][column + 1]) return pyramid[0][0] print(longest_slide_down([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]])) # 23 print(longest_slide_down([ [75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23], ])) # 1074
true
a5306511c39e1a2bd0e3077f86df25e6e47f2dc6
firozsujan/pythonBasics
/Lists.py
1,629
4.1875
4
# Task 9 # HakarRank # Lists # https://www.hackerrank.com/challenges/python-lists/problem def proceessStatement(insertStatement, list): if insertStatement[0] == 'insert': return insert(insertStatement, list) elif insertStatement[0] == 'print': return printList(insertStatement, list) elif insertStatement[0] == 'remove': return remove(insertStatement, list) elif insertStatement[0] == 'append': return append(insertStatement, list) elif insertStatement[0] == 'sort': return sort(insertStatement, list) elif insertStatement[0] == 'pop': return pop(insertStatement, list) elif insertStatement[0] == 'reverse': return reverse(insertStatement, list) def insert(insertStatement, list): position = int(insertStatement[1]) insert = int(insertStatement[2]) updatedList = [] updatedList = list[:position] + [insert] + list[position:] return updatedList def printList(insertStatement, list): print(list) return list def remove(insertStatement, list): list.remove(int(insertStatement[1])) return list def append(insertStatement, list): list.append(int(insertStatement[1])) return list def sort(insertStatement, list): list.sort() return list def pop(insertStatement, list): list.pop() return list def reverse(insertStatement, list): list.reverse() return list if __name__ == '__main__': N = int(input()) list = [] for i in range(N): insertStatement = [] insertStatement = input().split(' ') list = proceessStatement(insertStatement, list)
true
86b3488e679b6e34d43d0be6e219a6f01761b3e1
firozsujan/pythonBasics
/StringFormatting.py
655
4.125
4
# Task # HackerRank # String Formatting # https://www.hackerrank.com/challenges/python-string-formatting/problem def print_formatted(number): width = len(bin(number)[1:]) printString = '' for i in range(1, number+1): for base in 'doXb': if base == 'd': width = len(bin(number)[2:]) else : width = len(bin(number)[1:]) printString = printString + "{:{width}{base}}".format(i, base=base, width=width) printString = printString + '\n' print(printString) if __name__ == '__main__': n = int(input()) print_formatted(n)
true
87324442d3dabfdcae8ef4bbea84f21f1586d663
drdiek/Hippocampome
/Python/dir_swc_labels/lib/menu/select_processing.py
1,109
4.125
4
def select_processing_function(): reply = '' # main loop to display menu choices and accept input # terminates when user chooses to exit while (not reply): try: print("\033c"); # clear screen ## display menu ## print 'Please select your processing function of interest from the selections below:\n' print ' 1) Conversion of .swc file(s)' print ' 2) Plotting of an .swc file' print ' 3) Creation of a morphology matrix file' print ' !) Exit' reply = raw_input('\nYour selection: ') ## process input ## if reply == '!': return('!') else: num = int(reply) if ((num > 0) & (num <= 3)): return(num) else: reply = '' except ValueError: print 'Oops! That was not a valid number. Please try again ...'
true
f46893c5784cc16ad9c4bcaf19d47a126e1f02a5
Granbark/supreme-system
/binary_tree.py
1,080
4.125
4
class Node(): def __init__(self, value): self.value = value self.left = None self.right = None class BST(): def __init__(self): self.root = None def addNode(self, value): return Node(value) #returns a Node, see class def addBST(self, node, number): #node = current node, number is what you wish to add if node is None: return self.addNode(number) #go left elif number < node.value: node.left = self.addBST(node.left, number) #go right elif number > node.value: node.right = self.addBST(node.right, number) return node def printBST(self, node): #Print values from root #In order if node.left is not None: self.printBST(node.left) print(node.value) if node.right is not None: self.printBST(node.right) return if __name__ == "__main__": bst = BST() root = Node(50) bst.root = root bst.addBST(bst.root, 15) bst.addBST(bst.root, 99) bst.addBST(bst.root, 25) bst.addBST(bst.root, 56) bst.addBST(bst.root, 78) bst.printBST(bst.root)
true
6a5cf3421133b39a0108430efee4d3c9ba51933f
megnicd/programming-for-big-data_CA05
/CA05_PartB_MeganMcDonnell.py
2,112
4.1875
4
#iterator def city_generator(): yield("Konstanz") yield("Zurich") yield("Schaffhausen") yield("Stuttgart") x = city_generator() print x.next() print x.next() print x.next() print x.next() #print x.next() #there isnt a 5th element so you get a stopiteration error print "\n" cities = city_generator() for city in cities: print city print "\n" #list generator def fibonacci(n): """Fibonacci numbers generator, first n""" a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(5) #yields the first 5 fibonacci lists as the programme calculates them print x, print #convert to celcius using list comprehension def fahrenheit(t): return ((float(9)/5)*t + 32) def celsius(t): return (float(5)/9*(t - 32)) temp = (36.5, 37, 37.5, 39) F = map(fahrenheit, temp) print F C = map(celsius, F) print C #max using reduce def max(values): return reduce(lambda a,b: a if (a>b) else b, values) print max([47, 11, 42, 13]) #min using reduce def min(values): return reduce(lambda a,b: a if (a<b) else b, values) print min([47, 11]) #add using reduce def add(values): return reduce(lambda a,b: a+b, values) print add([47, 11, 42, 13]) #subtract using reduce def sub(values): return reduce(lambda a,b: a-b, values) print sub([47, 11]) #multiply using reduce def mul(values): return reduce(lambda a,b: a*b, values) print mul([2,5]) #divide using reduce def div(values): return reduce(lambda a,b: a/float(b) if (b != 0 and a != 'Nan') else 'Nan', values) print div([47, 'Nan', 0, 11]) #find even numbers using filter def is_even(values): return filter(lambda x: x % 2 == 0, values) print is_even([47, 11, 42, 13]) #conversion using map def to_fahrenheit(values): return map(fahrenheit, values) print to_fahrenheit([0, 37, 40, 100]) #conversion using map def to_celsius(values): return map(celsius, values) print to_celsius([0, 32, 100, 212])
true
2d3fb98cd2c98c632c60fc9da686b6567c1ea68d
jaimedaniels94/100daysofcode
/day2/tip-calculator.py
402
4.15625
4
print("Welcome to the tip calculator!") bill = float(input("What was the total bill? $")) tip = int(input("What percentage tip would you like to give? 10, 12, or 15? ")) split = int(input("How many people will split the bill? ")) bill_with_tip = tip / 100 * bill + bill bill_per_person = bill_with_tip / split final_amount = round(bill_per_person, 2) print(f"Each person should pay ${final_amount})
true
2b47e8987cc92f9069fa12915030329d764cf032
tomahim/project-euler
/python_solutions/problem3.py
780
4.125
4
from python_solutions.utils import timing @timing def compute_largest_prime_factor(value: int): denominator = 2 while denominator < value: disivion_result = value / denominator if disivion_result.is_integer(): value = disivion_result else: denominator += 1 return value if __name__ == '__main__': """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ example_value = 13195 example_answer = 29 assert example_answer == compute_largest_prime_factor(example_value) problem_value = 600851475143 result = compute_largest_prime_factor(problem_value) print(f'Largest prime factor of {problem_value} is : {result}')
true
c70b8b6d2966f6620ad280ca6cabd29bac4cadc1
Harrywekesa/Sqlite-database
/using_place_holders.py
562
4.1875
4
import sqlite3 #Get personal data from the user aand insert it into a tuple First_name = input("Enter your first name: ") Last_name = input("Enter your last name: ") Age = input("Enter your age: ") personal_data = (First_name, Last_name, Age) #Execute insert statement for supplied personal data with sqlite3.connect("place_holder.db") as conn: c = conn.cursor() c.execute("DROP TABLE IF EXISTS people") c.execute("CREATE TABLE people(First_name TEXT, Last_name TEXT, Age INT)") c.execute("INSERT INTO people VALUES(?, ?, ?)", personal_data)
true
b720f24465dda89e7ff7e6dd6f0fdde60fdb297d
vpreethamkashyap/plinux
/7-Python/3.py
1,594
4.21875
4
#!/usr/bin/python3 import sys import time import shutil import os import subprocess print ("\nThis Python script help you to understand Types of Operator \r\n") print ("Python language supports the following types of operators. \r\n") print ("Arithmetic Operators \r\n") print ("Comparison (Relational) Operators \r\n") print ("Assignment Operators \r\n") print ("Logical Operators \r\n") print ("Bitwise Operators \r\n") print ("Membership Operators \r\n") print ("Identity Operators \r\n") print ("Let us have a look on all operators one by one. \r\n") raw_input("Press enter to see how to aithrmetic operations occurs\n") var a = 50 var b = 20 var c c = a+b print("Addition of a & b is %d \r\n" %c) c = a-b print("Subtraction of a & b is %d \r\n" %c) c = a*b print("Multiplication of a & b is %d \r\n"%c) c = a/b print("Division of a & b is %d \r\n"%c) c = a%b print("Modulus of a & b is %d \r\n" %c) c = a**b print("Exponent of a & b is %d \r\n" %c) c = a//b print("Floor Division of a & b is %d \r\n" %c) raw_input("Press enter to see how to aithrmetic operations occurs\n") print("Python Comparison Operators\r\n") if(a == b): print(" a & b are same \r\n") if(a != b): print("a & b are not same\r\n") if(a > b): print("a is greater than b\r\n") if(a < b): print("b is greater than a\r\n") raw_input("Press enter to see how to Bitwise operations occurs\n") print ("\r\n Bit wise operator a&b %b \r\n" % (a&b)) print ("\r\n Bit wise operator a|b %b \r\n" % (a|b)) print ("\r\n Bit wise operator a^b %b \r\n" % (a^b)) print ("\r\n Bit wise operator ~a %b \r\n" % (~a))
true
db59ee60efb684c780262407c276487760cca73c
RoshaniPatel10994/ITCS1140---Python-
/Array/Practice/Beginin array in lecture.py
1,815
4.5
4
# Create a program that will allow the user to keep track of snowfall over the course 5 months. # The program will ask what the snowfall was for each week of each month ans produce a total number # of inches and average. It will also print out the snowfall values and list the highest amount of snow and the lowest amount of snow. # Declare variables snowfall = [0,0,0,0,0] index = int() one_month = float() total_inches = float() ave_inches = float() highest_inches = float() lowest_inches = float() ## #For loop ##for index in range(0, 5): ## #ask use for months snowfall ## one_month = float(input("Enter months of snowfall: ")) ## snowfall[index] = one_month ##print() snowfall = [10, 12, 14, 16, 18] for index in range(0, len(snowfall)): one_month = snowfall[index] print("Monthly snow fall : ", one_month) print() # Determin the total inches of snow fall for index in range(0, len(snowfall)): one_month = snowfall[index] total_inches = total_inches + one_month print(" total snowfall : ", total_inches) # average snowfall ave_inches = total_inches / (index + 1) print("Average snowfall: - " , ave_inches ) # Determine heighest value highest_inches = snowfall[0] for index in range(0, len(snowfall)): one_month = snowfall[index] if one_month > highest_inches : highest_inches = one_month #endif print("highest snowfall: - " , highest_inches ) # Determine Lowest value lowest_inches = snowfall[0] for index in range(0, len(snowfall)): one_month = snowfall[index] if one_month < lowest_inches : lowest_inches = one_month print("lowest snowfall: - " , lowest_inches )
true
c3869c3a16815c7934e88768d75ee77a4bcc207d
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 5/LookingForDatesPython.py
1,479
4.40625
4
#Looking For Dates Program #Written by: Betsy Jenaway #Date: July 31, 2012 #This program will load an array of names and an array of dates. It will then #ask the user for a name. The program will then look for the user in the list. #If the name is found in the list the user will get a message telling them #the name was found and the person's birthdate. Otherwise they will get a #message telling them the name #was not found and to try again. NOTE: this #program differs from the Raptor program in that it continually asks the user #for a name until one is found in the list. #Declare Variables #Loading the array with names Friends = ["Matt", "Susan", "Jim", "Bob"] Dates = ["12/2/99", "10/15/95", "3/7/95", "6/24/93"] SearchItem = "nothing" FoundDate = "nothing" FoundIndex = 0 Index = 0 Flag = False #Look for the name and tell the user if the program found it #Keep asking the user for a name until one is found. while Flag == False: #Ask the user for the name to search for SearchItem = input("What is the name you are looking for? ") if SearchItem in Friends: #Find out what the index is for the Found Name FoundIndex = Friends.index(SearchItem) FoundDate = Dates[FoundIndex] Flag = True print("We found your name!") print(SearchItem, "'s Birthday is: ", FoundDate) else: print("Sorry we did not find your name. Please try again.") Flag = False
true
c4a91a468b3c96852d1365870230b15433f8007c
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 2/chips.py
989
4.15625
4
# Roshani Patel # 2/10/20 # Chips # This program Calculate the cost of an order of chips. # Display program that will ask user how many bags of chips they want to buy. #In addition ask the user what size of bag. #If the bag is 8 oz the cost is 1.29 dollar if the bag is 16 oz then the cost is 3.59 dollars. #If bag is 32 oz then cost is $5.50. calculate the total cost of the order including tax at 6%. ## Declare Variable Size = 0 Qty = 0 Price = 0.0 Cost = 0.0 # Display Menu print("1 - 8 oz\t$1.29") print("2 - 16 oz\t$3.59") print("3 - 32 0z\t$5.50") # Bet Input Size = int(input("Enter size: ")) if Size == 1 or Size == 2 or Size == 3: Qty = int(input("Enter quantity: ")) # Calculate the COst if Size == 1: Price = 1.29 elif Size == 2: Price = 3.59 elif Size == 3: Price = 5.50 else: print("Enter 1, 2, or 3") Cost = Price * Qty * 1.06 # Display Cost print("Cost = $",format(Cost, '.2f'))
true
a95bdaa18d1b88eb8d178998f6af8f1066939c81
Lin-HsiaoJu/StanCode-Project
/stanCode Project/Wheather Master/weather_master.py
1,463
4.34375
4
""" File: weather_master.py Name: Jeffrey.Lin 2020/07 ----------------------- This program should implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ # This number controls when to stop the weather_master EXIT = -100 def main(): """ This program find and calculate the highest temperature, the lowest temperature, the average of daily temperature and the total days of cold day among the user inputs of everyday's temperature. """ print('stanCode "Weather Master 4.0"!') data = int(input('Next Temperature:(or '+str(EXIT)+' to quit)?')) if data == EXIT: print('No temperature were entered.') else: maximum = int(data) minimum = int(data) num = 1 sum = int(data) if maximum < 16: cold = 1 else: cold = 0 while True: data = int(input('Next Temperature:(or -100 to quit)?')) if data == EXIT: break else: sum += data num += 1 if data < 16: cold += 1 if data >= maximum: maximum = data if data <= minimum: minimum = data average = float(sum/num) print('Highest Temperature = ' + str(maximum)) print('Lowest Temperature = ' + str(minimum)) print('Average = ' + str(average)) print(str(cold) + ' cold day(s)') ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
92e0031f054add61799cd4bfcd81a835e705af0d
ruthvika-mohan/python_scripts-
/merge_yearly_data.py
1,002
4.125
4
# Import required modules # Glob module finds all the pathnames matching a specified pattern # Pandas required to do merge operation # chdir() method in Python used to change the current working directory to specified path. from os import chdir from glob import glob import pandas as pdlib # Move to the path that holds our CSV files csv_file_path = 'C:\folder_containing_csv_files' chdir(csv_file_path) # List all CSV files in the working directory list_of_files = [file for file in glob('*.csv')] print(list_of_files) """ Function: Produce a single CSV after combining all files """ def produceOneCSV(list_of_files,file_out): # Consolidate all CSV files into one object result_obj = pdlib.concat([pdlib.read_csv(file,header = 0,encoding = 'cp1252') for file in list_of_files],ignore_index = True) # Convert the above object into a csv file and export result_obj.to_csv(file_out) file_out = "MergedOutput.csv" produceOneCSV(list_of_files,file_out)
true
a29e29d8f4e58d67a3d7cf38132b587cb8c27822
dinulade101/ECE322Testing
/command/cancelBookingCommand.py
2,224
4.3125
4
''' This file deals with all the commands to allow the user to cancel bookings. It will initially display all the user's bookings. Then the user will select the number of the booking displayed to cancel. The row of the booking in the db will be removed. The member who's booking was canceled will get an automated message as well. ''' import sqlite3 import re import sys from command.command import Command from book_rides.cancel_booking import CancelBooking class CancelBookingCommand(Command): def __init__(self, cursor, email): super().__init__(cursor) self.email = email self.cb = CancelBooking(cursor) def menu(self): print(''' Cancel bookings:\n Press Ctrl-c to return to menu\n''') rows = self.cb.get_member_bookings(self.email) if len(rows) == 0: print("You do not have any bookings!") return valid_bno = set() for row in rows: valid_bno.add(row[0]) print("\nYour bookings:\n") self.display_page(0, rows, valid_bno) def cancel_booking(self,bno): # delete the booking and create a message for the booker self.cb.cancel_booking(self.email, bno) print('Booking canceled successfully!') def display_page(self, page_num, rows, valid_bno): page = rows[page_num*5: min(page_num*5+5, len(rows))] for row in page: print("Booking No. {0} | User: {1} | Cost: {2} | Seats: {3} | Pick up: {4} | Drop off: {5}".format(row[0], row[1], row[3], row[4], row[5], row[6])) if (page_num*5+5 < len(rows)): user_input = input("To delete a booking, please enter the booking number. To see more bookings enter (y/n): ") if (user_input == 'y'): self.display_page(page_num+1, rows, valid_bno) return else: print() user_input = input("To cancel a booking, please enter the booking number: ") if user_input.isdigit() and int(user_input) in valid_bno: print("Canceled the following booking with bno: " + user_input) self.cancel_booking(user_input) else: print("Invalid number entered")
true
3735f2e08803537b4f8c1ba5fa4ad92e6109e16b
Jacalin/Algorithms
/Python/hash_pyramid.py
661
4.5
4
''' Implement a program that prints out a double half-pyramid of a specified height, per the below. The num must be between 1 - 23. Height: 4 # # ## ## ### ### #### #### ''' def hash_pyramid(): # request user input, must be num bewtween 1 - 23 n = int(input("please type in a number between 1 - 23: ")) # check if num is in bounds if n > 23 or n < 1: n = int(input("please type in a number between 1 - 23: ")) # if num in bounds, loop through usernum(n), and print properly formated pyramid. else: for i in range(1,n+1): print (((" " * ((n - (i-1)) - 1)) + ("#" * i) ) , " " , ("#" * i) )
true
31fc3087cab6005638007c911291d6c23ae293ee
kyledavv/lpthw
/ex24.py
1,725
4.125
4
print("Let's practice everything.") print('You\'d need to know \'bout escapes with \\ that do:') print('\n newlines and \t tabs.') poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print("--------") print(poem) print("--------") five = 10 - 2 + 3 - 6 print(f"This should be five: {five}") def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 1000 beans, jars, crates = secret_formula(start_point) #remember that this is another way to format a string print("With a starting point of: {}".format(start_point)) #it's just like with an f"" string print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.") start_point = start_point / 10 print("We can also do that this way:") formula = secret_formula(start_point) #this is an easy way to apply a list to a format string print("We'd have {} beans, {} jars, and {} crates.".format(*formula)) print("Now to practice with my work schedule and payment per week.") chad = 65 * 3 jacinda = 65 raina = 65 * 2 jrs = 25 * 12 syd = 65 payment = chad + jacinda + raina + jrs + syd print("\tThis is the gross amount that I earn from my private lessons and juniors.") print("===>", payment) print("This is the payment after the percentage is taken out.") actual_pmt = payment * .65 print("\t====>", actual_pmt) lost_pmt = payment - actual_pmt print(f"This is the amount I lost from the percentage taken out: {lost_pmt}") print("Country Club's really get you with what they take out. \n:-(")
true
aa673ad99e3adc6a02d9e49a1c7d6b9d82ad2d2d
rawswift/python-collections
/tuple/cli-basic-tuple.py
467
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # create tuple a = ("one", "two", "three") # print 'em print a # how many node/element we have? print len(a) # 3 # print using format print "Counting %s, %s, %s..." % a # iterate for x in a: print x # print value from specific index print a[1] # 'two' # create another tuple (using previous tuple) b = (a, "four") print b[1] # 'four' print b[0][2] # 'three' # how many node/element we have? print len(b) # 2
true
05dbf2f6923071eccad18dc65d97a3e0baab3333
schlangens/Python_Shopping_List
/shopping_list.py
632
4.375
4
# MAKE sure to run this as python3 - input function can cause issues - Read the comments # make a list to hold onto our items shopping_list = [] # print out instruction on how to use the app print('What should we get at the store?') print("Enter 'DONE' to stop adding items.") while True: # ask for new items # if using python 2 change this to raw_input() new_item = input("Item: ") # be able to quit the app if new_item == 'DONE': break # add new items to our list shopping_list.append(new_item) # print out the list print("Here's your list:") for item in shopping_list: print(item)
true
ed5c9669052efef4d7003952c0a7f20437c5109d
alma-frankenstein/Rosalind
/RNA.py
284
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Transcribing DNA to RNA #Given: A DNA string t #Return: The transcribed RNA string of t . filename = 'rosalind_rna.txt' with open(filename) as file_object: contents = file_object.read() rna = contents.replace('T', 'U') print(rna)
true
6a8203f812ccc5b829b20e7698246d8c327ac3af
dudejadeep3/python
/Tutorial_Freecodecamp/11_conditionals.py
530
4.34375
4
# if statement is_male = True is_tall = False if is_male and is_tall: print("You are a tall male.") elif is_male and not is_tall: print("You are a short male") elif not is_male and is_tall: print("You are not a male but tall") else: print("You are not male and not tall") def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num3: return num2 else: return num3 print(max_num(4,1,10)) # we can compare strings also == is used for equal
true
dbfd05d60911bf8141c1bf910cad8229915e420a
dudejadeep3/python
/Tutorial_Freecodecamp/06_input.py
467
4.25
4
# Getting the input from the users name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + "! You are "+age) # Building a basic calculator num1 = input("Enter a number:") num2 = input("Enter another number:") result = float(num1) + float(num2); # we could use int() but it will remove decimal points print(result); # if we int() and pass number with decimal then we will get # an error and program will stop. # result = int(5.5)
true
cf717c597321786c758d22056fd1c90eb8d4b175
lima-oscar/GTx-CS1301xIV-Computing-in-Python-IV-Objects-Algorithms
/Chapter 5.1_Objects/Burrito5.py
1,764
4.46875
4
#In this exercise, you won't edit any of your code from the #Burrito class. Instead, you're just going to write a #function to use instances of the Burrito class. You don't #actually have to copy/paste your previous code here if you #don't want to, although you'll need to if you want to write #some test code at the bottom. # #Write a function called total_cost. total_cost should take #as input a list of instances of Burrito, and return the #total cost of all those burritos together as a float. # #Hint: Don't reinvent the wheel. Use the work that you've #already done. The function can be written in only five #lines, including the function declaration. # #Hint 2: The exercise here is to write a function, not a #method. That means this function should *not* be part of #the Burrito class. #If you'd like to use the test code, paste your previous #code here. #Write your new function here. def total_cost(burrito_list): total_cost = 0 for burrito_n in burrito_list: total_cost += burrito_n.get_cost() return total_cost #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. Note that these lines #will ONLY work if you copy/paste your Burrito, Meat, #Beans, and Rice classes in. # #If your function works correctly, this will originally #print: 28.0 #burrito_1 = Burrito("tofu", True, "white", "black") #burrito_2 = Burrito("steak", True, "white", "pinto", extra_meat = True) #burrito_3 = Burrito("pork", True, "brown", "black", guacamole = True) #burrito_4 = Burrito("chicken", True, "brown", "pinto", extra_meat = True, guacamole = True) #burrito_list = [burrito_1, burrito_2, burrito_3, burrito_4] #print(total_cost(burrito_list))
true
09c67cc5a452e5af7021221d589c49e17f37d7b6
panhboth111/AI-CODES
/pandas/4.py
394
4.34375
4
#Question: Write a Pandas program to compare the elements of the two Pandas Series. import pandas as pd ds1 = pd.Series([2, 4, 6, 8, 10]) ds2 = pd.Series([1, 3, 5, 7, 10]) print("Series1:") print(ds1) print("Series2:") print(ds2) print("Compare the elements of the said Series:") print("Equals:") print(ds1 == ds2) print("Greater than:") print(ds1 > ds2) print("Less than:") print(ds1 < ds2) #
true
2bf7cbe5bcecf17ebaf46be2f5420ebbde0163b0
panhboth111/AI-CODES
/pandas/16.py
530
4.28125
4
"""Question: Write a Pandas program to get the items of a given series not present in another given series. Sample Output: Original Series: sr1: 0 1 1 2 2 3 3 4 4 5 dtype: int64 sr2: 0 2 1 4 2 6 3 8 4 10 dtype: int64 Items of sr1 not present in sr2: 0 1 2 3 4 5 dtype: int64 """ import pandas as pd sr1 = pd.Series([1, 7, 3, 4, 5]) sr2 = pd.Series([2, 4, 6, 8, 10]) print("Original Series:") print("sr1:") print(sr1) print("sr2:") print(sr2) print("\nItems of sr1 not present in sr2:") result = sr1[~sr1.isin(sr2)] print(result)
true
e133ba7d9f305a476985d6d2659aefb7b91ddb51
MariinoS/projectEuler
/problem1.py
571
4.125
4
# Project Euler: Problem 1 Source Code. By MariinoS. 5th Feb 2016. """ # task: If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # # My Solution: """ list = range(1000) def sum_of_multiples(input): total = 0 for i in input: if i % 3 == 0 or i % 5 == 0: total = total + i return total print sum_of_multiples(list) """ # The script finishes in O.O37s. # The answer = 233168 """
true
2834050573db40f828573a3a5e88137c4851382e
P-RASHMI/Python-programs
/Functional pgms/QuadraticRoots.py
979
4.3125
4
''' @Author: Rashmi @Date: 2021-09-17 19:10:01 @Last Modified by: Rashmi @Last Modified time: 2021-09-17 19:36:03 @Title : A program that takes a,d,c from quadratic equation and print the roots” ''' import math def deriveroots(a,b,c): """to calculate roots of quadratic equation parameter : a,b,c return value : roots""" #To find determinent detrimt = b * b - 4 * a * c sqrt_val = math.sqrt(abs(detrimt)) if detrimt > 0: print("real and different") root1 = (-b + sqrt_val)/(2*a) root2 = (-b - sqrt_val)/(2*a) print("roots are: ", root1 , root2 ) elif detrimt == 0: print("roots are real and same") print("root is", -b /(2*a)) else: print("roots are complex") a = int(input("enter the x* x coefficient")) b = int(input("enter the x coefficient")) c = int(input("enter the constant")) if (a == 0): print("give the corect quadratic equation") else: deriveroots(a,b,c)
true
2af7aa31f51f43d8d4cdaaaf245833f3c215e9cf
P-RASHMI/Python-programs
/Logicalprogram/gambler.py
1,715
4.3125
4
''' @Author: Rashmi @Date: 2021-09-18 23:10 @Last Modified by: Rashmi @Last Modified time: 2021-09-19 2:17 @Title : Simulates a gambler who start with $stake and place fair $1 bets until he/she goes broke (i.e. has no money) or reach $goal. Keeps track of the number of times he/she wins and the number of bets he/she makes. ''' import random def gambler(stake,goal,number): """Description :to calculate wins, loss and percentage of wins,loss parameter : stake,goal,number(amount he had,win amount,bets) printing value : wins loss percentages and wins""" win_count = 0 loss_count = 0 counter = 0 while (stake > 0 and stake < goal and counter < number): try: counter+=1 randum_generated = random.randint(0,1) #if suppose randint(0,1,78) given three parameters generating type error exception if (randum_generated == 1): win_count = win_count + 1 stake = stake + 1 else: loss_count = loss_count + 1 stake = stake - 1 except TypeError as e: print("error found ", e ) #to find type of exception type(e).__name__ percent_win = (win_count/number)*100 percent_loss = 100-percent_win print("Number of wins",win_count) print("win percentage :",percent_win) print("loss percentage :",percent_loss ) print("Number of times betting done",counter) if __name__ == '__main__': stake = int(input("Enter the stake amount :")) goal = int(input("Enter how much money want to win")) number = int(input("Enter number of times he want to get involved in betting")) gambler(stake,goal,number)
true
65d56039fe3688d16aeb6737fbcd105df044155a
pranshulrastogi/karumanchi
/doubleLL.py
2,884
4.40625
4
''' implement double linked list ''' class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class doubleLL: def __init__(self): self.head = None # insertion in double linked list def insert(self,data,pos=-1): assert pos >=-1, "make sure to give valid pos argument" # get the new node new_node = Node(data) # insertion when list is empty if not self.head: if pos > 0: print("list is empty, can't insert node at defined location") else: self.head = new_node else: # insertion when list is not empty # 1. insertion at beginning if pos == 0: new_node.next = self.head self.head = new_node # 2. insertion at middle elif pos > 0: i=0 n=self.head while(i<pos and n.next ): i+=1 n=n.next new_node.next = n new_node.prev = n.prev n.prev.next = new_node n.prev = new_node else: #3. insertion at last (default) n=self.head while(n.next): n=n.next new_node.prev = n n.next = new_node # deletion in double linked list def delete(self,pos=-1): # by default deletes the last node n = self.head # check empty if not n: print("Can't perform delete on empty list!!") return False # deletion of head node if pos==0: n.next.prev = None self.head = n.next n.next = None # deletion at certain position elif pos > 0: i=0 while ( i<=pos and n.next ): i+=1 n=n.next if i<pos: print("not valid positon to delete") return False n.prev.next = n.next n.next.prev = n.prev n.next = None else: while(n.next): n = n.next n.prev.next = None n.prev = None # display def printLL(self): n = self.head while(n.next): print(n.data,end=' <-> ') n = n.next print(n.data) # driver if __name__ == '__main__': #insert in dll dll = doubleLL() for i in range(2,33,2): dll.insert(i) dll.printLL() print("inserting at 0") dll.insert(1,0) dll.printLL() print("inserting at 2") dll.insert(3,2) dll.printLL() print("inserting at last") dll.insert(34) dll.printLL()
true
0765b7bc193f7bc799aa0b713b32b9c97ce7b3eb
maheshganee/python-data
/13file operation.py
2,798
4.65625
5
""" file operation:python comes with an inbuilt open method which is used to work with text files //the text files can operated in three operation modes they are read write append //open method takes atleast one parameter and atmost two parameters //first parameter represents the file name along with full path and second parameter represents operation modes //operation modes represents with single carrcter they are r for read w for write a for append //open method returns a file pointer object which contains file name and operation mode details read operation mode-------use second parameter r to open the the file in read operation mode //when a file opened in read mode we can only perform read operations so read operation will applicable only when the file exit syntax-----open('file name,'mode) ex------fp = open('data.txt','r') read functions 1 read 2 readline 3 readlines read----this method will return the file data in a string format //this method takes atmost one parameter that is index position //the default value of index position is always length of the file syntax-----fp.read(index position) note ------all the read operation function will cause a shifting of file pointer courser to reset the file pointer courser we can use seek method seek------this method takes exactly one parameter that is index position to reset syntax-----fp.seek(index position) readline-------this method will return one line of the file at a time //this method takes atmost one parameter that is index position and default value is first line of file syntax-----fp.readline(index position) readlines--------this method will return list of lines in given files //no parameters required //output is always list syntax-----fp.readlines() 2.write operation mode------use w as second parameter in open function to work with the files in write operation //w o m will always creates new file with given name //in write operation mode we can use two functions they are write writelines write-------this method is used to write one string into the given file //write method take exactly one parameter that is one string syntax-----fp.write() writelines-------this method is used to add multipule strings to given file //this method takes exactly one parameter list r tuple syntax-----fp.writelines() 3.append operation mode-------use a as second parameter in open function to work with the files in append o m //to work with a o m the file should exit in the system //we can perform two functions in a o m which are similar to write operation mode they are write writelines rb --------read + binary(read + append) rb+---------read + append/write wb----------write +read wb+---------write+raed+append """ fp = open('/home/mahesh/Desktop/data.txt','w') fp.write('hi')
true
1e171d3183670dd0bac6ab179a3b7c13c42f834c
rronakk/python_execises
/day.py
2,705
4.5
4
print "Enter Your birth date in following format : yyyy/mm/dd " birthDate = raw_input('>') print" Enter current date in following format : yyyy/mm/dd " currentDate = raw_input('>') birth_year, birth_month, birth_day = birthDate.split("/") current_year, current_month, current_day = currentDate.split("/") year1 = int(birth_year) month1 = int(birth_month) day1 = int(birth_day) year2 = int(current_year) month2 = int(current_month) day2 = int(current_day) def daysBetweenDates(year1, month1, day1, year2, month2, day2): # Counts total number of days between given dates days = 0 assert(dayBeforeNext(year1, month1, day1, year2, month2, day2) > 0) while (dayBeforeNext(year1, month1, day1, year2, month2, day2)): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days def nextDay(year, month, day): # Helper function to return the year, month, day of the next day. if (day < daysInMonth(month, year)): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def dayBeforeNext(year1, month1, day1, year2, month2, day2): # Validates if user has not entered future date before past date if (year1 < year2): dbn = True elif(year1 == year2): if(month1 < month2): dbn = True elif(month1 == month2): if(day1 < day2): dbn = True else: dbn = False else: dbn = False else: dbn = False return dbn def daysInMonth(month, year): # Calculate days in a given month and year # Algorithm used for reference : http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month if (month == 2): days = 28 + isLeapYear(year) else: days = 31 - (month - 1) % 7 % 2 return days def isLeapYear(year): # Determine if give year is lear year or not. # Algorithm used for reference : http://www.dispersiondesign.com/articles/time/determining_leap_years """ if ((year % 4 == 0) or ((year % 100 == 0) and (year % 400 == 0))): leapYear = 1 else: leapYear = 0 return leapYear """ if (year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): leapYear = 1 else: leapYear = 0 else: leapYear = 1 else: leapYear = 0 return leapYear print "=============================================================== \n Your age in days is : %d " % daysBetweenDates(birth_year, birth_month, birth_day, current_year, current_month, current_day)
true
f9baac6271366884fbb8caaf201ccb6b4e53e254
sunilmummadi/Trees-3
/symmetricTree.py
1,608
4.21875
4
# Leetcode 101. Symmetric Tree # Time Complexity : O(n) where n is the number of the nodes in the tree # Space Complexity : O(h) where h is the height of the tree # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Approach: To check for symmetry of a tree, check if the extremes of a sub tree i.e. left child of # left subtree and right child of right subtree are same. And if middle elements i.e. right child of # left subtree and left child of right subtree are same. If the condition is not satisfied at any node # then the tree is not symmetric. If the entire tree can be recurrsively verified for this condition then # the tree is symmetric. # Your code here along with comments explaining your approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: # BASE if root == None: return True return self.helper(root.left, root.right) def helper(self, left, right): # Leaf Node if left == None and right == None: return True # Un symmetric if left == None or right == None or left.val != right.val: return False # recurssive call for left and right extremes and # recurssive call for left and right middle elements to check for symmetry return self.helper(left.left, right.right) and self.helper(left.right, right.left)
true
4e1bc4ed86486ee94c63f439d96d7f663df5587c
mcfarland422/python101
/loops.py
277
4.21875
4
print "Loops file" # A for loop expects a starting point, and an ending point. # The ending poin (in range) is non-inclusive, meaning, it will stop when it gets there # i (below) is going to be the number of the loop it's on for i in range(1,10): if (i == 5): print
true
4df919c2b292cf09bf210ea8337023dea1c63bbf
Rosswell/CS_Exercises
/linked_list_manipulation.py
2,673
4.15625
4
'''Prompt: You have simple linked list that specifies paths through a graph. For example; [(node1, node2), (node2, node3)] node 1 connects to node 2 and node 2 connects to node 3. Write a program that traverses the list and breaks any cycles. So if node 1 links to both node 2 and node 2374, one link should be broken and reset. Give the first link formed priority. You can use helper methods .get(index) and .set(index, (new_value)) to get and set new links in the list or write your own ''' '''Explanation: Given the constraints, there are basically two cases that we want to control for: cycles and multiple links. Will be maintaining 2 lists in addition to the original: one to store previously seen values, one to return. 1. Iterate through the list of edges, check if the source node (n1 in (n1, n2)) is already in the seen nodes dict 2. If it's not in the seen nodes dict, add it to the dict and make sure n1's pointer doesn't create a cycle or is the second edge from that node. If those are both true, append the edge to the return list 3. If it is in the dict, check if there is a cycle by comparing to the previous edge. If a cycle is present, append an edge containing (n1, n4), where original two edges were [(n1, n2)(n3, n4)], effectively skipping the node creating the cycle 4. All other cases are skipped, as they are not the original edges from a particular source node ''' from operator import itemgetter class linked_list(object): def __init__(self, edge_list): self.edge_list = edge_list def get(self, index): return self.edge_list[index] def set(self, index, new_value): self.edge_list[index] = new_value return self.edge_list def list_iter(self): ret_list = [] seen_dict = {} for i, edge in enumerate(self.edge_list): node_from, node_to = itemgetter(0, 1)(edge) if node_from not in seen_dict: # new node addition to seen dict seen_dict[node_from] = True if node_to not in seen_dict: # source and destination nodes are unique and create no cycles ret_list.append(edge) else: prev_node_from, prev_node_to = itemgetter(0, 1)(self.edge_list[i-1]) if prev_node_to == node_from: # cycling case - skips the cycled node to preserve path continuity ret_list.append((prev_node_from, node_to)) return sorted(list(set(ret_list))) input_list = [('n1', 'n2'), ('n2', 'n3'), ('n3', 'n1'), ('n1', 'n4'), ('n4', 'n5'), ('n1', 'n123')] x = linked_list(input_list) print(x.list_iter())
true
41585c6dca2b0c40fbdd86fecbedecfa663e306a
Shadow-Arc/Eleusis
/hex-to-dec.py
1,119
4.25
4
#!/usr/bin/python #TSAlvey, 30/09/2019 #This program will take one or two base 16 hexadecimal values, show the decimal #strings and display summations of subtraction, addition and XOR. # initializing string test_string1 = input("Enter a base 16 Hexadecimal:") test_string2 = input("Enter additional Hexadecimals, else enter 0:") # printing original string print("The original string 1: " + str(test_string1)) print("The original string 2: " + str(test_string2)) # using int() # converting hexadecimal string to decimal res1 = int(test_string1, 16) res2 = int(test_string2, 16) # print result print("The decimal number of hexadecimal string 1 : " + str(res1)) print("The decimal number of hexadecimal string 1 : " + str(res2)) basehex = test_string1 sechex = test_string2 basehexin = int(basehex, 16) sechexin = int(sechex, 16) sum1 = basehexin - sechexin sum2 = basehexin + sechexin sum3 = basehexin ^ sechexin print("Hexidecimal string 1 subtracted from string 2:" + hex(sum1)) print("Hexidecimal string 1 added to string 2:" + hex(sum2)) print("Hexidecimal string 1 XOR to string 2:" + hex(sum3))
true
50d3d8fe9a65b183a05d23919c255b71378c7af5
alejandrox1/CS
/documentation/sphinx/intro/triangle-project/trianglelib/shape.py
2,095
4.6875
5
"""Use the triangle class to represent triangles.""" from math import sqrt class Triangle(object): """A triangle is a three-sided polygon.""" def __init__(self, a, b, c): """Create a triangle with sides of lengths `a`, `b`, and `c`. Raises `ValueError` if the three length values provided cannot actually form a triangle. """ self.a, self.b, self.c = float(a), float(b), float(c) if any( s <= 0 for s in (a, b, c) ): raise ValueError('side lengths must all be positive') if any( a >= b + c for a, b, c in self._rotations() ): raise ValueError('one side is too long to make a triangle') def _rotations(self): """Return each of the three ways of rotating our sides.""" return ((self.a, self.b, self.c), (self.c, self.a, self.b), (self.b, self.c, self.a)) def __eq__(self, other): """Return whether this triangle equals another triangle.""" sides = (self.a, self.b, self.c) return any( sides == rotation for rotation in other._rotations() ) def is_similar(self, triangle): """Return whether this triangle is similar to another triangle.""" return any( (self.a / a == self.b / b == self.c / c) for a, b, c in triangle._rotations() ) def is_equilateral(self): """Return whether this triangle is equilateral.""" return self.a == self.b == self.c def is_isosceles(self): """Return whether this triangle is isoceles.""" return any( a == b for a, b, c, in self._rotations() ) def perimeter(self): """Return the perimeter of this triangle.""" return self.a + self.b + self.c def area(self): """Return the area of this triangle.""" s = self.perimeter() / 2.0 return sqrt(s * (s - self.a) * (s - self.b) * (s - self.c)) def scale(self, factor): """Return a new triangle, `factor` times the size of this one.""" return Triangle(self.a * factor, self.b * factor, self.c * factor)
true
5e4c5593c59e8218630172dd9690da00c7d8fc1c
CostaNathan/ProjectsFCC
/Python 101/While and for loops.py
1,090
4.46875
4
## while specify a condition that will be run repeatedly until the false condition ## while loops always checks the condition prior to running the loop i = 1 while i <= 10: print(i) i += 1 print("Done with loop") ## for variable 'in' collection to look over: ## the defined variable will change each iteration of the loop for letter in "Giraffe academy": print(letter) ## the loop will print each letter individualy for the defined variable ## letter will correspond to the first, than the second, than ... each iteration friends = ["Jim", "Karen", "Jorge"] for name in friends: print(name) for index in range(10): print(index) ## range() = will count up to the design value, but without it ## in the above example, index will correspond to 0,1,2,...,9 for each iteration for index in range(3,10): print(index) ## an example of for loop to loop through an array for index in range(len(friends)): print(friends[index]) for index in range(5): if index == 0: print("Begin iteration!") elif index == 4: print("Iteration complete!")
true
959aae8e60bcc42ea90447dc296262c791e18d8c
CostaNathan/ProjectsFCC
/Python 101/Try & Except.py
298
4.21875
4
## try/except blocks are used to respond to the user something when an error occur ## best practice to use except with specific errors try: number = int(input("Enter a number: ")) print(number) except ZeroDivisionError as err: print(err) except ValueError: input("Invalid input")
true
df3955f45591745ac7c20b87d71d01a16f774cf1
OlivierParpaillon/Contest
/code_and_algo/Xmas.py
1,504
4.21875
4
# -*- coding:utf-8 -* """ Contest project 1 : Christmas Tree part.1 Olivier PARPAILLON Iliass RAMI 17/12/2020 python 3.7.7 """ # Python program to generate branch christmas tree. We split the tree in 3 branches. # We generate the first branch of the christmas tree : branch1. # We will use the same variables for the whole code : only values will change. # nb_blank represents the number of blanks between the "*" ; # star_top represents the number of "*" on the top of the tree ; # and nb_branch defines the number of times we repeat the operation. def branch1(): nb_blank = 15 star_top = 1 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 1 star_top += 2 # We generate the middle branch of the christmas tree. # Same variables but we add 4 to star_top and we remove 2 from nb_blank def branch2(): nb_blank = 14 star_top = 3 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 2 star_top += 4 # We generate the last branch of the christmas tree. # We use the same variables but we remove 3 from nb_blank and we add 6 to star_top def branch3(): nb_blank = 13 star_top = 5 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 3 star_top += 6 # Main function to start the program. def main(): branch1(), branch2(), branch3() main()
true
23bd8f9abc8622a7fba3ec85097241eacd9f3713
DLLJ0711/friday_assignments
/fizz_buzz.py
1,486
4.21875
4
# Small: add_func(1, 2) --> outputs: __ # More Complex: add_func(500, 999) --> outputs: __ # Edge Cases: add_func() or add_func(null) or add_func(undefined) --> outputs: ___ # Take a user's input for a number, and then print out all of the numbers from 1 to that number. #startFrom = int(input('Start From (1-10): ')) not needed #x = 1 # endOn = int(input('End On (any number): ')) # while(x <= endOn): # print(x) # x +=1 # For any number divisible by 3, print 'fizz' # for i in range(lower, upper+1): # if((i%3==0): # print(i) # For any number divisible by 5, print 'buzz' # for i in range(lower, upper+1): # (i%5==0)): # print(i) # For any number divisible by 3 and 5, print 'fizzbuzz' # for i in range(lower, upper+1): # if((i%3==0) & (i%5==0)): # print(i) #print 1 to user's input NOT NEEDED # while(x <= endOn): # print(x) # x += 1 # HAD TO COMBINE CODE AND REPLACE SYNTAX AND ORDER OF EVALUATION #Starting range x = 1 #user's input endOn = int(input('End On (any number): ')) #for loop and if statment for x in range(x, endOn +1): if x % 3 == 0 and x % 5 == 0: print('fizzbuzz') elif x % 3 == 0: print("fizz") elif x % 5 == 0: print("buzz") else: print(x) #had continue after each statement replaced with else to end.
true
27908f6c8668a493e416fc1857ac8fa49e7bb255
s3rvac/talks
/2017-03-07-Introduction-to-Python/examples/22-point.py
353
4.25
4
from math import sqrt class Point: """Representation of a point in 2D space.""" def __init__(self, x, y): self.x = x self.y = y def distance(self, other): return sqrt((other.x - self.x) ** 2 + (other.y - self.y) ** 2) a = Point(1, 2) b = Point(3, 4) print(a.distance(b)) # 2.8284271247461903
true
7baaca13abcd7fc98fd5d9b78de0bc62557f4b83
s3rvac/talks
/2020-03-26-Python-Object-Model/examples/dynamic-layout.py
666
4.34375
4
# Object in Python do not have a fixed layout. class X: def __init__(self, a): self.a = a x = X(1) print(x.a) # 1 # For example, we can add new attributes to objects: x.b = 5 print(x.b) # 5 # Or even new methods into a class: X.foo = lambda self: 10 print(x.foo()) # 10 # Or even changing base classes during runtime (this is just for illustration, # I do not recommend doing this in practice): class A: def foo(self): return 1 class B(A): pass class C: def foo(self): return 2 b = B() print(b.foo(), B.__bases__) # 1 (<class '__main__.A'>,) B.__bases__ = (C,) print(b.foo(), B.__bases__) # 2 (<class '__main__.C'>,)
true
42b39efbe438ae62a818b8487aedeb5d71d4cf58
lafleur82/python
/Final/do_math.py
1,022
4.3125
4
import random def do_math(): """Using the random module, create a program that, first, generates two positive one-digit numbers and then displays a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”. Ensure your program conducts error-checking on the answer and notifies the user whether the answer is correct or not.""" a = random.randint(1, 9) b = random.randint(1, 9) op = random.randint(1, 3) answer = 0 if op == 1: print("What is", a, "+", b, "?") answer = a + b elif op == 2: print("What is", a, "-", b, "?") answer = a - b elif op == 3: print("What is", a, "*", b, "?") answer = a * b user_input = float(input()) if user_input == answer: print("Correct!") else: print("Incorrect.") if __name__ == '__main__': while True: do_math() print("Another? (y/n)") user_input = input() if user_input != 'y': break
true
074f936e918b85a0b3ed669bb60f0d02d7a790db
daniel-reich/ubiquitous-fiesta
/PLdJr4S9LoKHHjDJC_22.py
909
4.3125
4
# 1-> find if cube is full or not, by checking len of cube vs len of current row. ​ # 2-> calculate the missing parts in current row, by deducting the longest len of row vs current row. ​ # 3-> if we have missing parts return it. ​ # 4-> if we don't have missing parts, but our len of cube is smaller than our longest row. then that means we have a non-full cube. ​ def identify(*cube): totalMissingParts = 0 for row in range(len(cube)): maxLengthOfaRow = len(max([i for i in cube])) # Non-Full is True if len(cube) < maxLengthOfaRow or len(cube[row]) < maxLengthOfaRow: currentMissingParts = maxLengthOfaRow - len(cube[row]) totalMissingParts += currentMissingParts if totalMissingParts: return "Missing {}".format(totalMissingParts) else: if len(cube) < maxLengthOfaRow and not totalMissingParts: return "Non-Full" else: return "Full"
true
2950192f84c4b16ace89e832e95300b7b58db078
daniel-reich/ubiquitous-fiesta
/ZdnwC3PsXPQTdTiKf_6.py
241
4.21875
4
def calculator(num1, operator, num2): if operator=='+': return num1+num2 if operator=='-': return num1-num2 if operator=='*': return num1*num2 if operator=='/': return "Can't divide by 0!" if num2==0 else num1/num2
true
7e8131e9fa9aaf0b419635a8f06519d48571a49d
daniel-reich/ubiquitous-fiesta
/ZwmfET5azpvBTWoQT_9.py
245
4.1875
4
def valid_word_nest(word, nest): while True: if word not in nest and nest != '' or nest.count(word) == 2: return False nest = nest.replace(word,'') if word == nest or nest == '': return True
true
b7b5dc1ec31ac738b6ed4ef5f0bf7d383bc54fb2
daniel-reich/ubiquitous-fiesta
/MvtxpxtFDrzEtA9k5_13.py
496
4.15625
4
def palindrome_descendant(n): ''' Returns True if the digits in n or its descendants down to 2 digits derived as above are. ''' str_n = str(n) if str_n == str_n[::-1] and len(str_n) != 1: return True ​ if len(str_n) % 2 == 1: return False # Cannot produce a full set of pairs ​ return palindrome_descendant(int(''.join(str(int(str_n[i]) + int(str_n[i+1])) \ for i in range(0, len(str_n), 2))))
true
b2cea9d9a6e9442f4ff3877a211ea24b8072d821
daniel-reich/ubiquitous-fiesta
/hzs9hZXpgYdGM3iwB_18.py
244
4.15625
4
def alternating_caps(txt): result, toggle = '', True for letter in txt: if not letter.isalpha(): result += letter continue result += letter.upper() if toggle else letter.lower() toggle = not toggle return result
true
48d9d502b12feb2a2c6c637cc5050d353a6e45d0
daniel-reich/ubiquitous-fiesta
/tgd8bCn8QtrqL4sdy_2.py
776
4.15625
4
def minesweeper(grid): ''' Returns updated grid to show how many mines surround any '?' cells, as per the instructions. ''' def mines(grid, i, j): ''' Returns a count of mines surrounding grid[i][j] where a mine is identified as a '#' ''' count = 0 locs = ((i-1,j-1), (i-1,j), (i-1,j+1),(i,j-1), (i,j+1), (i+1,j-1), (i+1,j), (i+1,j+1)) # possible neighbours ​ for r, c in locs: if 0 <= r < len(grid) and 0 <= c < len(grid[0]): if grid[r][c] == '#': count += 1 ​ return str(count) ​ return [[mines(grid,i,j) if grid[i][j] == '?' else grid[i][j] \ for j in range(len(grid[0]))] for i in range(len(grid))]
true
17608253348421e9e8efeceef37697702b9e49b2
daniel-reich/ubiquitous-fiesta
/FSRLWWcvPRRdnuDpv_1.py
1,371
4.25
4
def time_to_eat(current_time): #Converted hours to minutes to make comparison easier breakfast = 420; lunch = 720; dinner = 1140; full_day = 1440; #Determines if it's morning or night morning = True; if (current_time.find('p.m') != -1): morning = False; #Splits the time from the A.M/P.M Callout num_time = current_time.split(' '); #Splits hours and minutes hours_minutes = num_time[0].split(':',1); #Converts hours to minutes and adds 12 hours if afternoon if (morning == False): hours = (int(hours_minutes[0]) + 12) * 60; elif (morning == True and int(hours_minutes[0]) == 12): hours = 0; else: hours = int(hours_minutes[0]) * 60; ​ #Totals up minutes and hours minutes_total = int(hours_minutes[1]) + hours; print(minutes_total); if (minutes_total < breakfast): diff_minutes = breakfast - minutes_total; elif (minutes_total > breakfast and minutes_total < lunch): diff_minutes = lunch - minutes_total; elif (minutes_total > lunch and minutes_total < dinner): diff_minutes = dinner - minutes_total; else: diff_minutes = full_day - minutes_total + breakfast; #conversion back to list diff_hours = int(diff_minutes / 60); diff_minutes_remain = abs((diff_hours * 60) - diff_minutes); answer = [diff_hours,diff_minutes_remain] return answer
true
f2cb2449e31eac8a7f3001a503cf34bb953440db
daniel-reich/ubiquitous-fiesta
/NNhkGocuPMcryW7GP_6.py
598
4.21875
4
import math ​ def square_areas_difference(r): # Calculate diameter d = r * 2 # Larger square area is the diameter of the incircle squared lgArea = d * d # Use the diameter of the circle as the hypotenuse of the smaller # square when cut in half to find the edges length # When the legs are equal length (because it's a square), you just # divide the hypotenuse by the sqrt of 2 # Smaller square area is the legs squared smLeg = d / math.sqrt(2) smArea = smLeg * smLeg # We then return the difference between the large area and small area return lgArea - round(smArea)
true
2163c89bda23d7bb9c02adc2729b3b678a695785
daniel-reich/ubiquitous-fiesta
/gJSkZgCahFmCmQj3C_21.py
276
4.125
4
def de_nest(lst): l = lst[0] #Define 'l' so a while loop can be used while isinstance(l,list): #repeat until l is not a list l = l[0] #This is a neat little trick in recursion, you can keep diving #into list by just taking the 0 index of itself! return l
true
701687d9659a7c7e4373ed7159096bf1b1f18a85
daniel-reich/ubiquitous-fiesta
/QuxCNBLcGJReCawjz_7.py
696
4.28125
4
def palindrome_type(n): decimal = list(str(n)) == list(str(n))[::-1] # assess whether the number is the same read forward and backward binary = list(str(bin(n)))[2:] == list(str(bin(n)))[2:][::-1] # assess whether the binary form of the number is the same read forward and backward ​ if((decimal) and (binary)): # if both decimal and binary forms of the number are palindromes return "Decimal and binary." ​ if(decimal): # if only the decimal form of the number is a palindrome return "Decimal only." ​ if(binary): # if only the binary form of the number is a palindrome return "Binary only." ​ return "Neither!" # if neither forms of the number are palindromes
true
13a03a6d6d627d8f0c36bb4b295a9b89cd8dd36e
lavakiller123/python-1
/mtable
333
4.125
4
#!/usr/bin/env python3 import colors as c print(c.clear + c.blue + 'Mmmmm, multiplication tables.') print('Which number?') number = input('> ' + c.green) print('table for ' + number) for multiplier in range(1,13): product = int(number) * multiplier form = '{} x {} = {}' print(form.format(number,multiplier,product))
true
177034604e43405fc616b4ea8c4017f96e8bacea
aliasghar33345/Python-Assignment
/Assignment_5/ASSIGNMENT_5.py
2,975
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """ Answer # 1 Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. """ def factorial(n): num = 1 while n > 0: num *= n n -= 1 return num print(factorial(1)) # In[2]: """ Answer # 2 Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. """ def caseCLC(string): uppers = 0 lowers = 0 for char in string: if char.islower(): lowers += 1 elif char.isupper(): uppers += 1 return uppers, lowers print(caseCLC("Hello Ali Asghar! are you ready to be called as Microsoft Certified Python Developer after 14 December?")) # In[3]: """ Answer # 3 Write a Python function to print the even numbers from a given list. """ def evenIndex(nums): li = [] for num in range(0,len(nums)): if nums[num] % 2 == 0: li.append(nums[num]) return li print(evenIndex([114,26,33,5,63,7,445,6,74,64,45.5,102.2,44])) # In[ ]: """ Answer # 4 Write a Python function that checks whether a passed string is palindrome or not. Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam """ def palindromeTEST(word): reverse = ''.join(reversed(word)) if word == reverse and word != "": return "You entered a palindrome." else: return "It is'nt palindrome." check_palindrome = input("Enter any word to test if it is pelindrome: ") print(palindromeTEST(check_palindrome)) # In[ ]: """ Answer # 5 Write a Python function that takes a number as a parameter and check the number is prime or not. """ def isprime(): nums = int(input("Enter any number to check if it is prime or not: ")) return prime(nums) def prime(nums): if nums > 1: for num in range(2,nums): if (nums % num) == 0: print("It is not a prime number.") print(num,"times",nums//num, "is", nums) break else: print("It is a prime number.") isprime() # In[ ]: """ Answer # 6 Suppose a customer is shopping in a market and you need to print all the items which user bought from market. Write a function which accepts the multiple arguments of user shopping list and print all the items which user bought from market. (Hint: Arbitrary Argument concept can make this task ease) """ def boughtITEM(): cart = [] while True: carts = input("\nEnter an item to add it in your cart: \nor Press [ENTER] to finish: \n") if carts == "": break cart.append(carts) item_list = "" for item in range(0,len(cart)): item_list = item_list + cart[item].title() + "\n" print("\nItems you have bought is:\n"+item_list) boughtITEM() # In[ ]:
true
7a5bf78bc03f1008220e365be65e95273686d56f
erik-kvale/HackerRank
/CrackingTheCodingInterview/arrays_left_rotation.py
2,412
4.4375
4
""" ------------------ Problem Statement ------------------ A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. FOr example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. ------------------ Input Format: ------------------ The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d (the number of left rotations you must perform). The second line contains n space-separated integers describing the respective elements of the array's initial state. ------------------ Constraints ------------------ 1 <= n <= 10^5 1 <= d <= n 1 <= a(sub i) <= 10^6 ------------------ Output Format ------------------ Print a single line of n space-separated integers denoting the final state of the after performing d left rotations. ============================ Solution Statement ============================ After reading in the necessary inputs, we need to simulate a left rotation on the array (Python list). For each rotation 'd' we need to pop off the first element of the array and append it at the last-index position of the array, this will simulate a left or counter-clockwise rotation. Visualizing the array as circle with its elements on the face of a clock can be helpful. When I pop off the first element (index=0), I store that value. My array is now length n - first element at which point I append the popped element to the end, effectively causing each element to shift one index to the left from its initial state. """ def array_left_rotation(num_of_elements, elements, num_of_rotations): for rotation in range(num_of_rotations): # O(n) first_element = elements.pop(0) # O(1) elements.append(first_element) # O(1) return elements # O(1) n, d = map(int, input().strip().split()) # O(1) a = list(map(int, input().strip().split())) # O(n) answer = array_left_rotation(n, a, d) # O(n) = O(n) + O(1) + O(1) + O(1) print(*answer, sep=' ') # O(1)
true
756347df8759c2befdb80feabcb255431be085d8
saiyampy/currencyconverter_rs-into-dollars
/main.py
898
4.28125
4
print("Welcome to rupees into dollar and dollar into rupees converter") print("press 1 for rupees into dollar:") print("press 2 for dollar into rupees:") try:#it will try the code choice = int(input("Enter your choice:\n")) except Exception as e:#This will only shown when the above code raises error print("You have entered a string") def dollars_into_rupees(): dollars = int(input("enter the amount of dollar to convert into rupees\n")) dollar_input = dollars*73.85 print(f"{dollars} dollars converted into rupees resulted {dollar_input} rupees") def rs_into_dollar(): op = int(input("enter the amount of rupees to convert into dollar\n")) value = op/73.85 print(f"{op} Rupees converted into dollars resulted {value}$ dollars ") if choice == 1: rs_into_dollar() if choice == 2: dollars_into_rupees() print("Thanks For Using This Code")
true
2d6ceb13782c1aa23f2f1c9dce160b7cb51cb5f3
nguya580/python_fall20_anh
/week_02/week02_submission/week02_exercise_scrapbook.py
2,398
4.15625
4
# %% codecell # Exercise 2 # Print the first 10 natural numbers using a loop # Expected output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 x = 0 while x <= 10: print(x) x += 1 # %% codecell # Exercise 3: # Execute the loop in exercise 1 and print the message Done! after # Expected output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # Done! x = 0 while x <= 10: print(x) x += 1 if x > 10: print("Done!") # %% codecell # Exercise 4: # Print the numbers greater than 150 from the list # list = [12, 15, 47, 63, 78, 101, 157, 178, 189] # Expected output: # 157 # 178 # 189 list = [12, 15, 47, 63, 78, 101, 157, 178, 189] for number in list: if number > 150: print(number) # %% codecell # Exercise 5: # Print the number that is even and less than 150 # list = [12, 15, 47, 63, 78, 101, 157, 178, 189] # Expected output: # 12 # 78 # Hint: if you find a number greater than 150, stop the loop with a break list = [12, 15, 47, 63, 78, 101, 157, 178, 189] for number in list: if number < 150 and number % 2 == 0: print(number) # %% codecell # Exercise 6: # This will be a challenging! # Write a while loop that flips a coin 10 times # Hint: Look into the random library using: # https://docs.python.org/3/library/random.html # https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python import random head_count = [] tail_count = [] def flip_coin(): """this function generates random value 0-1 for coin 1 is head 0 is tail""" coin = random.randrange(2) if coin == 1: print(f"You got a head. Value is {coin}") head_count.append("head") else: print(f"You got a tail. Value is {coin}") tail_count.append("tail") def flip(): """this function generate flipping coin 10 times""" for x in range(10): flip_coin() print(f"\nYou flipped HEAD {len(head_count)} times, and TAIL {len(tail_count)} times.\n") again() def again(): """ask user if they want to flip coint again.""" ask = input("Do you want to flip coint again? \nEnter 'y' to flip, or 'n' to exit.\n") if ask == "y": #clear lists output to remains list length within 10 del head_count[:] del tail_count[:] #run flipping coin again flip() elif ask == "n": print("\nBye bye.") #call function flip()
true
471bb7458f78b94190321bdcbaa0dce295cdb3f9
contactpunit/python_sample_exercises
/ds/ds/mul_table.py
1,088
4.21875
4
class MultiplicationTable: def __init__(self, length): """Create a 2D self._table of (x, y) coordinates and their calculations (form of caching)""" self.length = length self._table = { (i, j): i * j for i in range(1, length + 1) for j in range(1, length + 1) } print(self._table) def __len__(self): """Returns the area of the table (len x* len y)""" return self.length * self.length def __str__(self): return '\n'.join( [ ' | '.join( [ str(self._table[(i, j)]) for j in range(1, self.length + 1) ] ) for i in range(1, self.length + 1) ] ) def calc_cell(self, x, y): """Takes x and y coords and returns the re-calculated result""" try: return self._table[(x, y)] except KeyError as e: raise IndexError() m = MultiplicationTable(3) print(m)
true
c06217c63dd9a7d955ae6f2545773486d84158b0
Iliya-Yeriskin/Learning-Path
/Python/Exercise/Mid Exercise/4.py
266
4.40625
4
''' 4. Write a Python program to accept a filename from the user and print the extension of that. Sample filename : abc.java Output : java ''' file=input("Please enter a file full name: ") type=file.split(".") print("Your file type is: " + repr(type[-1]))
true
0d19a4381c7c94180999bc78613aecdf65cf04a0
Iliya-Yeriskin/Learning-Path
/Python/Projects/Rolling Cubes.py
2,517
4.1875
4
''' Cube project: receive an input of player money every game costs 3₪ every round we will roll 2 cubes, 1.if cubes are the same player wins 100₪ 2.if the cubes are the same and both are "6" player wins 1000₪ 3.if the cubes different but cube 2 = 2 player wins 40₪ 4.if the cubes different but cube 1 = 1 player wins 20₪ in the end we'll print how much money the player won. ''' from random import randint from time import sleep print("Welcome to the Rolling Cube Game\n--------------------------------\nEach round costs 3₪\n") money = input("How much money do you have?: \n") start_money = money turns = int(money)//3 change = int(money) % 3 print("Your Change is: "+str(change)+"₪") print("Prepare to play: "+str(turns)+" Rounds\n-----------------------") money = int(turns)*3 cube1 = 0 cube2 = 0 for i in range(turns): start_money = int(int(start_money)-3) money = int(int(money)-3) print("Round: "+str(i+1)+" Rolling...") sleep(2) cube1 = randint(1, 6) cube2 = randint(1, 6) if cube1 == cube2 & cube1 == 6: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 1000₪!!\n-----------------------") money = money+1000 elif cube1 == cube2: if cube1 == 1: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 120₪\n-----------------------") money = money+120 elif cube2 == 2: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 140₪\n-----------------------") money = money+140 else: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 100₪\n-----------------------") money = money+100 elif cube1 == 1: if cube2 == 2: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 60₪\n-----------------------") money = money+60 else: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 20₪\n-----------------------") money = money+20 elif cube2 == 2: print("You Rolled (" + str(cube1) + "," + str(cube2) + ") And Won 40₪\n-----------------------") money = money+40 else: print("You Rolled ("+str(cube1)+","+str(cube2)+") Sorry you didn't win\n-----------------------") print("Calculating your Prize....\n") sleep(3) print("Your Total winning are: ["+str(money)+"₪]\nNow you have: ["+str(int(start_money)+int(money))+"₪]" + "\nHope to see you again :-)")
true
5736199cbc797c8ae7d2cc6d8fc09da59023d5e2
Iliya-Yeriskin/Learning-Path
/Python/Exercise/Mid Exercise/10.py
306
4.3125
4
''' 10. Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string. Sample string : 'Net4U' Expected output: {'N': 1, 'e': 1, 't': 2, '4': 1, 'U': 1} ''' word=input("Please enter a word: ") dict={i:word.count(i) for i in word} print(dict)
true
03a72365c3d05751de58a9e973736dd925ea6bb2
Stefan1502/Practice-Python
/exercise 13.py
684
4.5
4
#Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. #Take this opportunity to think about how you can use functions. #Make sure to ask the user to enter the number of numbers in the sequence to generate. #(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. #The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) def sum(a): return a[-2] + a[-1] def Fibonnaci(inp): li = [1, 1] for i in range(0, (inp - 2)): li.append(sum(li)) return li inpp = int(input("number pls: ")) print(Fibonnaci(inpp))
true
252901028a8feadeb4070b57ff330d2c2751757c
Stefan1502/Practice-Python
/exercise 9.py
894
4.21875
4
#Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. #(Hint: remember to use the user input lessons from the very first exercise) #Extras: Keep the game going until the user types “exit” Keep track of how many guesses the user has taken, and when the game ends, print this out. import random num = random.randint(1, 9) guess = 10 attempts = 0 while guess != num and guess != "exit": guess = int(input("guess the num: ")) if guess < num: print('too low') attempts += 1 elif guess > num: print('too high') attempts += 1 elif guess == "exit": break elif guess == num: print('you won') print(f'attempts = {attempts}') num = random.randint(1, 9) attempts = 0
true
b831314d05f1b2a996e687d3f43f046ef46eab0d
Stefan1502/Practice-Python
/exercise 28.py
421
4.375
4
# Implement a function that takes as input three variables, and returns the largest of the three. # Do this without using the Python max() function! # The goal of this exercise is to think about some internals that Python normally takes care of for us. # All you need is some variables and if statements! def return_max(x,y,z): li = sorted([x,y,z]) return li[-1] print(return_max(1,156,55))
true
d0fdd8537fc6e96de145f6c409cc166699a51ee1
ericrommel/codenation_python_web
/Week01/Chapter04/Exercises/ex_4-10.py
1,171
4.34375
4
# Extend your program above. Draw five stars, but between each, pick up the pen, move forward by 350 units, turn right # by 144, put the pen down, and draw the next star. You’ll get something like this: # # _images/five_stars.png # # What would it look like if you didn’t pick up the pen? import turtle def make_window(color="lightgreen", title="Exercise"): win = turtle.Screen() win.bgcolor(color) win.title(title) return win def make_turtle(pensize=3, color="blue"): a_turtle = turtle.Turtle() a_turtle.color(color) a_turtle.pensize(pensize) return a_turtle def draw_star(a_turtle, side=100): for i in range(5): a_turtle.right(144) a_turtle.forward(side) wn = make_window(title="Exercise 9") star = make_turtle() star.penup() star.setposition(-250, 0) star.pendown() star.speed(0) for j in range(5): draw_star(star) star.penup() star.forward(500) star.right(144) star.pendown() star2 = make_turtle(color="red") star2.penup() star2.setposition(-100, 0) star2.pendown() star2.speed(0) for j in range(5): draw_star(star2) star2.forward(150) star2.right(144) wn.mainloop()
true
7fcd55b167623ad4139ebe7d9eab75f958c78fb2
ericrommel/codenation_python_web
/Week01/Chapter04/Exercises/ex_4-09.py
694
4.53125
5
# Write a void function to draw a star, where the length of each side is 100 units. (Hint: You should turn the turtle # by 144 degrees at each point.) # # _images/star.png import turtle def make_window(color="lightgreen", title="Exercise"): win = turtle.Screen() win.bgcolor(color) win.title(title) return win def make_turtle(pensize=3, color="blue"): a_turtle = turtle.Turtle() a_turtle.color(color) a_turtle.pensize(pensize) return a_turtle def draw_star(a_turtle, side=100): for i in range(5): a_turtle.right(144) a_turtle.forward(side) wn = make_window(title="Exercise 9") star = make_turtle() draw_star(star) wn.mainloop()
true
f4aeba34d229b94abb230c2d9607b8f39570fede
ericrommel/codenation_python_web
/Week01/Chapter03/Exercises/ex_3-06.py
871
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 wn = turtle.Screen() wn.bgcolor("lightgreen") wn.title("Exercise 6") triangle = turtle.Turtle() triangle.color("hotpink") triangle.pensize(3) for i in range(3): triangle.forward(80) triangle.left(120) square = turtle.Turtle() square.color("hotpink") square.pensize(4) for i in range(4): square.forward(80) square.left(90) hexagon = turtle.Turtle() hexagon.color("hotpink") hexagon.pensize(6) for i in range(6): hexagon.forward(80) hexagon.left(60) octagon = turtle.Turtle() octagon.color("hotpink") octagon.pensize(8) for i in range(8): octagon.forward(80) octagon.left(45) wn.mainloop()
true
bd0d86565d9a8380c8ede6fc6a36249d4b134ffb
arabindamahato/personal_python_program
/risagrud/function/actual_argument/default_argument.py
690
4.5625
5
''' In default argument the function contain already a arguments. if we give any veriable at the time of function calling then it takes explicitely . If we dont give any arguments then the function receives the default arguments''' '''Sometimes we can provide default values for our positional arguments. ''' def wish(name='Guest'): print('hello {}'.format(name)) print('hello {}'.format(name)) wish('Arabinda') ''' This below code is not right because " After default arguments we should not take non default arguments"''' # def wish(name='Guest', ph_no): # print('hello {} {}'.format(name, ph_no)) # print('hello {} {}'.format(name, ph_no)) # wish('Arabinda','ph_no')
true
90aba704a0cf75e1359c3585d1986dbb7a5b826d
arabindamahato/personal_python_program
/programming_class_akshaysir/find_last_digit.py
353
4.28125
4
print('To find the last digit of any number') n=int(input('Enter your no : ')) o=n%10 print('The last digit of {} is {}'.format(n,o)) #To find last digit of a given no without using modulas and arithmatic operator print('To find last digit of a given no') n=(input('Enter your no : ')) o=n[-1] p=int(o) print('The last digit of {} is {}'.format(n,p))
true