blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
cb48aff62616fd3fe4888d6a4fde3aef185d99c1
pancakewaffles/Stuff-I-learnt
/Python Refresher/Python Math/1 Numbers, Fractions, Complex, Factors, Roots, Unit Conversion/quadraticRootsCalc.py
517
4.15625
4
#! quadraticRootCalc.py # Finds roots of quadratic equations, including even complex roots! def roots(a,b,c): # a,b,c are the coefficients D = (b*b - 4*a*c)**0.5; x_1 = (-b+D)/(2*a); x_2 = (-b-D)/(2*a); print("x1: {0}".format(x_1)); print("x2: {0}".format(x_2)); #print("x1: %f"%(x_1)); Doesn't work for complex #print("x2: %f"%(x_2)); if(__name__=="__main__"): a = input("Enter a: "); b = input("Enter b: "); c = input("Enter c: "); roots(float(a),float(b),float(c));
true
4e8a52d1b2563727ac655e2c84ad0b80af626e29
fpert041/experiments_in_ML_17
/LB_02_TestEx.py
1,274
4.21875
4
#PRESS <Ctrl>+<Enter> to execute this cell #%matplotlib inline #In this cell, we load the iris/flower dataset we talked about in class from sklearn import datasets import matplotlib.pyplot as plt iris = datasets.load_iris() # view a description of the dataset print(iris.DESCR) %matplotlib inline #above: directive to plot inline #PRESS <Ctrl>+<Enter> to execute this cell #This populates info regarding the dataset. Amongst others, we can see that the 'features' used are sepal length and width and petal length and width #Lets plot sepal length against sepal width, using the target labels (which flower) X=iris.data Y=iris.target plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) #first two features are sepal length and sepal width plt.show() %matplotlib inline #here's also how to plot in 3d: from mpl_toolkits.mplot3d import Axes3D # #create a new figure fig = plt.figure(figsize=(5,5)) #this creates a 1x1 grid (just one figure), and now we are plotting subfigure 1 (this is what 111 means) ax = fig.add_subplot(111, projection='3d') #plot first three features in a 3d Plot. Using : means that we take all elements in the correspond array dimension ax.scatter(X[:, 0], X[:, 1], X[:, 2],c=Y)
true
1adb144238abf3ad518e644c680a44e7b66cca15
ianjosephjones/Python-Pc-Professor
/8_11_21_Python_Classs/Exercise_5-11.py
723
4.5625
5
""" 5-11: Ordinal Numbers --------------------- Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3. Store the numbers 1 through 9 in a list. Loop through the list. Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th" , and each result should be on a separate line. """ numbers = list(range(1, 10)) for number in numbers: if number == 1: print("1st") elif number == 2: print("2nd") elif number == 3: print("3rd") else: print(f"{number}th") """ Output: ------- 1st 2nd 3rd 4th 5th 6th 7th 8th 9th """
true
15a517a5443e03e322d9c2fbfcdbb31c9418cf25
awesomeleoding1995/Python_Learning_Process
/python_crash_course/chapter-9/user.py
1,773
4.125
4
class User(): """this class is used to create user-related profile""" def __init__(self, first_name, last_name): self.f_name = first_name self.l_name = last_name self.login_attempts = 0 def describe_user(self): formatted_name = self.f_name + " " + self.l_name return formatted_name.title() def greet_user(self): print("Thanks for logging in!") def increment_login_attempts(self): self.login_attempts += 1 def rest_login_attempts(self): self.login_attempts = 0 class Admin(User): """ This is a child class of User""" def __init__(self, first_name, last_name): """initialise parent class""" super().__init__(first_name, last_name) self.privilege = Privileges() class Privileges(): """describe tha attribute of admin""" def __init__( self, privileges = [ 'can add post', 'can delete post', 'can ban user', 'can manage post' ] ): self.privileges = privileges def show_privileges(self): for privilege in self.privileges: print("\nYou " + privilege) admin = Admin('eggy', 'zhang') admin_name = admin.describe_user() print("Welcome " + admin_name) admin.privilege.show_privileges() admin.greet_user() # user_1 = User('william', 'wu') # user_2 = User('gerard', 'bai') # user_3 = User('eggy', 'zhang') # user_1_name = user_1.describe_user() # print("\nWelcome " + user_1_name) # user_1.greet_user() # # counter = 0 # for counter in range(0, 5): # user_1.increment_login_attempts() # print(str(user_1.login_attempts)) # counter += 1 # user_1.rest_login_attempts() # print(str(user_1.login_attempts)) # user_2_name = user_2.describe_user() # print("\nWelcome " + user_2_name) # user_2.greet_user() # user_3_name = user_3.describe_user() # print("\nWelcome " + user_3_name) # user_3.greet_user()
true
27dc85dad52a603c8df7ca93ef2f35da27ed262d
danielvillanoh/conditionals
/secondary.py
2,425
4.59375
5
# author: Daniel Villano-Herrera # date: 7/23/2021 # --------------- # Section 2 # --------------- # # ---------- # Part 1 # ---------- # print('----- Section 2 -----'.center(25)) print('--- Part 1 ---'.center(25)) # 2 - Palindrome print('\n' + 'Task 1' + '\n') # # Background: A palindrome is a word that is the same if read forwards and backwards. Examples of palindromes include: # - mom # - dad # - radar # - deified # # Instructions # a. Prompt input from the user in the form of a word. # b. Determine if the word is a palindrome. # a. If so, print that the word is a palindrome. # b. Otherwise, print that the word is not a palindrome. word = input('Please enter a word: ') # Creating a function called palindrome with words as parameter. def palindrome(words): # Creating a variable called reserve which will take the parameter and reserve it. reverse = words[::-1] # If the parameter and reserve are the same, then we print out that they are the same, not if otherwise. if words == reverse: print('The word is a palindrome.') else: print('The word is not a palindrome') palindrome(word) # 2 - for Loop Patterns print('\n' + 'Task 2' + '\n') # # # Instructions # a. Create at least two of the following patterns using for loops and conditionals. One has been done for you as an # example. You still have to do two more. You are free to choose which ones you do. # b. Use the symbol specified by the user. # $$$$$ | i = 0 # $ | i = 1 # $ | i = 2 # $$$$$ | i = 3 # $ | i = 4 # $ | i = 5 # $$$$$ | i = 6 # When i is evenly divisible by 3 --> 5 symbols. Otherwise, 1 symbol. s = input('>> symbol | ') for i in range(7): if i % 3 == 0: print(s * 5) else: print(s) print() # **** | i = 0 # * * | i = 1 # * * | i = 2 # * * | i = 3 # * * | i = 4 # * * | i = 5 # **** | i = 6 d = input('Enter a symbol: ') for i in range(7): if i % 6 == 0: print(d * 4) else: print(d + ' ' * 3 + d) print() # & | i = 0 # & | i = 1 # & | i = 2 # & | i = 3 # & | i = 4 # &&&&& | i = 5 el = input('Enter a symbol: ') for i in range(6): if i == 5: print(el * 5) else: print(el) print() # @ @ | i = 0 # @ @ | i = 1 # @ @ | i = 2 # @ | i = 3 # @ @ | i = 4 # @ @ | i = 5 # @ @ | i = 6 # ------- # - # - # - # - # - # -------
true
b74184838111476129625eb2f3b1f26e6f189b4f
interviewprep/InterviewQuestions
/stacksandqueues/python/reverse_parentheses.py
1,304
4.15625
4
# You are given a string s that consists of lower case English letters and brackets. # Reverse the strings in each pair of matching parentheses, starting from the innermost one. # Your result should not contain any brackets. # Example 1: # # Input: s = "(abcd)" # Output: "dcba" # # Example 2: # # Input: s = "(u(love)i)" # Output: "iloveu" # Explanation: The substring "love" is reversed first, then the whole string is reversed. # # Example 3: # # Input: s = "(es(iv(re))nU)" # Output: "Universe" # Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. # # Example 4: # # Input: s = "a(bcdefghijkl(mno)p)q" # Output: "apmnolkjihgfedcbq" def reverse_parentheses(s): stack = [] for x in s: if x != ')': stack.append(x) else: temp = get_reverse(stack) for c in temp: stack.append(c) return ''.join(stack) def get_reverse(stack): result = [] x = len(stack) - 1 while stack[x] != '(': result.append(stack.pop()) x -= 1 stack.pop() # Get rid of '(' return result if __name__ == '__main__': tests = ["(abcd)", "(u(love)i)", "(es(iv(re))nU)", "a(bcdefghijkl(mno)p)q"] for t in tests: print(reverse_parentheses(t))
true
66af55819c15092e3431065410c26c302cf2e279
Tayyab-Ilahi12/Python-Programs-for-practice
/FlashCard Game.py
1,900
4.46875
4
""" This flashcard program allows the user to ask for a glossary entry. In response,if user select show flash card the program randomly picks an entry from all glossary entries. It shows the entry. After the user presses return, the program shows the definition of that particular entry. If user select show_definition the program randomly picks a definition fro the glossary. It shows the definition and if user presses return, the program displays the key of the random definition displayed. The user can repeatedly ask for an entry , or the definition also has the option to quit the program instead of seeing another entry or definition. """ from random import * def show_flashcard(): """ Show the user a random key and ask them to define it. Show the definition when the user presses return. """ random_key = choice(list(glossary)) print('Define: ', random_key) input('Press return to see the definition') print(glossary[random_key]) def show_definition(): """Show the user a random definiton. Show the key which is associated with the random definition printed above""" random_key = choice(glossary.values()) print(random_key) input('Press return to see the word') key = glossary.keys()[glossary.values().index(random_key)] print key # Set up the glossary glossary = {'word1':'definition1', 'word2':'definition2', 'word3':'definition3'} # The interactive loop exit = False while not exit: user_input = sinput('Enter s to show a flashcard,Enter d to see a definition and q to quit: ') if user_input == 'q': exit = True elif user_input == 's': show_flashcard() elif user_input == 'd': show_definition() else: print('You need to enter either q or s.')
true
4f58cdbfa6c6e24a07ad1305632cca0e50dfb70b
Ananya31-tkm/PROGRAMMING_LAB_PYTHON
/CO2/CO2-Q1.py
213
4.1875
4
n=int(input("enter number:")) fact=1 if n<0: print("cannot find factorial") elif n==0: print("Factorial is 0") else: for i in range(1,n+1): fact=fact*i print("Fctorial of ",n," is",fact)
true
a22fca2b62384a297e2feea5dbfa57a3dc509313
ArtHouse5/python_progs
/simple_tasks.py
2,303
4.21875
4
#1 print('Create list of 6 numbers and sort it in ascending order') l=[4,23,15,42,16,8] print('The initial list is ',l) l.sort() print(l) print() #2 print('Create dictionary with 5 items int:str and print it pairwise') d = {1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five'} print('The initial dictionaty is ',d) for key in d: print(key,d[key]) print() #3 print('Create tuple with 5 fractions and find min and max in it') from fractions import Fraction t=(Fraction(1,2),Fraction(2,3),Fraction(5,7),Fraction(1,4),Fraction(7,8)) print('The initial tuple is ',t) print('The maximum in this tuple is {}, the minimum is {}'.format(max(t),min(t))) print() #4 print('Create list of three words and concatenate it to get "word1->word2->word3"') l2=['Earth','Spain','Madrid'] print('The initial list is ',l2) sep='->' print(sep.join(l2)) print() #5 print(' Split the string "/bin:/usr/bin:/usr/local/bin" into list by symbol ":" ') s = '/bin:/usr/bin:/usr/local/bin' print(s.split(':')) print() #6 print('print which numbers from 1 to 100 are devided by 7 and which are not') for i in range(1,101): if i%7==0: print(i, ' devided by 7') else: print(i, ' is not devided by 7') print() #7 print('Create matrix 3x4 and print firstly all the rows then all the columns') multi=[[1,2,3,4], [5,6,7,8], [9,10,11,12] ] print('The initial matrix is ',multi) print('Rows are :') for row in multi: print(row) print('Columns are:') for column in range(0,4): print() for i in range(0,3): print(multi[i][column]) print() """ also we can do it with the help of numpy: import numpy as np A = np.array([[1,2,3,4],[5,6,7,8]]) array([[1, 2, 3, 4], [5, 6, 7, 8]]) A[:,2] # returns the third columm """ #8 print('Create a list and in the loop write the object and its index') l3=['booom', 84, None, 'python', True, False, 90, 33] print(l3) for object in l3: print('Object {} has index {}'.format(object,l3.index(object))) #9 print('Create a list with tree values "to_delete" among the others and delete them') l4=['to_delete','Good!','better','to_delete','to_delete','the_best'] print(l4) while 'to_delete' in l4: l4.remove('to_delete') print('Clear list : ',l4) #10 print('Print numbers from 10 to 1') for i in range(10,-1,-1): print(i)
true
d16fca91d7550b7a22417b6730d2d92cde1b217b
annamaryjacob/Python
/OOP/Polymorphism/2str.py
508
4.25
4
class Person(): def setPerson(self,age,name): self.age=age self.name=name def __str__(self): return self.name+str(self.age) ob=Person() ob.setPerson(25,"name") print(ob) #When we give print(ob) we get '<__main__.Person object at 0x7f92fee45ba8>'. This is the method called 2string method in the parent class #'Object' which is a parent class for every class we make. We overide this method in our child class (def __str__(self) so that when #we print ob we get only 'name'
true
6c048cc77e200c6e6a379addf34afc63bf910e5a
mherr77m/pg2014_herrera
/HW2/HW2_q1.py
1,280
4.3125
4
# !env python # Michael Herrera # 10/18/14 # HW2, Problem 1 # Pass the function two arrays of x,y points and returns # the distance between all the points between the two arrays. import numpy as np def distance(array1,array2): """ Calculates the distance between all points in two arrays. The arrays don't have to be the same size. Each array has the form [[x1,y1],[x2,y2],...,[xn,yn]] """ # Use array broadcasting in the distance formula to # allow for arrays of different sizes dist = np.sqrt((array1[:,0,np.newaxis] - array2[:,0])**2 + \ (array1[:,1,np.newaxis] - array2[:,1])**2) return dist if __name__ == '__main__': array1 = np.array([[1,2],[3,4],[5,6],[7,8]]) array2 = np.array([[1,2],[3,4]]) dist = distance(array1,array2) print "Problem 1:\n" print "Points from array1" for p in array1: print ' (%.0f,%.0f)' % (p[0],p[1]) print "Points from array2" for p in array2: print ' (%.0f,%.0f)' % (p[0],p[1]) print "\nPoint 1 Point 2 Distance" ic = 0 for i in array1: jc = 0 for j in array2: print " (%.0f,%.0f) (%.0f,%.0f) %.2f" % \ (i[0],i[1],j[0],j[1],dist[ic,jc]) jc += 1 ic += 1
true
ca7c7c91bf638b4e18660677fe8fb4f7630c4c01
Neenu1995/CHPC-PYTHON
/bisection_cuberoot.py
322
4.125
4
number = input('Enter the number : ' ) number = float(number) change = 0.00001 low =0.0 high = max(1.0,number) mid = (low+high)/2.0 while (abs(mid**3-number)>=change): if mid**3<number: low = mid else: high = mid mid =(low+high)/2.0 print 'The cube root of ', number ,' is ', mid
true
185abd0b12115a2cf3f91ac799fccc664c403a14
LessonsWithAri/textadv
/next.py
1,803
4.15625
4
#!/usr/bin/env python3 INVENTORY = [] room_learning_took_soda = False def room_learning(): global room_learning_took_soda print("You are in room #312. You see a Kellan, a Maria, and a Brooke.") if not room_learning_took_soda: print("There is a can of soda on the table.") print("Exits: DOOR") command = input("> ").lower() if command == "door": print("You have gone through the door.") room_hallway() elif command == "kellan": print("Kellan says, 'Hi!'") room_learning() elif command == "maria": print("Maria is busy doing coding") room_learning() elif command == "brooke": print("Brooke is writing a story") room_learning() elif command == "take the soda" and not room_learning_took_soda: print("You pick up the soda. It's nice and cold.") room_learning_took_soda = True INVENTORY.append('soda') room_learning() else: print("INVALID COMMAND!!!") room_learning() room_hallway_gave_matt_soda = False def room_hallway(): global room_hallway_gave_matt_soda print("You are in the hallway. It's very spoooooky.") if not room_hallway_gave_matt_soda: print("Matt is here, he's very thirsty.") print("Exits: LEARNING") command = input("> ").lower() if command == "learning": print("You are going back to the learning room.") room_learning() elif command == "give matt the soda" and not room_hallway_gave_matt_soda and 'soda' in INVENTORY: print("You give Matt the soda. He says thanks, gulps it down, and leaves.") INVENTORY.remove('soda') room_hallway_gave_matt_soda = True room_hallway() else: print("INVALID COMMAND!!!") room_hallway() room_learning()
true
6a8b4dab5c7639a003dc530cb9d4bf6c5fb5c552
Michaeloye/python-journey
/simp-py-code/Password_Validation_sololearn.py
1,044
4.40625
4
# Password Validation : You are interviewing to join a security team. They want to see you build a password evaluator for your technical interview to validate #the input. #task: Write a program that takes in a string as input and evaluates it as a valid password. The password is valid if it has a minimum 2 numbers, 2 of #the following special characters('!', '@', '#', '$', '%', '%', '*'), and a length of at least 7 characters. if the password passes the check, output 'Strong' #else output 'Weak'. #Input Format: A string representing the password to evaluate. #Output Format: A string that says 'Strong' if the input meets the requirements, or 'Weak', if not. #Sample Input: Hello@$World19 #Sample Output: Strong import string password = input("Enter password \n") numbers = 0 sym = string.punctuation no_of_sym = 0 for char in password: if char.isnumeric(): numbers += 1 elif char in sym: no_of_sym += 1 if no_of_sym >= 2 and numbers >= 2 and len(password) >= 7: print("Strong") else: print("Weak")
true
9940f0e66b71ed701e9ee4440772a39b4f0d8726
Michaeloye/python-journey
/simp-py-code/Tkinter_trial_DL.py
2,046
4.5625
5
from tkinter import * # Import all definitions from tkinter window = Tk() # Create a window label = Label(window, text = "Welcome to Python") # Create a label button = Button(window, text = "Click Me") # Create a button label.pack() # Place the label in the window button.pack() # Place the button in the window window.mainloop() window = Tk() label = Label(window, text = "Welcome to Python", cursor = "plus", justify = LEFT) button = Button(window, text = "Click") button.pack() # pack manager packs it row by row therefore the button comes before the label label.pack() window.mainloop() # This creates an event loop which processes the events until you close the main window # so therefore you have to create a window again using window = Tk() else it would give an error def pressbutton(): label["text"] = "Hi" # to change the text written... from "thank you" to "Hi" window = Tk() label = Label(window, text = "Hello there") button = Button(window, text = "Thank you", bg = "skyblue",command = pressbutton) label.pack() button.pack() window.mainloop() window = Tk() frame1 = Frame(window) frame1.pack() label = Label(frame1, text = "Hello") button = Button(frame1, text = "okay") label.grid(row = 1, column = 1) button.grid(row = 1, column = 2) window.mainloop() window = Tk() # Create a window window.title("Grid Manager Demo") # Set title message = Message(window, text ="This Message widget occupies three rows and two columns") message.grid(row = 1, column = 1, rowspan = 3, columnspan = 2) Label(window, text = "First Name:").grid(row = 1, column = 3) Entry(window).grid(row = 1, column = 4, padx = 5, pady = 5) Label(window, text = "Last Name:").grid(row = 2, column = 3) Entry(window).grid(row = 2, column = 4) Button(window, text = "Get Name").grid(row = 3, padx = 5, pady = 5, column = 4, sticky = E) image_1 = PhotoImage(file = "download.gif") canvas = Canvas(window, width = 300, height = 400) canvas.create_image(70,90, image = image_1) canvas.grid(row = 4, column = 7) window.mainloop() # Create an event loop
true
338d446f53b76308220122fdd2b1115eaf3906db
Michaeloye/python-journey
/simp-py-code/raise_to_power.py
588
4.40625
4
#raise to power base_num = int(input("Enter the base number: ")) pow_num = int(input("Enter the power number: ")) def raise_to_power(base_num, pow_num): result = 1 for num in range(pow_num): '''since the pow_num is what the base_num will multiply itself by. so pow_num if 3 will cause the code loop 3 times that means 1*4 for pow_num 1 then pow_num 2 the result will be stored as 4 for pow_num 1 then run again present result 4 4*4 for pow_num 3 16*4''' result = result * base_num return result print(raise_to_power(base_num, pow_num))
true
a68f609d435c84d30dc569699894df16d8db9354
Michaeloye/python-journey
/simp-py-code/New_driver's_license_sololearn.py
1,372
4.1875
4
# New Driver's License #You have to get a new driver's license and you show up at the office at the same time as 4 other people. The office says that they will see everyone in #alphabetical order and it takes 20 minutes for them to process each new license. All of the agents are available now and they can each see one customer at a #time. How long will it take for you to walk out of the office with your new license? # Task: Given everyon's name that showed up at the same time, determine how long it will take to get your new license. # Input Format: Your input will be a string of your name, then an integer of the number of available agents, and lastly a string of the other four names #seperated by spaces. # Output Format: You will output an integer of the number of minutes that it will take to get your license. # Sample Input: # "Eric" # 2 # "Adam Caroline Rebecca Frank" # Sample Output: # 40 Explanation it will take 40 minutes to get your license because you are in the second group of two to be seen by one of the two available agents. name = input("Please enter your name: ") no_of_agents = int(input("Please enter the number of agents: ")) others = input("Please enter the names of the rest people: ") list1 = [] others_split = others.split() list1.extend(others_split) list1.append(name) list1.sort() answer = int(((list1.index(name)/no_of_agents)*20) + 20) print(answer)
true
24f8a43e73503662cd2a930ad44a5fe1cb29e16f
Michaeloye/python-journey
/simp-py-code/task21.py
658
4.125
4
# Bob has a strange counter. At the first second t=1, it displays the number 3. At each subsequent second, the number displayed by the counter decrements by 1. # the counter counts down in cycles. In the second after the counter counts down to 1, the number becomes 2 times the initial number for that countdown cycle # and then continues counting down from the new initial number in a cycle. # Given a time, t. Find and print the value displayed by the counter at time t. v = 3 t = 1 time = int(input("Enter the time at which you want to know the value: ")) while time < t : if v == 1: break t += 1 v -= 1 t = t * 2 print(t)
true
25b83260765a26cab0ba821ad5b69b5161ffc171
Michaeloye/python-journey
/simp-py-code/task7.py
672
4.1875
4
# Given a string input count all lower case, upper case, digits, and special symbols def findingchars(string): ucharcount = 0 lcharcount = 0 intcount = 0 symcount = 0 for char in string: if char.isupper(): ucharcount+=1 elif char.islower(): lcharcount+=1 elif char.isnumeric(): intcount+=1 else: symcount+=1 print("Number of lowercase characters is ", lcharcount, " Number of uppercase characters is ", ucharcount, " Number of integers is ", intcount, " Number of symbols is ", symcount,) findingchars("GUioKJio*$%#124")
true
a802e0447e69c9e42b353305575d0762fcbc3f86
fish-py/PythonImpl
/collections/dict.py
237
4.125
4
dict1 = { "firstName": "Jon", "lastName": "Snow", "age": 33 } """ 遍历dict """ for key in dict1.keys(): print(key) for value in dict1.values(): print(value) for key, value in dict1.items(): print(key, value)
true
e58d6c0bc2831729f65f722de7e4bb30b7291a4b
DanielSouzaBertoldi/codewars-solutions
/Python/7kyu/Isograms/solution.py
508
4.15625
4
# Calculates the ocurrence of every letter of the word. # If it can't find more than one ocurrence for every letter, # then it's an isogram. def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False return True # That was my first try at this challenge. Then ocurred to me # you could use the set() function and just compare the # lengths, like so: def is_isogram(string): return len(string) == len(set(string.lower()))
true
b20046be773df17575d2c87213cc2c55aa70e186
n8951577/scrapy
/factorial.py
253
4.1875
4
def factorial(x): if x == 1: return 1 else: return x * factorial(x - 1) try: n = int(input("enter a number to find the factorial of a digit")) print ("The factorial of n is %d" % factorial(n)) except: print("Invalid")
true
dc0d64d1c54a204ecebbb0a589f354f13447c876
priyanshi1996/Advanced_Python_Course
/Ex_Files_Adv_Python/Exercise Files/04 Collections/defaultdict_finished.py
1,272
4.5
4
# Demonstrate the usage of defaultdict objects from collections import defaultdict def main(): # define a list of items that we want to count fruits = ['apple', 'pear', 'orange', 'banana', 'apple', 'grape', 'banana', 'banana'] fruitCount = {} # Count the elements in the list # This code will give error because we are trying to modify the value # of this key, before its been initialy added to the dictionary for fruit in fruits: fruitCount[fruit] += 1 # To avoid the above error we could write something like this for fruit in fruits: if fruit in fruitCount.keys(): fruitCount[fruit] += 1 else: fruitCount[fruit] = 1 # use a dictionary to count each element # this code says that if I am trying to access a key which # does not exists, create a default value for me fruitCounter = defaultdict(int) # We can also use lambda here, here each key will start from 100 # fruitCounter = defaultdict(lambda:100) # Count the elements in the list for fruit in fruits: fruitCounter[fruit] += 1 # print the result for (k, v) in fruitCounter.items(): print(k + ": " + str(v)) if __name__ == "__main__": main()
true
5af4158a8ff3d270b35e6b6b02332ca3cb82ce43
IfthikarAliA/python
/Beginner/3.py
261
4.125
4
#User input no. of Element a=int(input("Enter the number of Element: ")) #Empty List l=[] #Function to get list of input for i in range(a): l.append(int(input(f"Enter the {i+1} item: "))) #Iterator over a list for i in l: if(i%2==0): print(i)
true
f707d8fc6cf42c70d569c187792d1fa674f17bc0
austindrenski/GEGM-Programming-Meetings
/ProgrammingMeeting1_Python/Example.py
428
4.125
4
class Example: """Represents an example.""" def __init__(self, value): self.value = value def increase_value(self, amount): """Increases the value by the specified amount.""" self.value = self.value + amount return self.value > 0 def __repr__(self): """Returns a string that represents the current object.""" return "The value of this example is %i" % self.value
true
663c8604ccf16d20dd92c597ba4b5f33fd26bb39
austinrhode/SI-Practical-3
/shortest_word.py
488
4.4375
4
""" Write a function that given a list of word, will return a dictionary of the shortest word that begins will each letter of the alphabet. For example, if the list is ["Hello", "hi", "Goodbye", "ant", "apple"] your dictionary would be { h: "Hi", g: "Goodbye", a: "ant" } because those are the shortest words that start with h, g, and a (which are the only starting letters present) Notice that the function is not case sensitive. """ def shortest_word(a_list): pass
true
3f63aac86bed8b98276e9850fbb00421121d6eae
BridgitA/Week10
/mod3.py
713
4.125
4
maximum_order = 150.00 minimum_order = 5.00 def cheese_program(order_amount): if order_amount.isdigit() == False: print("Enter a numeric value") elif float(order_amount) > maximum_order: print(order_amount, "is more than currently available stock") elif float(order_amount) < minimum_order: print(order_amount, "is less than currently available stock") elif (float(order_amount)<= maximum_order) and (float(order_amount)>= minimum_order): print(order_amount, "pounds costs", int(order_amount) * 5) else: print("Enter numeric value") weight = input("Enter cheese order weight (pounds numeric value): ") function = cheese_program(weight)
true
f8293c7294cc10da6dab7dfedf7328c865f899fe
michellesanchez-lpsr/class-sampless
/4-2WritingFiles/haikuGenerator.py
794
4.3125
4
# we are writing a program that ask a user for each line of haiku print("Welcome to the Haiku generator!") print("Provide the first line of your haiku:") # create a list to write to my file firstL = raw_input() print(" ") print("Provide the second line of your haiku:") secondL = raw_input() print(" ") print("Provide the third line of your haiku:") thirdL = raw_input() print(" ") print("What file would you like to write your haiku to?") # ask the user for raw_input x = raw_input() myProgram = open( x , "w") myProgram.write(firstL) myProgram.write(secondL) myProgram.write(thirdL) print("Done! To view your haiku, type 'cat' and the name of your file at the command line.") print("When you run cat and the file name at the terminal, you should get your haiku!") myProgram.close()
true
9e20d9bab577aba6e39590e3365b56b9325dd32a
michellesanchez-lpsr/class-sampless
/msanchez/university.py
584
4.1875
4
# print statements print(" How many miles away do you live from richmond state?") miles = raw_input() miles = int(miles) #if else and print statements if miles <=30: print("You need atleast 2.5 gpa to get in") else: print("You need atleast 2.0 gpa to get in") print(" What is your gpa?") gpa = float(raw_input()) gpa = int(gpa) if miles <=30 <= 2.0: print("Great you have been accepted") else: print("What is your act score?") act = (input()) act = int(act) if miles >30 and gpa >= 2.5 and act >=18: print("Sorry you need all 3 to get in") else: print("Accepted")
true
5ff742b0b2ec95157cc738b9668d911db3ee6e7e
ceden95/self.py
/temperature.py
445
4.46875
4
#the program convert degrees from F to C and the opposite. temp = input("Insert the temperature you would like to convert(with a 'C' or 'F' mark):") temp_type = temp[-1].upper() temp_number = float(temp[:-1]) C_to_F = str(((9*temp_number)+(160))/5) F_to_C = str((5*temp_number-160)/9) if (temp_type == "C"): print(C_to_F + "F") elif (temp_type == "F"): print (F_to_C + "C") else: print("told you to mark the temperature")
true
76f0e060b29af72dd5420918b10a0b2034073891
ceden95/self.py
/9.3.1.fileFor_listOfSongs.py
2,791
4.34375
4
#the program uses the data of file made from a list of songs details in the following structure: #song name;artist\band name;song length. #the function my_mp3_playlist in the program returns a tuple of the next items: #(name of the longest song, number of songs in the file, the most played artist) def main(): file_path = "C:\python course\9.3.1\9.3.1.listOfSongs.txt" playlist_tuple = my_mp3_playlist(file_path) print(playlist_tuple) def my_mp3_playlist(file_path): """the function creates a tuple of 3 item from a date in file_path. :param file_path: file path to a file of playlist. :file_path type: str :return: (first_in_tuple, second_in_tuple, third_in_tuple). :rtype: tuple""" opened_file_path = open(file_path, "r") readed_file_path = opened_file_path.read() opened_file_path.close() #the longest song first_in_tuple = find_the_longest_song(readed_file_path) #number of songs in the file second_in_tuple = len(song_details_in_list(readed_file_path)) #the most played artist third_in_tuple = find_most_played_artist(readed_file_path) ourTuple = (first_in_tuple, second_in_tuple, third_in_tuple) return ourTuple def song_details_in_list(readed_file_path): splited_lines_file = readed_file_path.split("\n") song_details = [] for item in splited_lines_file: splited_item = item.split(";") song_details.append(splited_item) return song_details def find_the_longest_song(readed_file_path): song_details = song_details_in_list(readed_file_path) listOfSongsStr = [] for item in song_details: listOfSongsStr.append(item[2]) listOfSongsFloat = [] for item in listOfSongsStr: a = item.replace(":", ".") strToFloat = float(a) listOfSongsFloat.append(strToFloat) listOfSongsFloat.sort() longestSong = str(listOfSongsFloat[-1]).replace(".", ":") for item in song_details: if longestSong in item: longest_song = item[0] return longest_song def find_most_played_artist(readed_file_path): song_details = song_details_in_list(readed_file_path) listOfArtist = [] for item in song_details: listOfArtist.append(item[1]) times_played_dict = {} for item in listOfArtist: if item in times_played_dict.keys(): times_played_dict[item] = int(times_played_dict[item]) + 1 else: times_played_dict[item] = 1 maxValue = max(times_played_dict.values()) ourArtist = "" for key in times_played_dict.keys(): if(times_played_dict[key] == maxValue): ourArtist = key break return ourArtist main()
true
266f1eef9643832e942c30fec52406331b26b8ae
ceden95/self.py
/for_loop.py
816
4.3125
4
#the program creates a new list(from the list the user created) of numbers bigger then the number the user choosed. def main(): list1 = input('type a sequence of random numbers devided by the sign ",": ') my_list = list1.split(",") n = int(input("type a number which represent the smallest number in your new list: ")) is_greater(my_list, n) def is_greater(my_list, n): """the fuction creates a list of numbers from my_list from numbers bigger them number n. :param my_list: list of numbers :my_list type: list :param n: number from user :n type: int""" my_new_list = [] for num in my_list: num = int(num) if num > n: my_new_list.append(num) else: continue print(my_new_list) main()
true
f55a6562de4c30e76723c61ef0a3a60ef178bec2
ceden95/self.py
/shift_left.py
713
4.4375
4
#the program prints the new list of the user when the first item moving to the last on the list. def shift_left(my_list): """the func receives a list, replace the items on the list with the item on the left :param my_list: list from user. :type my_list: list. :return: my_shift_list :rtype: list with str items""" my_list.append("") my_list[-1] = my_list[0] my_shift_list = my_list[1:-1] + [my_list[-1]] print(my_shift_list) list = input('please type a group of numbers\\words devided by "," (without space):') print("your list is: ") print(list) list = list.split(",") print("your new updated list with the first item to the last is:") shift_left(list)
true
c32e466c8f7004bc5e9b8fd23cfe9714d39cad09
Andrewctrl/Final_project
/Visting_Mom.py
744
4.25
4
import Visting_mom_ending import Getting_help def choice(): print("You get dressed up quicky as you rush out to visit your mom in the hospital. " + "You visit your mom in the hospital, she is doing well. But you have a pile of bills. You get a job working at In-and-Out. Balancing work and school is hard, your grades are dropping.") answer = input("Do you quit school and work full time, or do you try to get help with school, therefore maintaining your job and school." + "Type \"Quit School\" to quit school, \"Get help\" to get help with school.") # question for dropping out or getting help with school if answer == "Quit School": Visting_mom_ending.final() if answer == "Get Help": Getting_help.got_help()
true
ea5a201812b6f4ad9ba49505a53e99bcbf207a42
ar021/control-flow-lab
/exercise-2.py
305
4.15625
4
# exercise-02 Length of Phrase while True: phrase = input('Please enter a word or phrase or "quite" to Exit:') if phrase == 'quite': print('Goodbye') break else: phrase_length = len(phrase) print(f'What you entered is {phrase_length} characters long')
true
d2cc0691e0e05128e98144d19206b7a6f2df3f70
EVgates/VSAproject
/proj02/proj02_02.py
1,100
4.3125
4
# Name: # Date: # proj02_02: Fibonaci Sequence """ Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci sequence 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... """ amount = int(raw_input("How many numbers do you wish to generate?")) x=0 y=1 print y while amount-1> 0: z = x + y print z x= y y= z amount= amount-1 print "Generation complete." c = raw_input("Do you want to generate any more numbers?") if c=="yes" or c=="Yes" or c=="Yeah" or c== "Yep" or c=="YES" or c=="yep" or c=="yeah" or c=="y" or c=="Y": dog = int(raw_input("How many numbers do you wish to generate this time?")) x=0 y=1 print y for number in range (1,dog): z = x+ y print z x= y y= z dog= dog + 1 "Program complete." elif c=="no" or c=="No" or c=="NO" or c=="Nope" or c=="nope": print "Program complete." else: print "That is an unacceptable answer. Program incomplete."
true
0c6f697432c64e2ff1dfd39192c3e2d5d7938ba9
H0bbyist/hero-rpg
/hero_rpg.py
2,112
4.1875
4
from math import * #!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Character: def alive(self): if self.health > 0: return True def attack(self, enemy): enemy.health -= self.power def print_status(self): print("The {} has {} health and {} power.".format(self.name, self.health, self.power)) class Hero(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power class Goblin(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power class Zombie(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power hero = Hero("Hero", 10, 5) goblin = Goblin("Goblin", 6, 2) zombie = Zombie("Zombie", float(inf), 100) en = zombie while en.alive() and hero.alive(): print() hero.print_status() en.print_status() print() print("What do you want to do?") print("1. fight {}".format(en.name)) print("2. do nothing") print("3. flee") print("> ", end=' ') raw_input = input() if raw_input == "1": # Hero attacks goblin hero.attack(goblin) print("You do {} damage to the {}.".format(hero.power,en.name)) if en.health <= 0: print("The {} is dead.".format(en.name)) elif raw_input == "2": pass elif raw_input == "3": print("What kind of hero runs?") break else: print("Invalid input {}".format(raw_input)) if en.health > 0: # Goblin attacks hero en.attack(hero) print("The {} does {} damage to you.".format(en.name, en.power)) if hero.health <= 0: print("You are dead.")
true
e2af114dca2a51f5802980c84b596e2e794ae15e
Percapio/Algorithms-and-Data-Structures
/lib/algorithms/quick_sort.py
1,957
4.15625
4
# Quick Sort: # Sort an unsorted array/list by first indexing an element as the pivot point, # check if this index is our target. If not, then check if target is more than # the indexed point. If it is then we check the right half of the list, otherwise # we check the left half. ###################################################### # Recursive Quick Sort # Time Complexity: O( nlogn ) def recursive( array ): size = len( array ) # Recursive requires base case if size <= 1: return array # Partition the array for sorting left, right, pivot = partition( array, size ) # Recursive call this function on left and right and concat # results together return recursive( left ) + [ pivot ] + recursive( right ) def partition( array, size ): # Pivot point to compare elements too pivot = array[ 0 ] # Left and right list to plug the elements in for sorting left = [] right = [] # Iterate: placing lower than in left list and higher in right for i in range( 1, size ): if array[ i ] < pivot: left.append( array[ i ] ) else: right.append( array[ i ] ) return left, right, pivot ###################################################### ###################################################### # Iterative Quick Sort # Time Complexity: O( n^2 ) def iterative( array ): # push the array onto a stack stack = array[:] size = len( stack ) # iterate until stack is empty while size > 0: # decrease stack size, and use size as index for pivot size -= 1 pivot = stack[ size ] # partition the given array around the pivot point array = partition_iter( array, pivot ) return array def partition_iter( array, pivot ): left = [] right = [] # step through the array, and partition based on for i in range( len(array) ): if array[ i ] < pivot: left.append( array[ i ] ) else: right.append( array[ i ] ) # concat return left + right
true
48ff5efd50d6150ab8bf1b0e5e30fb7f0bd6e585
bhandarisudip/learn_python_the_hard_way_book_exercises
/ex6-studydrills.py
1,535
4.6875
5
#ex06-study drills #assign a string to x that includes a formatting character, which is then replaced by 10 x = "There are %d types of people."%10 #create a variable, binary, and assign the string "binary" to it binary = 'binary' #assign a new variable a string "don't" to a variable 'do_not' do_not = "don't" #create a string called y, replace the formatting characters with variables "binary" and # "do_not". Example of two strings inside a string. y = "Those who know %s and those who %s."%(binary, do_not) #print x, i.e., "There are 10 types of people" print(x) #print y, i.e., "There are those who know binary and those who don't" print(y) #print "I said: There are 10 types of people". #Example of an integer (10) within a string (x), within a string "I said:" print('I said: %r'%x) #print "I also said: Those who know binary and those who do not". #Example of two strings (binary and do_not) within a string (y) within a string "I also said:" print("I also said: '%s'"%y) #assign boolean False to a variable hilarious hilarious = False #assign a string "Isn't that joke so funny?!" to a variable, joke_evaluation joke_evaluation = "Isn't that joke so funny?! %r" #assign a string "This is the left side of the string..." to variable w. w = 'This is the left side of the string...' #assign "a string with a right side" to a variable e e = 'a string with a right side' #print "This is the left side of the string...a string with a right side" #example of concatenating two strings with an operator '+' print(w+e)
true
a957213cad27ef8e8fcb5fcad84e18a9ff3ffa33
Arun-9399/Simple-Program
/binarySearch.py
550
4.15625
4
#Binary Search Algorithm def binarySearch(alist, item): first=0 last= len(alist)-1 found= False while first<= last and not found: midpoint= (first+last)//2 if alist[midpoint]== item: found= True else: if item<alist[midpoint]: last= midpoint-1 else: first= midpoint+1 return found if __name__ == "__main__": testlist=[0, 1,2, 8,13,17,19,32,42] print (binarySearch(testlist,3)) print (binarySearch(testlist, 32))
true
342ddc75e963daefe5348880baeaee70eb1d58f1
nikita-sh/CSC148
/Lab 3/queue_client.py
1,219
4.375
4
""" Queue lab function. """ from csc148_queue import Queue def list_queue(lst: list, q: Queue): """ Takes all elements of a given list and adds them to the queue. Then, checks the queue for items that are not lists and prints them. If the item being checked is a list, it is added to the queue. This process repeats until it is empty. >>> q = Queue() >>> l1 = [1, 3, 5] >>> l2 = [1, [3, 5], 7] >>> l3 = [1, [3, [5, 7], 9], 11] >>> list_queue(l1, q) 1 3 5 >>> list_queue(l2, q) 1 7 3 5 >>> list_queue(l3, q) 1 11 3 9 5 7 """ for i in lst: q.add(i) while not q.is_empty(): nxt = q.remove() if type(nxt) != list: print(nxt) else: for i in nxt: q.add(i) if __name__ == "__main__": q = Queue() val = int(input("Enter an integer:")) if val == 148: pass else: q.add(val) while val != 148: val = int(input("Enter an integer:")) if val == 148: break else: q.add(val) total = 0 while not q.is_empty(): total += q.remove() print(total)
true
677822cf2d9796a31de51f13477c5f31d097da76
hicaro/practice-python
/sorting/insertionsort.py
502
4.125
4
class InsertionSort(object): ''' Insertion Sort sorting algorithm implementation - Best case: O(n) - Average case: O(n^2) - Worst case: O(n^2) ''' @staticmethod def sort(numbers=None): _len = len(numbers) for i in range(1, _len): to_insert = numbers[i] j = i-1 while j >= 0 and numbers[j] > to_insert: numbers[j+1] = numbers[j] j=j-1 numbers[j+1] = to_insert
true
7df9e746b8e11f1e8d3dee1f840275f5e9763d68
ruchitiwari20012/PythonTraining-
/operators.py
693
4.53125
5
# Arithmetic Operators print(" 5+ 6 is ", 5+6) print(" 5- 6 is ", 5-6) print(" 5* 6 is ", 5*6) print(" 5/6 is ", 5/6) print(" 5//6 is ", 5//6) # Assignment Operator x=5 print(x) x+=7 print(x) x-=7 print(x) x/=7 print(x) #Comparison Operator i=8 print(i==5) print(i!=5)# i not equal to 5 print(i>=5) print(i<=5) # Logical Operator a = True b = False print(a and b) print(a or b) # Identical Operator # is , is not print(a is b) # No print(a is not b) # yes # Membership Operators #in , not in print("Membership Operators") list = [3,32,2,39,33,35] print(32 in list) print(324 not in list) print("Bitwise Operator") print(0 & 2) print( 0| 3)
true
f2121f4abcd95f8f5a98aaee6103f703cd5aa357
danismgomes/Beginning_Algorithms
/isPalindromeInt.py
603
4.15625
4
# isPalindrome # It verifies if a integer number is Palindrome or not answer = int(input("Type a integer number: ")) answer_list = [] while answer != 0: # putting every digit of the number in a list answer_list.append(answer % 10) # get the first digit answer = answer // 10 # remove the first digit def is_palindrome(a_list): for i in range(0, len(a_list)//2): if a_list[i] != a_list[len(a_list)-i-1]: # verifying if some element of the list is not palindrome return "It is not Palindrome." return "It is Palindrome." print(is_palindrome(answer_list))
true
d257b52336940b64bc32956911164029f56c5f22
maxz1996/mpcs50101-2021-summer-assignment-2-maxz1996
/problem3.py
1,587
4.40625
4
# Problem 3 # Max Zinski def is_strong(user_input): if len(user_input) < 12: return False else: # iterate through once and verify all criteria are met number = False letter = False contains_special = False uppercase_letter = False lowercase_letter = False special = {'!', '@', '#', '$', '%'} numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'} # using ascii codes to establish upper and lower bounds is a common pattern I've observed in algorithm problems involving strings # https://www.programiz.com/python-programming/examples/ascii-character lower_bound = ord('a') upper_bound = ord('z') for c in user_input: if c in special: contains_special = True elif c in numbers: number = True elif lower_bound <= ord(c.lower()) <= upper_bound: letter = True if c.lower() == c: lowercase_letter = True else: uppercase_letter = True return number and letter and contains_special and uppercase_letter and lowercase_letter print("Enter a password: ") user_input = input() if is_strong(user_input): print("This is a strong password.") else: print("This is not a strong password!") print("""Strong passwords contain: -at least 12 characters -both numbers and letters -at least one of these special characters: !, @, #, $, % -at least one capital and one lower case letter""")
true
56c94622c6852985b723bf52b0c2f20d2617f6c8
kaozdl/property-based-testing
/vector_field.py
2,082
4.125
4
from __future__ import annotations from typing import Optional import math class Vector: """ representation of a vector in the cartesian plane """ def __init__(self, start: Optional[tuple]=(0,0), end: Optional[tuple]=(0,0)): self.start = start self.end = end def __str__(self) -> str: return f'Vector:{self.start}, {self.end} - {self.length}' def __add__(self, v2: Vector) -> Vector: if not isinstance(v2, Vector): raise ValueError('Addition is only implemented for two vectors') return Vector( start=( self.start[0] + v2.start[0], self.start[1] + v2.start[1]), end=( self.end[0] + v2.end[0], self.end[1] + v2.end[1]) ) def __eq__(self, v2: Vector) -> bool: if not isinstance(v2, Vector): raise ValueError('Equality is only implemented for two vectors') return self.start == v2.start and self.end == v2.end @property def length(self) -> float: """ returns the length of the vector """ return math.sqrt((self.start[0] - self.end[0])**2 + (self.start[1] - self.end[1])**2) def center(self: Vector) -> Vector: """ returns an equivalent vector but with start in (0,0) """ new_end = (self.end[0] - self.start[0], self.end[1] - self.start[1]) return Vector(end=new_end) def project_x(self) -> Vector: """ Returns the projection over X of the vector """ return Vector( start=(self.start[0],0), end=(self.end[0],0) ) def project_y(self) -> Vector: """ returns the projection over Y of the vector """ return Vector( start=(0,self.start[1]), end=(0,self.end[1]), ) IDENTITY = Vector() CANONIC_X = Vector(start=(0,0), end=(1,0)) CANONIC_Y = Vector(start=(0,0), end=(0,1))
true
d629fb9d9ce965a27267cbc7db6a33662e0ff1d1
vusalhasanli/python-tutorial
/problem_solving/up_runner.py
403
4.21875
4
#finding runner-up score ---> second place if __name__ == '__main__': n = int(input("Please enter number of runners: ")) arr = map(int, input("Please enter runners' scores separated by space: ").split()) arr = list(arr) first_runner = max(arr) s = first_runner while s == max(arr): arr.remove(s) print("The second runner's score was : {}".format(max(arr)))
true
0844afed653ec7311aa6e269867e2723f131deca
atg-abhijay/Fujitsu_2019_Challenge
/EReport.py
1,374
4.34375
4
import pandas as pd def main(): """ main function that deals with the file input and running the program. """ df = pd.DataFrame() with open('employees.dat') as infile: """ 1. only reading the non-commented lines. 2. separating the record by ',' or ' ' into 3 columns - employee number, first name and last name """ df = pd.read_csv(infile, comment='#', header=None, names=['emp_number', 'emp_first_name', 'emp_last_name'], sep=" |,", engine='python') process_dataframe(df, 'emp_number', 'Processing by employee number...') print() process_dataframe(df, 'emp_last_name', 'Processing by last (family) Name...') def process_dataframe(dataframe, sort_column, message): """ Sort the given dataframe according to the column specified and print the records from the resulting dataframe along with the supplied message. :param pandas.DataFrame dataframe: Dataframe to process :param str sort_column: column by which to sort the dataframe :param str message: a message to show before printing the sorted data """ sorted_df = dataframe.sort_values(by=[sort_column]) print(message) for record in sorted_df.itertuples(index=False, name=None): print(str(record[0]) + ',' + record[1] + ' ' + record[2]) if __name__ == '__main__': main()
true
c3e6a8a88cce32769e8fe867b8e0c166255a8105
hansen487/CS-UY1114
/Fall 2016/CS-UY 1114/HW/HW6/hofai/q6.py
488
4.25
4
password=input("Enter a password: ") upper=0 lower=0 digit=0 special=0 for letter in password: if (letter.isdigit()==True): digit+=1 elif (letter.islower()==True): lower+=1 elif (letter.isupper()==True): upper+=1 elif (letter=='!' or letter=='@' or letter=='#' or letter=='$'): special+=1 if (upper>=2 and lower>=1 and digit>=2 and special>=1): print(password,"is a valid password.") else: print(password,"is not a valid password.")
true
d82eafc8998a0a3930ee2d868158da93fca0329b
hansen487/CS-UY1114
/Fall 2016/CS-UY 1114/HW/HW2/hc1941_hw2_q5.py
844
4.15625
4
""" Name: Hansen Chen Section: EXB3 netID: hc1941 Description: Calculates how long John and Bill have worked. """ john_days=int(input("Please enter the number of days John has worked: ")) john_hours=int(input("Please enter the number of hours John has worked: ")) john_minutes=int(input("Please enter the number of minutes John has worked: ")) bill_days=int(input("Please enter the number of days Bill has worked: ")) bill_hours=int(input("Please enter the number of hours Bill has worked: ")) bill_minutes=int(input("Please enter the number of minutes Bill has worked: ")) minutes=(john_minutes+bill_minutes)%60 hours=john_hours+bill_hours+(john_minutes+bill_minutes)//60 hours=hours%24 days=john_days+bill_days+(john_hours+bill_hours)//24 print("The total time both of them worked together is:",days,"days,",hours,"hours, and",minutes,"minutes.")
true
a7e9f749651d491f1c84f088ea128cbeaf18d9a5
lindsaymarkward/cp1404_2018_2
/week_05/dictionaries.py
505
4.125
4
"""CP1404 2018-2 Week 05 Dictionaries demos.""" def main(): """Opening walk-through example.""" names = ["Bill", "Jane", "Sven"] ages = [21, 34, 56] print(find_oldest(names, ages)) def find_oldest(names, ages): """Find oldest in names/ages parallel lists.""" highest_age = -1 highest_age_index = -1 for i, age in enumerate(ages): if age > highest_age: highest_age = age highest_age_index = i return names[highest_age_index] main()
true
d0b18dd59833733b72f5ef43a9b3d53ea0d1d429
Abarna13/Floxus-Python-Bootcamp
/ASSIGNMENT 1/Inverted Pattern.py
278
4.21875
4
''' Write a python program to print the inverted pyramid? * * * * * * * * * * * * * * * ''' #Program rows = 5 for i in range(rows,0,-1): for j in range(0,rows-1): print(end="") for j in range(0,i): print("*",end= " ") print()
true
d9918e166dc1f669bed7f96b01cce30470f0a85a
nealsabin/CIT228
/Chapter5/hello_admin.py
599
4.21875
4
usernames = ["admin","nsabin","jbrown","arodgers","haaron"] print("------------Exercise 5-8------------") for name in usernames: if name == "admin": print("Hello, admin. Would you like to change any settings?") else: print(f"Hello, {name}. Hope you're well.") print("------------Exercise 5-9------------") usernames = [] if usernames: for name in usernames: if name == "admin": print("Hello, admin. Would you like to change any settings?") else: print(f"Hello, {name}. Hope you're well.") else: print("The list is empty!")
true
31d8a9230ed12e4d4cb35b2802a9c721c1d23d15
nealsabin/CIT228
/Chapter9/restaurant_inheritance.py
1,049
4.21875
4
#Hands on 2 #Exercise 9-2 print("\n----------------------------------------------------------") print("-----Exercise 9-6-----\n") class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(f"{self.restaurant_name} serves {self.cuisine_type} food.") print(f"Occupent Limit: {self.number_served}") def set_number_served(self,served): self.number_served = served def increment_served(self, served): self.number_served += served class IceCreamStand(Restaurant): def __init__(self,restaurant_name,cuisine_type): super().__init__(restaurant_name,cuisine_type) self.flavors=["vanilla","chocolate","strawberry"] def display_flavors(self): print(f"{self.restaurant_name} serves: ") for flavor in self.flavors: print(flavor) stand=IceCreamStand("DQ","Ice Cream") stand.display_flavors()
true
5e2463436e602ab6a8764adee0e48605f50a7241
Jay07/CP2404
/billCalc.py
252
4.125
4
print("Electricity Bill Estimator") Cost = float(input("Enter cents per kWh: ")) Usage = float(input("Enter daily use in kWh: ")) Period = float(input("Enter number of billing days: ")) Bill = (Cost*Usage*Period)/100 print("Estimated Bill: $", Bill)
true
42c4caab27c4cdd3afc59c6270f372c6e388edb3
mvanneutigem/cs_theory_practice
/algorithms/quick_sort.py
1,936
4.40625
4
def quick_sort(arr, start=None, end=None): """Sort a list of integers in ascending order. This algorithm makes use of "partitioning", it recursively divides the array in groups based on a value selected from the array. Values below the selected value are on one side of it, the ones above it on the other. then the process is repeated for each of these sides and so on. Args: arr (list): list to sort. start (int): start index to sort list from end (int): end index to sort to list to. """ if start is None: start = 0 if end is None: end = len(arr) -1 pivot = partition(arr, start, end) if pivot == start: if start + 1 != end: quick_sort(arr, start+1, end) elif pivot == end: if start != end - 1: quick_sort(arr, start, end-1) else: if start != pivot -1: quick_sort(arr, start, pivot - 1) if pivot + 1 != end: quick_sort(arr, pivot + 1, end) def partition(arr, start, end): """"Separate the given array in two chuncks, by selecting a "pivot"value and moving all values smaller than the pivot to one side of it, and the values bigger than it to the other side of it. Args: arr (list): list to partition. start (int): start index to partition. end (int): end index to partition. Returns: int: index of the pivot value after partitioning the list. """ j = start+1 pivot = arr[start] for i in range(start+1, end+1): if arr[i] < pivot: arr[i], arr[j] = arr[j], arr[i] j += 1 # swap pivot to correct position arr[j - 1], arr[start] = arr[start], arr[j - 1] return j - 1 def main(): """Example usage.""" arr = [8, 4, 76, 23, 5, 78, 9, 5, 2] result = [2, 4, 5, 5, 8, 9, 23, 76, 78] quick_sort(arr) assert(result == arr)
true
1c7605d505ea2a2176883eaba72cfc04ff2fb582
knowledgewarrior/adventofcode
/2021/day1/day1-p1.py
1,590
4.40625
4
''' As the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine. For example, suppose you had the following report: 199 200 208 210 200 207 240 269 260 263 This report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on. The first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something. To do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.) In the example above, the changes are as follows: 199 (N/A - no previous measurement) 200 (increased) 208 (increased) 210 (increased) 200 (decreased) 207 (increased) 240 (increased) 269 (increased) 260 (decreased) 263 (increased) In this example, there are 7 measurements that are larger than the previous measurement. How many measurements are larger than the previous measurement? ''' import sys import os def main(): counter = 1 with open('input.txt') as my_file: num_list = my_file.readlines() for i in range(0,len(num_list)-1): if num_list[i+1] > num_list[i]: counter +=1 print(str(counter)) if __name__ == '__main__': main()
true
2c05503575eccf27161b3217d13da4027c91affb
dharunsri/Python_Journey
/Inheritance.py
738
4.3125
4
# Inheritance # Accessing another classes is calles inheritance class Songs: # Parent class / super class def name(self): print("People you know") def name2(self): print("Safe and sound") class selena(Songs): # Child class/ sub class - can access everything from parent class def info(self): print("American singer") def info2(self): print("Selena Gomez") class swift(selena): # It can access both classes. Or if selena is not a child class then swift(selena,songs) - this will access both def info3(self): print("Taylor Swift") s = Songs() s2 = selena() s3 = swift() s.name() s2.info2() s3.info3()
true
aabb79dc9eb7d394bf9a87cd51d9dacde5eabf3e
dharunsri/Python_Journey
/Python - Swapping of 2 nums.py
1,286
4.3125
4
# Swapping of two numbers a = 10 # 1010 b = 20 # 10100 # Method 1 temp = a a = b b = temp print(" Swapping using a temporary variable is : " ,'\n',a, '\n',b) # Method 2 a = a+b # 10 + 20 = 30 b = a-b # 30 - 20 = 10 a = a-b # 30 - 10 = 20 print(" Swapping without using a temporary variable is : ",'\n', a ,'\n', b) """Sometimes the bits can be lost for example, 5 = 101 6 =110 while swapping = 5 + 6 = 11 -> 1010 [ got 4 bits of 3 bits value. Losing a bit] """ # Method 3 # XOR method - here the losing of bits can be avoided a = a^b b = a^b a = a^b print("Swapping without using a temporary variable and without losing a bit: ", '\n',a ,"\n", b) """ xor works as - if the bit is, 0 in the second variable first will be the ans or if the bit is 1 in the second variable complement of 1st is ans for example, 10 - 01010 20 - 10100 11110 - 30 so the swapping will perform like this """ # Method 4 # Simple way - Rot2 method (rotation 2 | 2 rotation method) a,b =b,a print("Swapping in a simple way without using temporary variable : ", '\n',a ,"\n", b)
true
2dd468406342dc6e8f767ba6d469613b19eed0ad
samanthamirae/Journey
/Python/OrderCostTracking.py
2,862
4.25
4
import sys totalOrders = 0 #tracks number of orders in the batch batchCost = 0 #tracks the total cost across all orders in this batch # our functions def orderprice(wA,wB,wC): #calculates the cost total of the order cTotal = 2.67 * wA + 1.49 * wB + 0.67 * wC if cTotal > 100: cTotal = cTotal * .95 return cTotal def shippingcharge(oW): #Finds the shipping charge for the order based on total weight if oW <= 5: sCost = 3.5 elif oW <= 20: sCost = 10 else: sCost = 9.5 + .1 * oW return sCost def submitorder(): #Lets the user submit a new order global totalOrders global batchCost try: #checks for a float weightA = float(input("How many pounds of Artichokes would you like to order?\n")) weightB = float(input("How many pounds of Beets would you like to order?\n")) weightC = float(input("How many pounds of Carrots would you like to order?\n")) costTotal = orderprice(weightA,weightB,weightC) orderWeight = weightA + weightB + weightC shippingCost = shippingcharge(orderWeight) orderTotal = shippingCost + costTotal #update totals totalOrders += 1 batchCost = batchCost + orderTotal #Tell the user the cost, shipping charge, and final charge for their order print("Total Cost is: " '${:,.2f}'.format(costTotal)) print("Shipping Charge for this order is: " '${:,.2f}'.format(shippingCost)) print("Order Cost and Shipping: " '${:,.2f}'.format(orderTotal)) except ValueError: print("Invalid weight. Please choose again.") def summary(): #Shows statistics of the batch including number of orders, total cost of all orders, #and average cost for an order avg = 0 if totalOrders > 0: avg = batchCost / totalOrders print("Number of Orders:",totalOrders) print("Total Cost of All Orders: " '${:,.2f}'.format(batchCost)) print("Average Order Cost: " '${:,.2f}'.format(avg)) def reset(): #Resets the batch statistics to prepare for a new batch global totalOrders totalOrders = 0 global batchCost batchCost = 0 #execute the program as long as "exit" isn't entered: while True: print("Type submit to enter a new order, ") print("type summary to see batch statistics, ") print("type reset to reset statistics, or type exit to exit") line = sys.stdin.readline() if line.strip() == 'submit': submitorder() elif line.strip() == 'summary': summary() elif line.strip() == 'reset': reset() elif line.strip() == 'exit': break else: print("Invalid choice. Try again.")
true
788e78bede5679bcb0f93f4642602520baead921
shirisha24/function
/global scope.py
372
4.1875
4
# global scope:-if we use global keyword,variable belongs to global scope(local) x="siri" def fun(): global x x="is a sensitive girl" fun() print("chinni",x) # works on(everyone) outside and inside(global) x=2 def fun(): global x x=x+x print(x) fun() print(x) # another example x=9 def fun() : global x x=4 x=x+x print(x) fun()
true
9332d185e61447e08fc1209f52ae41cecdc90132
mchoimis/Python-Practice
/classroom3.py
701
4.3125
4
print "This is the grade calculator." last = raw_input("Student's last name: ") first = raw_input("Student's first name: ") tests = [] test = 0 #Why test = 0 ? while True: test = input("Test grade: ") if test < 0: break tests.append(test) total = 0 #Why total = 0 ? for test in tests: total = total + test average = total / len(tests) #Note the number of tests varies. print "*" * 20 print "Student's name: ", first, last num = 1 for test in tests: print "Test {num}: {grade}".format(num=num, grade=test) num = num + 1 print "Average: {average}".format(average=average) #Dont' know format...
true
7fb16ee09b9eb2c283b6e6cd2b2cabab06396a58
mchoimis/Python-Practice
/20130813_2322_len-int_NOTWORKING.py
1,302
4.1875
4
""" input() takes values raw_input() takes strings """ # Asking names with 4-8 letters name = raw_input("Choose your username.: ") if len(name) < 4: print "Can you think of something longer?" if len(name) > 8: print "Uhh... our system doesn't like such a long name." else: print 'How are you, ', name, '.\n' # Asking age in numbers # int() turns objects into integers. It always rounds down. # e.g., 3.0, 23.5 is a float, not an integer. int(3.5) == 3 TRUE age = raw_input("What is your age?\n") if type(age) is str: print 'Please enter in number.' if int(age) >= 24: print 'Congratulations! You are qualified.\n' else: print 'Sorry, you are not qualified.\n' # Asking tel in 10 digits # len() returns the number of digits or letters of an object as integer # len() doesn't take numbers as arguments? tel = raw_input("What is your phone number?\n") while len(tel) != 10: print 'Please enter with 10 digits.' tel = raw_input("Again, what is your phone number?\n") if len(tel) == 10: print 'Your number is', tel, '.\n' ask = raw_input("Can I call you at this number? (Y or N)\n") if ask == 'y': print "Thanks for your input.\n" elif ask == 'Y': print "Thanks for your input.\n" else: print "Thanks, come again.\n"
true
f91a713fff27f167f0c6e9924a2f8b39b5d99cd3
Manuferu/pands-problems
/collatz.py
919
4.40625
4
# Manuel Fernandez #program that asks the user to input any positive integer and outputs the successive values of the following calculation. # At each step calculate the next value by taking the current value and, if it is even, divide it by two, but if it is odd, # multiply it by three and add one. Have the program end if the current value is one. #ask user to insert an integer number num = int(input("Please enter a positive integer:")) div = 2 while num >1: # Keep in the loop in the case that always you have a value greater than 1 if (num % div)==0 : # If the value is even, the reminder will be 0, then enter here num= int(num / 2) #update the value of num dividing by 2 else: # if the reminder is not 0, then is odd, enter here num = (num * 3) + 1#update the value of num multiplying by three and add one print(num)#print num each case it pass through the conditional
true
5a388d39dbab1a59a8bf51df96b26eb51192e70e
manojkumarpaladugu/LearningPython
/Practice Programs/largest_num.py
358
4.53125
5
#Python Program to Find the Largest Number in a List num_list = [] n = input("Enter no. of elements:") print("Enter elements") for i in range(n): num = input() num_list.append(num) print("Input list is: {}".format(num_list)) big = 0 for i in num_list: if i > big: big = i print("Largest number in the list is: {}".format(big))
true
4655d4a9c07fdc83d990068507bb7a614bee7321
manojkumarpaladugu/LearningPython
/Practice Programs/print_numbers.py
310
4.34375
4
#Python Program to Print all Numbers in a Range Divisible by a Given Number print("Please input minimum and maximum ranges") mini = input("Enter minimum:") maxi = input("Enter maximum:") divisor = input("Enter divisor:") for i in range(mini,maxi+1,1): if i % divisor == 0: print("%d" %(i))
true
35b61f8813afb1b2f2fcbed2f6f0e9cb97097503
manojkumarpaladugu/LearningPython
/Practice Programs/second_largest.py
377
4.4375
4
#Python Program to Find the Second Largest Number in a List num_list = [] n = input("Enter no. of elements:") print("Enter elements:") for i in range(n): num_list.append(input()) print("Input list is: {}".format(num_list)) num_list.sort(reverse=True) print("The reversed list is: {}".format(num_list)) print("The second largest number is: {}", num_list[1])
true
56b022638dff063eefcda1b732613b1441b0bde3
vinromarin/practice
/python/coursera-programming-for-everbd/Exercise_6-3.py
402
4.125
4
# Exercise 6.3 Encapsulate this code in a function named count, and generalize it # so that it accepts the string and the letter as arguments. def count(str, symbol): count = 0 for letter in str: if letter == symbol: count = count + 1 return count str_inp = raw_input("Enter string:") smb_inp = raw_input("Enter symbol to count:") cnt = count(str_inp, smb_inp) print cnt
true
e70a3ca8aeb66c993ba550fa3261f51f5c4ea845
PurneswarPrasad/Good-python-code-samples
/collections.py
2,017
4.125
4
#Collections is a module that gives container functionality. We'll discuss their libraries below. #Counter from collections import Counter #Counter is a container that stores the elemnts as dictionary keys and their counts as dictionary values a="aaaaaabbbbcc" my_counter=Counter(a) #makes a dictionary of a print(my_counter.keys()) #prints the keys print(my_counter.values()) #prints the values print(my_counter.most_common(1)) #prints the most common key-value pair. Putting 2 will print the 2 most common key-value pairs, etc. # most_common() returns a list with tuples in it. print(my_counter.most_common(1)[0][0]) #this prints the element with the highest occurence. print(list(my_counter.elements())) #iterates over the whole Counter and returns a list of elements #NamedTuple from collections import namedtuple Point=namedtuple('Point', 'x,y') pt=Point(1,-4) #returns point with x and y values print(pt) #OrderedDict library is used to create dictionaries whose order can be maintained. Python 3.7 and higher already has this built-in function while creating dictionaries. #defaultDict from collections import defaultdict d=defaultdict(int) d['a']=1 d['b']=2 d['c']=1 print(d['d']) #Giving a key-value that is not there in the dictionary will give a default value of the kind of datatype mentioned in the defaultdict() function. #Deque (Double ended queue)-(Insert and remove from both ends) from collections import deque dq=deque() dq.append(1) print(dq) dq.append(2) #appends 2 to the right of 1 print(dq) dq.appendleft(3) #append 3 to the left of 1 print(dq) dq.pop() #removoes an element from the right side print(dq) dq.popleft() #removes an element from the left print(dq) dq.clear() #Clears the entire deque dq.extend(3,1,2,4,5,6) #appends multiple elements to the right print(dq) dq.extendleft(3,1,2,4,5,6) #appends multiple elements to the left print(dq) dq.rotate(1) #Shifts elements to the right side by 1 place print(dq) dq.rotate(-1) #Shifts elements to theleft by 1 place print(dq)
true
3798ed579d458994394902e490bd4afb781c843d
petr-jilek/neurons
/models/separationFunctions.py
1,055
4.25
4
import math """ Separation and boundary function for dataGenerator and separators. Separation function (x, y): Return either 1 or 0 in which region output is. Boundary function (x): Return value of f(x) which describing decision boundary for learning neural network. """ # Circle separation and boundary functions. # Circle with center in x = 0.5 and y = 0.5 and radius 0.3 # (x - 0.5)^2 + (y - 0.5)^2 = 0.3^2 def circleSeparationFunc(x, y): if (((x - 0.5) ** 2) + ((y - 0.5) ** 2)) < (0.3 ** 2): return 1 else: return 0 def circleBoundaryFunction(x): a = (0.3 ** 2) - ((x - 0.5) ** 2) if a > 0: return math.sqrt(a) + 0.5 else: return 0 def circleBoundaryFunction2(x): a = (0.3 ** 2) - ((x - 0.5) ** 2) if a > 0: return -math.sqrt(a) + 0.5 else: return 0 # Linear separation and boundary functions. # Linear function y = f(x) = x def linearSeparationFunc(x, y): if y > x: return 1 else: return 0 def linearBoundaryFunction(x): return x
true
dc11626d5790450752c98f192d4ddee383b21aae
teebee09/holbertonschool-higher_level_programming
/0x03-python-data_structures/3-print_reversed_list_integer.py
227
4.59375
5
#!/usr/bin/python3 def print_reversed_list_integer(my_list=[]): "prints all integers of a list, in reverse order" if my_list: for n in range(0, len(my_list)): print("{:d}".format(my_list[(-n) - 1]))
true
4a4c9eb5d19396aa917b6ea5e9e74ab168b7287d
jramos2153/pythonsprint1
/main.py
2,176
4.40625
4
"""My Sweet Integration Program""" __author__ = "Jesus Ramos" #Jesus Ramos # In this program, users will be able to solve elementary mathematical equations and graph. name = input("Please enter your name: ") print("Welcome", name, "!") gender = input("Before we start, tell us a bit about your self. Are you male or female? ") print("It's nice to know that you are a", gender) age = input("What is your age? ") print("Wow", age, "is so old!") number = input("Thanks for sharing all of this information! What's your favorite number?") print(number, "is a lame number, definitely not my favorite!") operation = input("Since we're talking about numbers, what is your favorite math operation?") print("Nice to know that", operation, "is your favorite, why don't we practice a few problems to get warmed up! ") input("Let's start off with addition, what is 2 + 2?") # using first numeric operator (addition) a = 2 b = 2 print("Let's check, smarty pants. Answer:", a + b) input("How about 2 - 2?") # using second numeric operator (subtraction) print("Hmmm, let's see if you got it! Answer:", a - b) input("Let's kick it up a notch, what's 2 x 2?") # using third numeric operator (multiplication) print("Will you get this one right? Answer:", a * b) input("We're almost done with warm up, what's 2 divided by 2?") print("Let's see if you got it. Answer:", a / b) #line above shows fourth numeric operator (division) input("That was a good warm up, let's step up our game. What is the remainder when you divide 85 by 15?") c = 85 d = 15 print("Annnnddd the answer is: ", c % d) #the line above shows the modular operator being used input("Let's test how good your math skills really are. What is 85 raised to the power of 15?") print("Let's see if you got it. Answer:", c ** d) input("How about this, what is 85 divided by 15, to the nearest whole number when rounded down?") print("The correct answer is:", c // d) #line above shows the floor division numeric operator being used input("That was still easy, what about x + 5 if x = 10?") x = 10 x += 5 print("Let's see, the correct answer is: ", x) #line above shows assignment and shortcut operator being used
true
06f51bde337c4f60bae678ada677654c4bab7afd
ramjilal/python-List-Key-concept
/shallow_and_deep_copy_list.py
1,400
4.53125
5
#use python 2 #first simple copy of a list, List is mutable so it can be change by its copy. x = [1,2,3] y = x # here list 'y' and list 'x' point to same content [1,2,3]. y[0]=5 # so whenever we will change list 'y' than list 'x' would be change. print x #print -> [5,2,3] print y #print -> [5,2,3] #/**************************************************************\ #so to overcome this error we use SHALLOW copy. #/**************************************************************\ #SHALLOW COPY of a LIST from copy import * x = [1,2,3] y = copy(x) y[0]=5 print x #print -> [1,2,3] print y #print -> [5,2,3] #/**************************************************************\ #but shallow copy also fail in deep copy of a list .let an example #/**************************************************************\ from copy import * x = [1,2,[3,4]] y = copy(x) y[0] = 12 y[2][0] = 5 # change value of first element of List [3,4]. print x #print -> [1,2,[5,4]] print y #print -> [12,2,[5,4]] #/**************************************************************\ #so to overcome this error we use DEEP copy. #/**************************************************************\ from copy import * x = [1,2,[3,4]] y = deepcopy(x) y[0] = 12 y[2][0] = 5 # change value of first element of List [3,4]. print x #print -> [1,2,[3,4]] print y #print -> [12,2,[5,4]]
true
00c319cb96b7c226943266109c4e48c723fc4ff5
bhargavpydimalla/100-Days-of-Python
/Day 1/band_generator.py
487
4.5
4
#1. Create a greeting for your program. print("Hello there! Welcome to Band Generator.") #2. Ask the user for the city that they grew up in. city = input("Please tell us your city name. \n") #3. Ask the user for the name of a pet. pet = input("Please tell us your pet's name. \n") #4. Combine the name of their city and pet and show them their band name. band_name = f"{city} {pet}" #5. Make sure the input cursor shows on a new line. print(f"Your band name should be {band_name}.")
true
7a183fdbe4e63ee69c2c204bfaa69be6e7e29933
demelziraptor/misc-puzzles
/monsters/monsters.py
2,634
4.125
4
import argparse from random import randint """ Assumptions: - Two monsters can start in the same place - If two monsters start in the same place, they ignore eachother and start by moving! - All monsters move at each iteration - For some reason, the monsters always move in the same order... - This monster world runs python 2.7 """ class Main: monsters = {} cities = {} def __init__(self): self._parse_args() self._setup_monsters_and_cities() def _parse_args(self): """ get cli arguments and add to arg variable """ parser = argparse.ArgumentParser(description='Monsters, destroying stuff!') parser.add_argument('map_file', metavar='M', type=file, help='the map file') parser.add_argument('--num', metavar='n', type=int, default=6, help='number of monsters to add to the map (default: 6)', dest='num_monsters') self.args = parser.parse_args() print self.args def _setup_monsters_and_cities(self): """ read map file, add map and monster dictionaries """ for line in args.map_file: self._parse_map(line) for num in range(args.num_monsters): self.monsters[num] = random.choice(list(self.cities.keys())) def run_iterations(self): """ do an iteration until all monsters die or each monster moves 10,000 times """ self._move() self._destroy() def print_map(self): """ print out remaining map in correct format """ for city in city_map: #format and print stuff pass def _move(self): """ moves the monsters! """ for monster, location in self.monsters.iteritems(): options = self.cities[location] direction = random.choice(list(options.keys())) new_location = options[direction] self.monsters[monster] = new_location print "Monster #{n} has moved {d} to {l}".format(n = monster, d = direction, l = new_location) def _destroy(self): pass def _parse_map(self, line): """ put map lines into cities dictionary """ line_list = line.split() location = line_list.pop[0] location_dict = {} for road in line_list: position = road.find('=') direction = road[:position] city = road[position+1:] location_dict[direction] = city self.cities[location] = location_dict if __name__ == "__main__": main = Main main.run_iteration() main.print_map()
true
d927fecd196dab0383f022b4a5669a47e7f9fb37
Oyelowo/GEO-PYTHON-2017
/assignment4/functions.py
2,671
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 27 11:15:48 2017 @author: oyeda """ ##You should do following (also criteria for grading): #Create a function called fahrToCelsius in functions.py #The function should have one input parameter called tempFahrenheit #Inside the function, create a variable called convertedTemp to which you should #assign the conversion result (i.e., the input Fahrenheit temperature converted to Celsius) #The conversion formula from Fahrenheit to Celsius is: #Return the converted value from the function back to the user #Comment your code and add a docstring that explains how to use your fahrToCelsius function #(i.e., you should write the purpose of the function, parameters, and returned values) def fahrToCelsius(tempFahrenheit): #define function to convert parameter(tempFahrenheit) """ Function for converting temperature in Fahrenheit to Celsius. Parameters ---------- tempFahrenheit: <numerical> Temperature in Fahrenheit convertedTemp: <numerical> Target temperature in Celsius Returns ------- <float> Converted temperature. """ convertedTemp = (tempFahrenheit - 32)/1.8 #assign the conversion to convertedTemp variable return convertedTemp #return the converted temperature variable #What is 48° Fahrenheit in Celsius? ==> Add your answer here: fahrToCelsius(48) #What about 71° Fahrenheit in Celsius? ==> Add your answer here: fahrToCelsius(71) print ("32 degrees Fahrenheit in Celsius is:", fahrToCelsius(32)) #check what the function does by using help function which returns the docstring comments help(fahrToCelsius) #0 temperatures below -2 degrees (Celsius) #1 temperatures from -2 up to +2 degrees (Celsius) [1] #2 temperatures from +2 up to +15 degrees (Celsius) [2] #3 temperatures above +15 degrees (Celsius) def tempClassifier(tempCelsius): #define the function of the parameter(tempCelsius) """ Function for classifying temperature in celsius. Parameters ---------- tempCelsius: <numerical> Temperature in Celsius Returns ------- <integer> Classified temperature. """ #conditional statements to assign temperatues to different values/classes if tempCelsius < -2: return 0 elif tempCelsius >= -2 and tempCelsius<=2: return 1 elif tempCelsius >= 2 and tempCelsius<=15: return 2 else: return 3 #What is class value for 16.5 degrees (Celsius)? ==> Add your answer here: tempClassifier(16.5) #What is the class value for +2 degrees (Celsius)? ==> Add your answer here: tempClassifier(2) tempClassifier(15)
true
8913aa3c08840276a068ebe6b6d6d69afe519167
AndrewKalil/holbertonschool-machine_learning
/unsupervised_learning/0x02-hmm/1-regular.py
2,114
4.28125
4
#!/usr/bin/env python3 """ Regular Markov chain """ import numpy as np def markov_chain(P, s, t=1): """determines the probability of a markov chain being in a particular state after a specified number of iterations Args: P is a square 2D numpy.ndarray of shape (n, n) representing the transition matrix P[i, j] is the probability of transitioning from state i to state j n is the number of states in the markov chain s is a numpy.ndarray of shape (1, n) representing the probability of starting in each state t is the number of iterations that the markov chain has been through """ if (not isinstance(P, np.ndarray) or not isinstance(s, np.ndarray)): return None if (not isinstance(t, int)): return None if ((P.ndim != 2) or (s.ndim != 2) or (t < 1)): return None n = P.shape[0] if (P.shape != (n, n)) or (s.shape != (1, n)): return None while (t > 0): s = np.matmul(s, P) t -= 1 return s def regular(P): """determines the steady state probabilities of a regular markov chain Args: P is a is a square 2D numpy.ndarray of shape (n, n) representing the transition matrix P[i, j] is the probability of transitioning from state i to state j n is the number of states in the markov chain """ np.warnings.filterwarnings('ignore') # Avoid this warning: Line 92. np.linalg.lstsq(a, b)[0] if (not isinstance(P, np.ndarray)): return None if (P.ndim != 2): return None n = P.shape[0] if (P.shape != (n, n)): return None if ((np.sum(P) / n) != 1): return None if ((P > 0).all()): # checks to see if all elements of P are posistive a = np.eye(n) - P a = np.vstack((a.T, np.ones(n))) b = np.matrix([0] * n + [1]).T regular = np.linalg.lstsq(a, b)[0] return regular.T return None
true
26144b4784b9602b473a8d1da19fe8b568fdc662
blackdragonbonu/ctcisolutions
/ArrayStringQ3.py
948
4.4375
4
''' The third question is as follows Write a method to decide if two strings are anagrams or not. We solve this by maintaining counts of letters in both strings and checking if they are equal, if they are they are anagrams. This can be implemented using a dictionary of byte array of size 26 ''' from collections import defaultdict def hash_solution(str1,str2): dict1=defaultdict(int) dict2=defaultdict(int) if len(str1)==len(str2): for i,letter in enumerate(str1): dict1[letter]+=1 dict2[str2[i]]+=1 for key in dict1: if dict1[key]!=dict2[key]: return False else: return False return True def solutions(str1,str2,method): if method=="hash_solution": check=hash_solution(str1,str2) if check: print("The string are anagrams") else: print("The strigs are not anagrams") if __name__=="__main__": str1=input("Enter first string \n") str2=input("Enter second string \n") solutions(str1,str2,"hash_solution")
true
6aa56313f436099121db045261afc16dbcac9595
Adrianbaldonado/learn_python_the_hard_way
/exercises/exercise_11.py
304
4.25
4
"""Asking Qestions The purpose of this exercise is to utilize all ive learned so far """ print("How old are you?", end=' ') age = (' 22 ') print("How tall are you?", end=' ') height = ( 5 ) print("How do you weigh?", end=' ') weight = ('160') print(f"So, you're{age} old, {height} tall and {weight}")
true
18b210811e067834d980f7b80b886d36e060d65b
deepikaasharma/unpacking-list
/main.py
310
4.34375
4
# Create a list some_list = ['man', 'bear', 'pig'] # Unpack the list man, bear, pig = some_list ''' The statement above is equivalent to: man = some_list[0] bear = some_list[1] pig = some_list[2] ''' # Show that the variables represent the values of the original list print(man, bear, pig) print(some_list)
true
9ee2d6ea090f939e7da651d7a44b204ff648168a
ShumbaBrown/CSCI-100
/Programming Assignment 3/guess_the_number.py
874
4.21875
4
def GuessTheNumber(mystery_num): # Continually ask the user for guesses until they guess correctly. # Variable to store the number of guesses guesses = 0 # loop continually ask the user for a guess until it is correct while (True): # Prompt the user of a guess guess = int(input('Enter a guess: ')) guesses += 1 # Update the user as to whether the guess is too high, too low or correct if (guess > mystery_num): print('Too high!') elif (guess < mystery_num): print('Too low!') else: if (guesses == 1): print('You\'re correct! It took you 1 guess') else: print('You\'re correct! It took you %d guesses' % (guesses)) # If the guess is correct exit the loop break GuessTheNumber(100)
true
d02467d8e5ec22b8daf6e51b007280d3f4c8a245
malav-parikh/python_programming
/string_formatting.py
474
4.4375
4
# leaning python the hard way # learnt the basics # string formatting using f first_name = 'Malav' last_name = 'Parikh' middle_name = 'Arunkumar' print(f"My first name is {first_name}") print(f"My last name is {last_name}") print(f"My middle name is {middle_name}") print(f"My full name is {first_name} {middle_name} {last_name}") # string formatting using format function sentence = "My full name is {} {} {}" print(sentence.format(first_name,middle_name,last_name))
true
e4e80522ce19e03c1c6bceee954741d324d79b44
ffabiorj/desafio_fullstack
/desafio_parte_1/question_1.py
504
4.1875
4
def sum_two_numbers(arr, target): """ The function receives two parameters, a list and a target. it goes through the list and checks if the sum of two numbers is equal to the target and returns their index. """ number_list = [] for index1, i in enumerate(arr): for index2, k in enumerate(arr[index1+1:]): if i + k == target: number_list.append(arr.index(i)) number_list.append(arr.index(k)) return number_list
true
58f0290c093677400c5a85267b1b563140feda85
FrancescoSRende/Year10Design-PythonFR
/FileInputOutput1.py
1,512
4.53125
5
# Here is a program that shows how to open a file and WRITE information TO it. # FileIO Example 3 # Author: Francesco Rende # Upper Canada College # Tell the user what the program will do... print ("This program will open a file and write information to it") print ("It will then print the contents to the screen for you to see") # So as before we will still have to open a file, but this time we specify for the parameter either "w" or "a" # "w" means we are going to "write" information which overwrite everything that was in the file from before. # "a" means that we "append" which will add to the end of existing information. def addSong(): song = str(input("What is your favorite song?")) file = open("FileInfo1.txt", "a") file.write ("\n"+song) file.close() file = open("FileInfo1.txt", "r") print (file.read()) addMore = input("Would you like to add another song? (y/n) \n") if addMore.lower() == "y": addSong() else: print("Thanks for your time!") def giveSongs(): file = open("FileInfo1.txt", "r") print(file.read()) def doSomething(): choice = int(input("Would you like to:\n1. Add a new song or\n2. Get the list of songs\n")) if choice == 1: addSong() elif choice == 2: giveSongs() else: print("Invalid choice.") doItAgain = input("Would you like to try again? (y/n) \n") if doItAgain.lower() == "y": doSomething() else: print("Thanks for your time!") doSomething() # This is a way to gracefully exit the program input("Press ENTER to quit the program")
true
2306ffb05eecd0dc048f36c8359b7684178f0634
MuhammadRehmanRabbani/Python
/Average of 2D Array python/average.py
1,260
4.28125
4
# defining the average function def average(matrix,matrix_size): my_sum = 0 # declaring variable to store sum count = 0 # declaring variable to count total elements of 2D array # this for loop is calculating the sum for i in range(0, matrix_size): for j in range(0, matrix_size): my_sum = my_sum+ int(matrix[i][j]) count = count+1 # calculating the average average = my_sum/count return average; # defining the main function def main(): matrix = [] #declaring matrix ave = 0 matrix_size=int(input("Enter N for N x N matrix : ")) #prompt print("Enter {} Elements in Square Matrix:".format(matrix_size)) # prompt #this for loop is taking elements from user and storing them to 2D array for i in range(0, matrix_size): row = [] for j in range(0, matrix_size): row.append(input()) matrix.append(row) print("You entered:") #prompt #printing 2D array for i in range(0, matrix_size): print(" ".join(matrix[i])) # calling the average function to find average of matrix elements ave = average(matrix,matrix_size) # printing average print('Average is: ',ave) if __name__ == "__main__": main()
true
356a8c8ecc88afd964c5a83dc438890a3326b483
girishsj11/Python_Programs_Storehouse
/Daily_coding_problems/daily_coding_2.py
737
4.125
4
''' Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6] ''' print("Enter the list elements with space : ") input_list = list(map(int, input().split())) output_list=list() temp=1 for i in input_list: temp*=i print("multiplication of all the elements in a given list is:\n",temp) for i in input_list: output_list.append(temp//i) print("input given user list is:\n",input_list) print("output list is:\n",output_list)
true
9d3dad6f365a6e73d00d90411f80a1a6e165f0cf
girishsj11/Python_Programs_Storehouse
/codesignal/strstr.py
1,378
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 26 12:33:18 2021 @author: giri """ ''' Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview. Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1. Example For s = "CodefightsIsAwesome" and x = "IA", the output should be strstr(s, x) = -1; For s = "CodefightsIsAwesome" and x = "IsA", the output should be strstr(s, x) = 10. Input/Output [execution time limit] 4 seconds (py3) [input] string s A string containing only uppercase or lowercase English letters. Guaranteed constraints: 1 ≤ s.length ≤ 106. [input] string x String, containing only uppercase or lowercase English letters. Guaranteed constraints: 1 ≤ x.length ≤ 106. [output] integer An integer indicating the index of the first occurrence of the string x in s, or -1 if s does not contain x. ''' def strstr(s, x): try: return (s.index(x)) except ValueError: return -1 if __name__ == "__main__": print(strstr('CodefightsIsAwesome','IA')) print(strstr('CodefightsIsAwesome','IsA'))
true
1f75ec5d58684cd63a770bd63c7aab3ee7b26de6
girishsj11/Python_Programs_Storehouse
/codesignal/largestNumber.py
569
4.21875
4
''' For n = 2, the output should be largestNumber(n) = 99. Input/Output [execution time limit] 4 seconds (py3) [input] integer n Guaranteed constraints: 1 ≤ n ≤ 9. [output] integer The largest integer of length n. ''' def largestNumber(n): reference = '9' if(n==1): return int(reference) elif(n>1 and n<=10): return int(reference*n) else: return ("Exceeded/below the range value") if __name__ == "__main__": n = int(input("Enter the number to get its largest number of digits : ")) print(largestNumber(n))
true
478ed1b0685ac4fda3e3630472b2c05155986d50
girishsj11/Python_Programs_Storehouse
/codesignal/Miss_Rosy.py
2,510
4.15625
4
''' Miss Rosy teaches Mathematics in the college FALTU and is noticing for last few lectures that the turn around in class is not equal to the number of attendance. The fest is going on in college and the students are not interested in attending classes. The friendship is at its peak and students are taking turns for classes and arranging proxy for their friends. They have been successful till now and have become confident. Some of them even call themselves pro. One fine day, the proxy was called in class as usual but this time Miss Rosy recognized the student with his voice. When caught, the student disagreed and said that it was a mistake and Miss Rosy has interpreted his voice incorrectly. Miss Rosy let it go but thought of an idea to give attendance to the students present in class only. In the next lecture, Miss Rosy brought a voice recognition device which would save the voice of students as per their roll number and when heard again will present the roll number on which it was heard earlier. When the attendance process is complete, it will provide a list which would consist of the number of distinct voices. The student are unaware about this device and are all set to call their proxies as usual. Miss Rosy starts the attendance process and the device is performing its actions. After the attendance is complete, the device provides a list. Miss Rosy presents the list to you and asks for the roll numbers of students who were not present in class. Can you provide her with the roll number of absent students in increasing order. Note: There is at least one student in the class who is absent. Input Format The first line of input consists of the actual number of students in the class, N. The second line of input consists of the list (N space-separated elements) presented to you by Miss Rosy as recorded by the voice recognition device. Constraints 1<= N <= 100 1<= List_elements <=N Output Format Print the roll number of students who were absent in class separated by space. Example : Input 7 1 2 3 3 4 6 4 Output 5 7 ''' def main(N,List_elements): List_elements.sort() k = List_elements[0] out_elements = list() for i in List_elements: if(k not in List_elements): out_elements.append(k) k +=1 for element in out_elements: print(element,end=' ') if __name__ == "__main__": N = int(input()) List_elements = list(map(lambda x:int(x) , input().split(' '))) main(N,List_elements)
true
b986d60ff29d4cf7ff66d898b5f0f17a29a168cb
girishsj11/Python_Programs_Storehouse
/prime_numbers_generations.py
577
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 14 16:00:24 2021 @author: giri """ def is_prime(num): """Returns True if the number is prime else False.""" if num == 0 or num == 1: return False for x in range(2, num): if num % x == 0: return False else: return True if __name__ == "__main__": lower = int(input("Enter the lower range to generate prime numbers : ")) upper = int(input("Enter the upper range to generate prime numbers : ")) list(filter(is_prime,range(lower,upper)))
true
8b6aad04e70312c2323d1a8392cef1bc10587b2e
Stone1231/py-sample
/loop_ex.py
413
4.125
4
for i in [0, 1, 2, 3, 4]: print(i) for i in range(5): print(i) for x in range(1, 6): print(x) for i in range(3): print(i) else: print('done') #A simple while loop current_value = 1 while current_value <= 5: print(current_value) current_value += 1 #Letting the user choose when to quit msg = '' while msg != 'quit': msg = input("What's your message? ") print(msg)
true
ded47265e7eda94698d63b24bd4665b2e8afb16e
mikvikpik/Project_Training
/whitespace.py
308
4.1875
4
"""Used in console in book""" # Print string print("Python") # Print string with whitespace tab: \t print("\tPython") # Print multiple whitespaces and strings print("Languages:\nPython\nC\nJavaScript") # variable set to string and call variable without print favorite_language = "python" favorite_language
true
7791023ad7a3561d91401b22faeff3fce3a1c7c8
EoinMcKeever/Test
/doublyLinkedListImplemention.py
1,028
4.4375
4
class Node: def __init__(self, data): self.data = data self.next = None self.previous = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None #insert at tail(end) of linked list def insert(self, data): new_node = Node(data) if self.head is None: self.head = new_node self.tail = new_node else: new_node.previous = self.tail self.tail.next = new_node self.tail = new_node # we can traverse a doubly linked list in both directions def traverse_forward(self): actual_node = self.head while actual_node is not None: print("%d" % actual_node.data) actual_node = actual_node.next def traverse_backward(self): actual_node = self.tail while actual_node is not None: print("%d" % actual_node.data) actual_node = actual_node.previous if __name__ == '__main__': linked_list = DoublyLinkedList() linked_list.insert(1) linked_list.insert(2) linked_list.insert(3) linked_list.traverse_forward() linked_list.traverse_backward()
true
6eb48816205257b528b1aefd8f03fa8206716aa9
sayee2288/python-mini-projects
/blackjack/src/Deck.py
1,401
4.1875
4
''' The deck class simulates a deck of cards and returns one card back to the player or the dealer randomly. ''' import random class Deck: ''' The deck class creates the cards and has functions to return a card or shuffle all cards ''' def __init__(self): print('Deck is ready for the game') self.card = '' self.shape = '' self.deck = { 0: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'], 1: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'], 2: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'], 3: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'] } self.suit = { 0: 'Spades', 1: 'Hearts', 2: 'clubs', 3: 'diamonds' } def pick_card(self): while True: a = random.randint(0, 3) b = random.randint(0, len(self.deck[a])-1) self.card = self.deck[a][b] if self.card in self.deck[a]: del self.deck[a][b] break else: continue print('You retrieved this card: {} of {}' .format(self.card, self.suit[a])) return self.card, self.suit[a] def shuffle(self): print('Deck has been shuffled') self.__init__() if __name__ == "__main__": my_deck = Deck() my_deck.pick_card()
true
0240991d2a500c398cfd17ea1ac3616d00dd09dd
Spandan-Madan/python-tutorial
/8_while_loops.py
2,147
4.40625
4
import random # ** While Loops ** # What if you want your code to do something over and over again until some # condition is met? # For instance, maybe you're writing code for a timer # and you want to keep checking how much time has passed until you have waited # the correct amount of time. # Then you should use a while loop. Check out the example: time_to_count = 10 seconds_passed = 0 while seconds_passed < time_to_count: # this is called the condition print("ticks_passed:", seconds_passed) seconds_passed += 1 # increase seconds_passed by 1 print("Timer done!") print("\n") # At the beginning of the loop, the condition (`seconds_passed < time_to_count`) # is evaluated. If the condition is `True`, then the body of the loop--the # indented block that follows the while condition--is run. If the condition # is `False`, then it continues with the rest of the code. # A really important thing to consider when writing a while loop is # "termination": making sure that at some point, the condition will evaluate to # `False`. Otherwise, the loop will run forever! # ** Break ** # There is one exception to the idea of termination. Consider this while loop: n_tries = 0 while True: n_tries += 1 n = random.randint(1, 10) # chooses a random number between 1 and 10 if n == 10: break print("Outside of loop; took", n_tries, "tries") # Clearly, the condition here will never be `False`! They key here is the word # `break`. This keyword causes Python to "break" out of the loop and continue # with the next line of code. Note that writing a "while True" loop can be # dangerous, because it is not clear when the loop will terminate. If possible, # state the condition explicitly. You should reserve "while True" for # situations where you really do have to continue doing something forever, or # where it is not clear how many times you will have to do something. # ** Exercises ** # 1. Write a while loop that prints all the numbers from 1 to 10. # Your code here. # 2. What is wrong with this code? # count = 10 # while (count < 100): # print(count) # count = count - 1
true
e6bed67b87876e59d12ad8a0e2776649b169f3bf
Spandan-Madan/python-tutorial
/5_booleans.py
1,334
4.40625
4
# ** Boolean Comparisons ** print("Examples of boolean comparisons") # Python also supports logical operations on booleans. Logical operations take # booleans as their operands and produce boolean outputs. Keep reading to learn # what boolean operations Python supports. # And # The statement `a and b` evaluates to True only if both a and b are `True`. # Use the keyword `and` to perform this operation print("True and True is", True and True) print("False and False is", False and False) print("True and False is", True and False) # Or # The statement `a or b` evaluates to True if a is `True` or b is `True`. # use the keyword `or` to perform this operation print("True or True is", True or True) print("False or False is", False or False) print("True or False is", True or False) # Not # The keyword `not` flips a boolean from True to False or vice versa print("not True is", not True) print("not False is", not False) print("\n") # ** Exercises ** print("Output of exercises") # 1. Modify line 38 below so that it only prints `True` if all of a, b, and c # are True. Modify the three values to test your code. a = True b = True c = True print(False) # 2. Modify line 42 so that it only prints `True` if x is less than 10 or # greater than 100. Change the value of x to test your code. x = 0 print(False)
true
b6965d0d5ebe028780d4ba63d10d1c159fab97c7
jasonwee/asus-rt-n14uhp-mrtg
/src/lesson_text/re_groups_individual.py
407
4.1875
4
import re text = 'This is some text -- with punctuation.' print('Input text :', text) # word starting with 't' then another word regex = re.compile(r'(\bt\w+)\W+(\w+)') print('Pattern :', regex.pattern) match = regex.search(text) print('Entire match :', match.group(0)) print('Word starting with "t":', match.group(1)) print('Word after "t" word :', match.group(2))
true
8025c47447a18c0f93b4c59c6c1191c6b0c6454a
shail0804/Shail-Project
/word_series.py
2,137
4.125
4
def Character_to_number(): """ This function converts a given (User Defined) Character to Number\ as per the given Pattern (2*(Previous Character) + counter) """ nb = input('please enter the character: ') nb = nb.upper() count = 1 sum = 0 for s in range(65,ord(nb)+1): sum = sum*2+count count = count+1 print ('The Value of ',chr(s),':',sum,' \n') def String_to_number(): """ This function converts a given (User Defined) String to Number\ as per the given Pattern (2*(Previous Character) + counter)\ This function calculates the individual value of the letters of the String\ and then gives us the Sum of all the letters, which is the Numeric Value of the String. """ alpha = input('Please enter a word: ') alpha = alpha.upper() final_sum = 0 for s in alpha: count = 1 sum = 0 for i in range(65,ord(s)+1): sum = sum*2 + count count = count+1 print('for',s,'value is',sum) final_sum = final_sum+sum print('The sum of given words is: ', final_sum,' \n') def Digit_to_string(): """This function Converts a given Number into String :/ with character value calculated as per the given pattern (2*(Previous Character) + counter) """ numb = int(input('Enter the number: ')) temp = numb while (temp >= 1): sum = 0 i = 1 prev_char = '' prev = 0 l=0 while (temp >= sum): prev = sum if (prev == 0): prev_char = '' elif(prev ==1): prev_char= 'A' else: l= i-2 prev_char = chr(ord('A') + l) sum = sum *2 + i i=i+1 if (temp==numb): word = prev_char else: word = word + prev_char temp = temp -prev print('The Word is: ',word, ' \n') if __name__=='__main__': Character_to_number() String_to_number() Digit_to_string()
true
e8596535535979655079184dbf2d61899b8610b3
diptaraj23/TextStrength
/TextStrength.py
324
4.25
4
#Calculating strength of a text by summing all the ASCII values of its characters def strength (text): List=[char for char in text] # storing each character in a list sum=0 for x in List: sum=sum+ord(x) #Extracting ASCII values using ord() function and then adding it in a loop return sum
true
1775f4ecf0c6270b6209dd68358899fa92c8387c
jasonchuang/python_coding
/27_remove_element.py
897
4.40625
4
''' Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. ''' def removeElement(nums, val): index = 0 for i in range(0, len(nums)): print "inside range val: {} {}:".format(val, nums[i]) if nums[i] != val: print "index: {} :".format(index) nums[index] = nums[i] index += 1 return index #given = [3,2,2,3] given = [0,1,2,2,3,0,4,2] #target = 3 target = 2 print removeElement(given, target) print given
true