blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0ebc30ff3f710310db361194090f163abcf9e8c7
MarsWilliams/PythonExercises
/How-to-Think-Like-a-Computer-Scientist/DataFiles.py
2,582
4.34375
4
#Exercise 1 #The following sample file called studentdata.txt contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student. #joe 10 15 20 30 40 #bill 23 16 19 22 #sue 8 22 17 14 32 17 24 21 2 9 11 17 #grace 12 28 21 45 26 10 #john 14 32 25 16 89 #Using the text file studentdata.txt write a program that prints out the names of students that have more than six quiz scores. infile = open("studentdata.txt", "r") aline = infile.readline() #could omit this line if using a for loop while aline: data = aline.split() if len(data[1:]) > 6: print data[0] aline = infile.readline() #could omit this line if using a for loop infile.close() #Exercise 2 #Using the text file studentdata.txt (shown in exercise 1) write a program that calculates the average grade for each student, and print out the student’s name along with their average grade. infile = open("studentdata.txt", "r") aline = infile.readline() while aline: aline = (aline.rstrip()).split() scores = 0 for a in aline[1:]: scores = scores + int(a) print "%s's average score is %s." % (aline[0].capitalize(), str(int(scores / len(aline[1:])))) aline = infile.readline() infile.close() #Exercise 3 #Using the text file studentdata.txt (shown in exercise 1) write a program that calculates the minimum and maximum score for each student. Print out their name as well. infile = open("studentdata.txt", "r") aline = infile.readline() while aline: aline = (aline.rstrip()).split() print "%s's maximum score is %s and h/er minimum score is %s." % (aline[0].capitalize(), max(aline[1:]), min(aline[1:])) aline = infile.readline() infile.close() #At the bottom of this page is a very long file called mystery.txt The lines of this file contain either the word UP or DOWN or a pair of numbers. UP and DOWN are instructions for a turtle to lift up or put down its tail. The pairs of numbers are some x,y coordinates. Write a program that reads the file mystery.txt and uses the turtle to draw the picture described by the commands and the set of points. infile = open("mystery.txt", "r") aline = infile.readline() import turtle wn = turtle.Screen() ben = turtle.Turtle() while aline: aline = (aline.rstrip()).split() if aline[0] == "UP": ben.penup() elif aline[0] == "DOWN": ben.pendown() else: ben.goto(int(aline[0]), int(aline[1])) aline = infile.readline() infile.close()
true
e59b96d2f3400e5f8b52cb8a26ee3e7479913d29
dhoshya/grokking-algorithms
/quickSort.py
440
4.15625
4
# D&C def quickSort(arr): # base case if len(arr) < 2: return arr else: pivot = arr[0] # using list comprehension less = [i for i in arr[1:] if i <= pivot] # using normal syntax greater = list() for i in arr[1:]: if i >= pivot: greater.append(i) return quickSort(less) + [pivot] + quickSort(greater) print(quickSort([10, 5, 2, 3]))
true
e44f1c6cef22aedc4f5114c69f0260f2a37646a9
AniketKul/learning-python3
/ordereddictionaries.py
849
4.3125
4
''' Ordered dictionaries: they remember the insertion order. So when we iterate over them, they return values in the order they were inserted. For normal dictionary, when we test to see whether two dictionaries are equal, this equality os only based on their K and V. For ordered dictionary, when we test to see whether two dictionaries are equal, insertion order is considered as an equality test between two OrderedDicts with same key and values but different insertion order. ''' od1 = OrderedDict() od1['one'] = 1 od1['two'] = 2 od2 = OrderedDict() od2['two'] = 2 print(od1 == od2) #Output: False ''' OrderedDict is often used in conjunction with sorted method to create a sorted dictionary. For example, ''' od3 = OrderedDict(sorted(od1.items(), key = lambda t : (4*t[1]) - t[1]**2)) od3.values() #Output: odict_values([6, 5, 4, 1, 3, 2])
true
f4451ce74fd1b6d16856f09f21f2eee9ae8c8f9a
jorricarter/PythonLab1
/Lab1Part2.py
523
4.125
4
#todo get input currentPhrase = input("If you provide me with words, I will convert them into a camelCase variable name.\n") #todo separate by word #found .title @stackoverflow while looking for way to make all lowercase wordList = currentPhrase.title().split() #todo all lowercase start with uppercase #found .title() to acheive this #todo first letter of first word should be lower case wordList[0] = wordList[0].lower() #todo join words into single word newName = ''.join(wordList) #todo print to screen print (newName)
true
d51e758b43989603f02fc40214a03a970be2d4d1
KishorP6/PySample
/LC - Decission.py
1,362
4.34375
4
##Input Format : ##Input consists of 8 integers, where the first 2 integers corresponds to the fare and duration in hours through train, the next 2 integers corresponds to the fare and duration in hours though bus and the next 2 integers similarly for flight, respectively. The last 2 integers corresponds to the fare and duration weightage, respectively. ##Output Format : ## Output is a string that corresponds to the most efficient means of transport. The output string will be one of the 3 strings - "Train Transportation" , "Bus Transportation" or "Flight Transportation". train_fare = int(input()) train_duration = int(input()) bus_fare = int(input()) bus_duration = int(input()) flight_fare = int(input()) flight_duration = int(input()) fare_weightage = int (input()) duration_weightage = int (input()) train_weightage = int(train_fare*fare_weightage+ train_duration*duration_weightage) bus_weightage = int(bus_fare*fare_weightage+ bus_duration*duration_weightage) flight_weightage = int(flight_fare*fare_weightage+ flight_duration*duration_weightage) if flight_weightage < train_weightage and flight_weightage < bus_weightage : print ("Flight Transportation") else: if bus_weightage < train_weightage and bus_weightage < flight_weightage : print ( "Bus Transportation") else : print ( "Train Transportation")
true
ddeadc23b291498c7873533b16bf78c945670b2c
CStage/MIT-Git
/MIT/Lectures/Lecture 8.py
1,429
4.125
4
#Search allows me to search for a key within a sorted list #s is the list and e is what we search for #i is the index, and the code basically says that while i is shorter than the the #length of the list and no answer has been given yet (whether true or false) #then it should keep looking through s to see if it can find e. #i=0 means that we START looking at index 0 #For every run-through where we don't find what we need, we look for the key at #index that is 1 higher than the previous def Search(s,e): answer=None i = 0 numCompares=0 while i < len(s) and answer==None: numCompares+=1 if e==s[i]: answer=True elif e<s[i]: answer=False i+=1 print(answer,numCompares) #If you are working with a sorted list it is a great idea to make the search START #at the middle of the list. That way you can throw half the list out at each #run-through. Basically, using a log-function is worth way more for you. def bSearch(s, e, first, last): print(first, last) if (last-first)<2: return s[int(first)] ==e or s[int(last)]==e mid=first+(last-first)/2 if s[int(mid)]==e: return True if s[int(mid)]>e: return bSearch(s,e, first, mid-1) return bSearch(s,e,mid+1,last) list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def Search1(s,e): print(bSearch(s,e,0,len(s)-1)) print("Search complete") Search1(list,13)
true
9e11800cd87f7fa6c523cf6e0f6869e2ce59fb66
jacobeskin/Moon-Travel
/kuumatka_xv.py
1,828
4.25
4
import itertools import numpy as np import matplotlib.pyplot as plot # Numerical calculation and visualisation of the change in position # and velocity of a spacecraft when it travels to the moon. Newtons # law of gravitation and second law of motion are used. Derivative is # evaluated with simple Euler method. This project was originally # done in Finnish, the variable names reflect that. # Define constants and vectors for position and velocity g = 6.674*(10**(-11)) # Gravitation constant Maa = 5.974*(10**24) # Earths mass Kuu = 7.348*(10**22) # Moons mass X = 376084800 # Target distance, low orbit of moon (Wikipedia) n = 0 # Keeps tab on how many time steps has gone r1 = 6578100 # Distance from Earths center in the beginning v1 = 12012 # Starting velocity + 10% V = np.array([v1]) # Vector that will house the values of velocity R = np.array([r1]) # Vector that will house the values of distance dt = 10 # Length of time step in seconds # Iterate our way to the moon! for i in itertools.count(): n = n+1 # New distance r = r1+v1*dt R = np.append(R,r) # Updated acceleration b = Kuu/((3844*(10**5)-r1)**2) c = Maa/(r1**2) A = g*(b-c) # New velocity v = v1+A*dt V = np.append(V,v) # Update position and velocity r1 = r v1 = v # When arriving to the moon if r>=X: break T = (n*dt)/3600 # Travel time in hours print(T) # Plot the graphs of position and velocity as function of time plot.figure(1) plot.subplot(211) plot.plot(R) plot.xlabel('Aika, s') # "Aika" means time plot.ylabel('Matka, m') # "Matka" means distance plot.subplot(212) plot.plot(V) plot.xlabel('Aika, s') plot.ylabel('Nopeus, m/s') # "Nopeus" means velocity plot.show()
true
e050bf9dbde856f206bac59513c3a19e47e23a92
nwelsh/PythonProjects
/lesson3.py
408
4.28125
4
#Lesson 3 I am learning string formatting. String formatting in python is very similar to C. #https://www.learnpython.org/en/String_Formatting name = "Nicole" print("Hello, %s" % name) #s is string, d is digit, f is float (like c) age = 21 print("%s is %d years old" % (name, age)) data = ("Nicole", "Welsh", 21.1) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data)
true
cad277b1a2ca68f6a4d73edc25c2680120b88137
tanvirtin/gdrive-sync
/scripts/File.py
1,380
4.125
4
''' Class Name: File Purpose: The purpose of this class is represent data of a particular file in a file system. ''' class File: def __init__(self, name = None, directory = None, date = None, fId = None, folderId = None, extension = ""): self.__name = name self.__directory = directory self.__date = date self.__id = fId self.__folderId = folderId self.__mimeType = extension def __repr__(self): return self.getName ''' Name: getName Purpose: A getter method for the name of the file. return: private attribute __name ''' @property def getName(self): return self.__name ''' Name: getDir Purpose: a getter method for the name of the directory the file is in. return: private attribute __directory ''' @property def getDir(self): return self.__directory ''' Name: getLastModified Purpose: a getter method for the date that the file was last modified at return: private attribute __date ''' @property def getLastModified(self): return self.__date ''' Name: getDetails Purpose: Returns the full file address of a file object. return: a string representing the full file details ''' def getDetails(self): return self.getDir + self.getName @property def getFileId(self): return self.__id @property def getFolderId(self): return self.__folderId @property def getMimeType(self): return self.__mimeType
true
caa33fdad5d9812eb473d03a497c46d6a0ad71f2
YasirQR/Interactive-Programming-with-python
/guess_number.py
1,963
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import math import random import simplegui num_range = 100 count = 0 stop = 7 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number global count count =0 secret_number = random.randrange(num_range) print "New Game! Guess a number!" print "" # define event handlers for control panel def range100(): global num_range global stop global count num_range = 100 stop = 7 print "" new_game() def range1000(): global num_range global stop global count num_range = 1000 stop = 10 print "" new_game() def input_guess(guess): print "" print "Guess was " + guess global count count +=1 if int(guess) == secret_number: print "You guessed right!!!" print "" new_game() elif count == stop: print("GAME OVER! You ran out of guesses") print "" new_game() elif int(guess) > secret_number: print "Lower!" print ("You have " +str(stop - count) + " guesses left") else: print "Higher!" print ("You have " +str(stop - count) + " guesses left") # create frame f = simplegui.create_frame("GUESSER", 200,200) f.add_input("Your Guess (Press Enter)", input_guess, 200) blank = f.add_label('') label1 = f.add_label('New Game: Change range') f.add_button("Number (0,100)",range100, 200) f.add_button("Number (0,1000)", range1000, 200) # register event handlers for control elements and start frame # call new_game new_game() # always remember to check your completed program against the grading rubric
true
1c10a0791d3585aa56a5b6c88d133b7ea98a8b24
haydenbanting/LawnBot
/Mapping/mapping_functions/matrix_builder.py
2,029
4.25
4
''' Function for creating matricies for map routing algorithms Author: Kristian Melo Version: 15 Jan 2018 ''' ######################################################################################################################## ##Imports ######################################################################################################################## from Mapping.constants import constants as c ######################################################################################################################## #To use Dijkstras algorithm we need a list of "edges". this is a n x 3 matrix where each row contains the start point, #end point, and distance. def build_edges_matrix(lawn): edges = [] #loop through all nodes in list for nodes in lawn: #loop through all the neighbors in a given node for i in nodes.neighbors: #add new edge between the given node and its neighbore to the list of edges #note the length is always gridsize since neighbores are always adjacent squares edges.append([str(nodes.location), str(i), c.GRIDSIZE]) return edges ######################################################################################################################## ''' #legacy code, keeping in case of future changes def build_distance_matrix(lawn): movelist = [] obslist = [] for node in lawn: if node.type != 9: movelist.append(node) else: obslist.append(node) distance = np.zeros((len(movelist), len(movelist))) i,j = 0,1 while i < len(movelist): while j < len(movelist): x1 = movelist[i].location[0] x2 = movelist[j].location[0] y1 = movelist[i].location[1] y2 = movelist[j].location[1] r = m.hypot(x2-x1,y2-y1) if col.obstacleDetection(obslist, x1, y1, x2, y2) == False: distance[i, j] = r j += 1 i += 1 j = i + 1 return distance '''
true
66d85d4d119be319d62c133c1456c91a630291db
10zink/MyPythonCode
/HotDog/hotdog.py
1,624
4.1875
4
import time import random import Epic # Programmed by Tenzin Khunkhyen # 3/5/17 for my Python Class # HotDogContest #function that checks the user's guess with the actual winner and then returns a prompt. def correct(guess, winner): if guess.lower() == winner.lower(): statement = "\nYou gusses right, %s wins!" %winner else: statement = "\nYou guess wrong, the winner was %s" %winner return statement #main function which runs the program def main(): tom = 0 sally = 0 fred = 0 guess = Epic.userString("Pick a winnder (Tom, Sally, or Fred: ") print "Ready, Set, Eat!\n" keepGoing = True while keepGoing: #I created three seperate random number ranges to procduce different numbers for each contestant tNumber = random.randrange(1,6) sNumber = random.randrange(1,6) fNumber = random.randrange(1,6) tom = tom + tNumber sally = sally + sNumber fred = fred + fNumber time.sleep(2) print "\nchomp.. chomp... chomp... \n" print "Tom has eaten %s hot dogs!" %tom print "Sally has eaten %s hot dogs!" %sally print "Fred has eaten %s hot dogs!" %fred #the following if statement then determined the winner if tom >= 50: winner = "Tom" keepGoing = False elif sally >= 50: winner = "Sally" keepGoing = False elif fred >= 50: winner = "Fred" keepGoing = False print "%s" %correct(guess,winner) main()
true
0b18e86b3b5c414604e6cf3e35618770998043a9
10zink/MyPythonCode
/Exam5/Store.py
1,448
4.46875
4
import json import Epic # Programmed by Tenzin Khunkhyen # 4/16/17 for my Python Class # This program is for Exam 5 # This program just reads a json file and then prints information from a dictionary based on either # a category search or a keyword search. #This function reads the json file and converts it into a dictionary def fileReader(): jsonTxt = "" f = open('PetStore.json') for line in f: line = line.strip() jsonTxt = jsonTxt + line petStore = json.loads(jsonTxt) return petStore #This function takes in a dictionary and also string "a" def sorter(petStore, a): answers = "" #This if statement is for category search if(a == 'c'): userInput = Epic.userString("Enter a category: ") print "" for cat in petStore: if(cat["Category"].lower() == userInput): print "%s - $%s" % (cat["Product"], cat["Price"]) #This if statement is for keyword search if(a == 'k'): userInput = Epic.userString("Enter a keyword: ") print "" for key in petStore: if(userInput in key["Product"].lower()): print "%s - $%s" % (key["Product"], key["Price"]) return answers def main(): b = Epic.userString("Search by category (c) or keyword (k)?") a = b.lower() #This line calls the method d = sorter(fileReader(), a) print d main()
true
c601c685111500976d62442a4e2be11bb928ee77
justdave001/Algorithms-and-data-structures
/SelectionSort.py
524
4.1875
4
""" Sort array using brute force (comparing value in array with sucessive values and then picking the lowest value """ #Time complexity = O(n^2) #Space complexity = O(1) def selection_sort(array): for i in range(len(array)): for j in range(i+1, len(array)): if array[i] > array[j]: array[i], array[j] = array[j], array[i] return array if __name__ == "__main__": array = list(map(int, input().rstrip().split())) print(selection_sort(array))
true
3c8df58e0135bd806acd5735d66bf42e718cd49d
signoreankit/PythonLearn
/numbers.py
551
4.1875
4
""" Integer - Whole numbers, eg: 0, 43,77 etc. Floating point numbers - Numbers with a decimal """ # Addition print('Addition', 2+2) # Subtraction print('Subtraction', 3-2) # Division print('Division', 3/4) # Multiplication print('Multiplication', 5*7) # Modulo or Mod operator - returns the remained after the division print('Modulo', 97 % 5) # Exponent - a**b represents a to the power b print('Exponent', 2 ** 4) # Floor Division - Returns the left side of the decimal or simple integer if no decimal print('Floor Division', 9 // 2)
true
3b6559c4f2511789a65a458111ba32103cf340a6
tjrobinson/LeoPython
/codes.py
2,373
4.21875
4
for x in range(0,2): userchoice = input("Do you want to encrypt or decrypt?") userchoice = userchoice.lower() if userchoice == "encrypt": Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" StringToEncrypt = input("Please enter a message to encrypt: ") StringToEncrypt = StringToEncrypt.upper() ShiftAmount = int(input("Please enter a number from 1 to 25 to be your key. ")) if 25 < ShiftAmount: print("Uh Oh, number was too big") StringToEncrypt = input("Please enter the message to encrypt: ") StringToEncrypt = StringToEncrypt.upper() ShiftAmount = int(input("Please enter a number from 1 to 25 to be your key. ")) encryptedString = "" for currentCharacter in StringToEncrypt: position = Alphabet.find(currentCharacter) newPosition = position + ShiftAmount if currentCharacter in Alphabet: encryptedString = encryptedString + Alphabet[newPosition] else: encryptedString = encryptedString + currentCharacter print("Your message is", encryptedString) if userchoice == "decrypt": Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" StringToEncrypt = input("Please enter the message to decrypt: ") StringToEncrypt = StringToEncrypt.upper() ShiftAmount = int(input("Please enter the key to decrypt. ")) if 25 < ShiftAmount: print("Uh Oh, number was too big") StringToEncrypt = input("Please enter the message to decrypt: ") StringToEncrypt = StringToEncrypt.upper() ShiftAmount = int(input("Please enter the key to decrypt. ")) ShiftAmountB = ShiftAmount + ShiftAmount ShiftAmount = ShiftAmount - ShiftAmountB encryptedString = "" for currentCharacter in StringToEncrypt: position = Alphabet.find(currentCharacter) newPosition = position - ShiftAmount if currentCharacter in Alphabet: encryptedString = encryptedString + Alphabet[newPosition] else: encryptedString = encryptedString + currentCharacter encryptedString = encryptedString.lower() print("The message is", encryptedString) nothing = input("")
true
44d05ed22e742656562ce9179d63dee9cc2d8980
redjax/practice-python-exercises
/06-string-lists.py
567
4.375
4
""" Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) """ test = [0, 1, 2, 3, 4, 5] # print(test[::-1]) word_input = input("Enter a word, we'll tell you if it's a palindrome: ") def reverse_word(word): reversed_word = word[::-1] return reversed_word word_reversed = reverse_word(word_input) if word_input == word_reversed: print("{} is a palindrome!".format(word_input)) else: print("{} is not a palindrome. Oh well!".format(word_input))
true
510de01b1b80cc1684faaf2441dd5154bdd52b7c
zaydalameddine/Breast-Cancer-Classifier
/breastCancerClassifier.py
1,959
4.125
4
# importing a binary database from sklearn from sklearn.datasets import load_breast_cancer # importing the splitting function from sklearn.model_selection import train_test_split # importing the KNeighborsClassifier from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt # loading the databse into that variable breast_cancer_data = load_breast_cancer() # get a better understanding of the database print(breast_cancer_data.target, breast_cancer_data.target_names) # split data into 80%training and 20% testing sets breast_cancer_train, breast_cancer_test, target_train, target_test = train_test_split(breast_cancer_data.data, breast_cancer_data.target, test_size = 0.2, random_state = 100) # printing the len of the data to make sure that the data is the same len as its adjoining labels print(len(breast_cancer_train), len(breast_cancer_test), len(target_train), len(target_test)) highest_accuracy = 0 index = 0 # finding the best k value using a loop from 1 - 100 for k in range(1, 101): # creating and training the classifier model classifier = KNeighborsClassifier(n_neighbors = k) classifier.fit(breast_cancer_train, target_train) accuracy = 0 # testing model against test sets and checking if score is higher than previous k if classifier.score(breast_cancer_test, target_test) > highest_accuracy: highest_accuracy = classifier.score(breast_cancer_test, target_test) index = k #make a model using the best k value and predict the label for the test set classifier = KNeighborsClassifier(n_neighbors = index) classifier.fit(breast_cancer_train, target_train) guesses = classifier.predict(breast_cancer_test.data) #while not a great graph ot shows that the data is mostly right which is also displayed by the 0.965 R^2 value plt.scatter(guesses, target_test.data, alpha = 0.1) plt.xlabel("Classification Guess") plt.ylabel("Clasification Label") plt.title("Breast Cancer Classifier") plt.show()
true
b0a6d7b51978c4ed6691bc4542e63d63f90fc36a
mirandaday16/intent_chatbot
/formatting.py
301
4.25
4
# Capitalizes the first letter of every word in a string, e.g. for city names # Parameters: a place name (string) entered by the user def cap_first_letters(phrase): phrase_list = [word[0].upper() + word[1:] for word in phrase.split()] cap_phrase = " ".join(phrase_list) return cap_phrase
true
adc452c82b5e6a0346987e640bcd8364578e0ac6
MLBott/python-fundamentals-student
/A1/243 assignment 1 Michael Bottom.py
1,909
4.125
4
""" Author: Michael Bottom Date: 1/14/2019 """ import math def lowestNumListSum(firstList, secondList): """ This function accepts two lists of numbers and returns the sum of the lowest numbers from each list. """ firstList.sort() secondList.sort() sumTwoLowest = firstList[0] + secondList[0] return sumTwoLowest def lastNumListAvg(primaryList, secondaryList): """ This function accepts two lists of numbers and returns the average of the last number in each list. """ primaryList.sort() secondaryList.sort() avgTwoLowest = (primaryList[-1] + secondaryList[-1]) / 2 return avgTwoLowest def pythagoreanResult(sideOne, sideTwo): """ This function accepts two non-hypotenuse side length values of a triangle and returns the length value of the hypotenuse """ sideThree = math.sqrt(sideOne**2 + sideTwo**2) return sideThree def lowMidAvg(): """ This function asks the user to enter three integers, creates a list out of them, and returns a message for the hightest, lowest, and average numbers of the list. """ myList = [] myList.append(int(input("Enter the 1st number: "))) myList.append(int(input("Enter the 2nd number: "))) myList.append(int(input("Enter the 3rd number: "))) myList.sort() sumList = sum(myList) avgList = sumList/len(myList) highestNmbr = "The highest number is: " + str(max(myList)) + "\n" lowestNmbr = "The lowest number is: " + str(min(myList)) + "\n" avgNmbr = "The average is: " + str(avgList) return print(highestNmbr + lowestNmbr + avgNmbr) def stringConcat(theStringList): """ This function accepts a list of strings and returns a single string that is a string concatenation of the entire list. """ swapString = "" for item in theStringList: swapString += item return swapString help(str.split)
true
93542a99082c9944497ae78bf2f4589d6985e56c
adithyagonti/pythoncode
/factorial.py
260
4.25
4
num=int(input('enter the value')) if num<0: print('no factorial for _ve numbers') elif num==0: print('the factorial of 0 is 1') else: fact=1 for i in range(1,num+1): fact= fact*i print("the factorial of", num,"is",fact)
true
b6456f6c87553fab9af92919b1505a90bf675ad8
geediegram/parsel_tongue
/ozioma/sleep_schedule.py
651
4.15625
4
# Ann inputs the excepted hours of sleep, the excess no of hours and no of sleep hours # First number is always lesser than the second number # If sleep hour is less than first number, display "Deficiency" # If sleep hour is greater than second number, display "Excess" # If sleep hour is greater than sleep hour and lesser than excess no of hours, display "Normal" # print('Enter the required no of sleep hours.') a = int(input()) b = int(input()) if a < b: h = int(input()) if h < a: print('Deficiency!') elif h > b: print('Excess!') elif a < h < b: print('Normal!') else: print('Inputs are not valid')
true
2edfabb63a04e58a1987cb9935140691549c1911
geediegram/parsel_tongue
/goodnew/main.py
1,443
4.46875
4
from functions import exercise if __name__ == "__main__": print(""" Kindly choose any of the options to select the operation to perform 1. max_of_three_numbers 2. sum_of_numbers_in_a_list 3. product_of_numbers_in_a_list 4. reverse-string 5. factorial_of_number 6. check_if_a_number-falls_in_the_range 7. check_the_number_of_upper_case_and_lower_case_letters 8. list_of_unique_number 9. write_the_number_number_of_even_number_in_a_list 10.prime_number """) user_input = int(input("Kindly select your desired function\n")) if user_input == 1: exercise.max_of_three_numbers() if user_input == 2: exercise.sum_of_numbers_in_a_list() if user_input == 3: exercise.product_of_numbers_in_a_list() if user_input == 4: exercise.reverse_a_string() if user_input == 5: exercise.factorial_of_a_number() if user_input == 6: exercise.check_whether_a_number_falls_in_a_given_range() if user_input == 7: exercise.calculate_number_of_uppercase_and_lowercase_letters() if user_input == 8: exercise.list_with_unique_element_of_the_first_list([1,2,3,2,1,2,1,1,5,6,1]) if user_input == 9: exercise.prime_numbers() if user_input == 10: exercise.even_number([8, 9, 80, 23, 12])
true
5f24adb4960ef8fbe41b5659321ef59c1143d2b1
geediegram/parsel_tongue
/Emmanuel/main.py
877
4.28125
4
from functions import exercise if __name__== "__main__": print(""" 1. Check for maximum number 2. Sum of numbers in a list 3. Multiple of numbers in a list 4. Reverse strings 5. Factorial of number 6. Number in given range 7. String counter 8. List unique elements """) user_input= int(input("Choose which function you wish to make use of:")) if user_input == 1: print(exercise.max_of_three_numbers()) elif user_input == 2: exercise.sum_of_a_list() elif user_input == 3: exercise.multiply_numbers_in_a_list() elif user_input == 4: print(exercise.reverse_string()) elif user_input == 5: print(exercise.factorial()) elif user_input == 6: exercise.number_fall_in_a_given_range() elif user_input == 7: exercise.string_counter() else: print(exercise.list_unique_elements())
true
6e456e8a3206d57ab9041c2cbc00013701ed3345
geediegram/parsel_tongue
/ozioma/positive_and_negative_integer.py
363
4.5625
5
# take a number as input # if the number is less than 0, print "Negative!" # if the number is greater than 0, print "Positive!" # if the number is equal to 0, print "Zero!" print('Enter a value: ') integer_value = int(input()) if integer_value < 0: print('Negative!') elif integer_value > 0: print('Positive!') elif integer_value == 0: print('Zero!')
true
4dfbf66266a20143fc1f3ef6095dbe11b995f3e3
victorkwak/Projects
/Personal/FizzBuzz.py
884
4.1875
4
# So I heard about this problem while browsing the Internet and how it's notorious for stumping like 99% # of programmers during interviews. I thought I would try my hand at it. After looking up the specifics, # I found that FizzBuzz is actually a children's game. # # From Wikipedia: Fizz buzz is a group word game for children to teach them about division.[1] Players take # turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number # divisible by five with the word "buzz". # # The programming problem seems to have added the additional condition of saying "FizzBuzz" if the number # is divisible by both 3 and 5. for i in range(1, 101): if i % 15 == 0: # equivalent to i % 3 == 0 and i % 5 == 0 print "FizzBuzz" if i % 3 == 0: print "Fizz" if i % 5 == 0: print "Buzz" else: print i
true
b05ab548d4bb352e48135c2a0afd2a4a6251e9ea
whencespence/python
/unit-2/homework/hw-3.py
282
4.25
4
# Write a program that will calculate the number of spaces in the following string: 'Python Programming at General Assembly is Awesome!!' string = 'Python Programming at General Assembly is Awesome!!' spaces = 0 for letter in string: if letter == ' ': spaces += 1 print(spaces)
true
cfeb8cd2427bfac3c448c16eb217e3d01152d005
bm7at/wd1_2018
/python_00200_inputs_loops_lists_dicts/example_00920_list_methods_exercise.py
336
4.34375
4
# create an empty list called planets # append the planet "earth" to this list # print your list planet_list = [] # append planet_list.append("earth") print planet_list # [1, 2, 3, 4, 5] # now extend your planets list # with the planets: "venus", "mars" # print your list planet_list.extend(["venus", "mars"]) print planet_list
true
dfc679815218037a7d1926ad153c23875d61dd64
Mwai-jnr/Py_Trials
/class_01/l28.py
735
4.34375
4
#if statements ## start name = "victor" if name == "victor": print("you are welcome") else: print('you are not welcome') # example 2 age = '15' if age <= '17': print("you are under age") else: print("you can visit the site") # example 3 # two if statements age = '17' if age <='17': print('you are under age') if age >= '13' and age < '20': print('you are a teenager') else: print('you can visit the site') #example 4 age = '20' if age <='17': print('you are under age') if age >= '13' and age < '18': print('you are a teenager') else: if age >= '19' and age < '35': print("you are an older guy ") print('you can visit the site')
true
66948e9a7ce8e8114d8a492300d48506a2e4c30b
Mwai-jnr/Py_Trials
/class_01/L37.py
854
4.46875
4
# Loops. # For Loop. #Example 1 #for x in range (0,10): # print('hello') #Example 2 #print(list(range(10,20))) # the last no is not included when looping through a list #Example 3 #for x in range(0,5): # print('Hello %s' % x) # %s acts as a placeholder in strings #it is used when you want to insert something in a string in our case numbers 0-5. # while loop #Example 1 password = 'victor' enter_pass = '' pass_count = 0 pass_limit = 3 pass_out_limit = False while enter_pass != 'victor' and not (pass_out_limit): if pass_count < pass_limit: enter_pass = input('Enter Password: ') pass_count += 1 else: pass_out_limit = True if enter_pass == 'victor': print('welcome to the site') else: print('try again later')
true
6bbe9e80f879c703b375b52b8e8b3ca5ea16b9f5
deepakkmr896/nearest_prime_number
/Nearby_Prime.py
998
4.1875
4
input_val = int(input("Input a value\n")) # Get the input from the entered number nearestPrimeNum = []; # Define a function to check the prime number def isPrime(num): isPrime = True for i in range(2, (num // 2) + 1): if(num % i == 0): isPrime = False return isPrime # Assuming 10 as the maximum gap between the successive prime number for i in range(1, 11): precVal = input_val - i; forwVal = input_val + i; # Check both the preceding and succeeding number for the prime and capture whichever is found first or both (e.g. 3 and 5 for 7) if (precVal > 1): if (isPrime(precVal) == True): nearestPrimeNum.append(precVal) if (isPrime(forwVal) == True): nearestPrimeNum.append(forwVal) if (len(nearestPrimeNum) > 0): break if (len(nearestPrimeNum) > 0): print("Nearest prime no/nos is: {}".format(' and '.join(map(str, nearestPrimeNum)))) else: print("There is no prime number exists nearby")
true
a9067a7adee78d3a72e2cd379d743dd360ed2795
joelamajors/TreehouseCourses
/Python/Learn Python/2 Collections/4 Tuples/intro_to_tuples.py
578
4.5625
5
my_tuple = (1, 2, 3) # tuple created my_second_tuple = 1, 2, 3 # this is a tuple too # the commas are necesary! my_third_tuple = (5) # not a tuple my_third_tuple = (5,) # parenthesis are not necessary, but helpful. dir(my_tuple) # will give you all the stuff you can do. Not much! # you can edit _stuff_ within a tuple, but you can't edit the tuple tuple_with_a_list = (1, "apple", [3, 4, 5]) # can't change [0], [1]. ints and strings are immutable. # strings are mutable tuple_with_a_list[2][1] = 7 # gives a list of [3, 7, 5] # but you can't remove the list itself!
true
8824bf993e2383393d16357e6a318fd27e8e0525
joelamajors/TreehouseCourses
/Python/Learn Python/2 Collections/5 Sets/set_math_challenge.py
2,248
4.4375
4
# Challenge Task 1 of 2 # Let's write some functions to explore set math a bit more. # We're going to be using this # COURSES # dict in all of the examples. # _Don't change it, though!_ # So, first, write a function named # covers # that accepts a single parameter, a set of topics. # Have the function return a list of courses from # COURSES # where the supplied set and the course's value (also a set) overlap. # For example, # covers({"Python"}) # would return # ["Python Basics"]. COURSES = { "Python Basics": {"Python", "functions", "variables", "booleans", "integers", "floats", "arrays", "strings", "exceptions", "conditions", "input", "loops"}, "Java Basics": {"Java", "strings", "variables", "input", "exceptions", "integers", "booleans", "loops"}, "PHP Basics": {"PHP", "variables", "conditions", "integers", "floats", "strings", "booleans", "HTML"}, "Ruby Basics": {"Ruby", "strings", "floats", "integers", "conditions", "functions", "input"} } # below did not work # def covers(set_of_topics): # list_of_courses = [] # for value in COURSES: # list_of_courses.append(value) # return list_of_courses def covers(set_of_topics): # had to get help list_of_courses = [] for key, value in COURSES.items(): if value & set_of_topics: list_of_courses.append(key) return list_of_courses # CHALLENGE 2 of 2 # Great work! # OK, let's create something a bit more refined. # Create a new function named # covers_all # that takes a single set as an argument. # Return the names of all of the courses, in a list, # where all of the topics in the supplied set are covered. # For example, # covers_all({"conditions", "input"}) # would return # ["Python Basics", "Ruby Basics"]. # Java Basics and PHP Basics would be exclude because they # don't include both of those topics def covers_all(set_of_topics): course_list = [] for course, value in COURSES.items(): if (set_of_topics & value) == set_of_topics: course_list.append(course) return course_list
true
e0dc49212a72b8f58ba69c192bf48e41718d93c5
brian-sherman/Python
/C859 Intro to Python/Challenges/11 Modules/11_9 Extra Practice/Task1.py
434
4.21875
4
""" Complete the function that takes an integer as input and returns the factorial of that integer from math import factorial def calculate(x): # Student code goes here print(calculate(3)) #expected outcome: 6 print(calculate(9)) #expected outcome: 362880 """ from math import factorial def calculate(x): f = factorial(x) return f print(calculate(3)) #expected outcome: 6 print(calculate(9)) #expected outcome: 362880
true
4b775221b8af334d4b2f8b9af0c64ecd2d3c9724
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_5_1_Multiplication_Table.py
548
4.25
4
""" Print the two-dimensional list mult_table by row and column. Hint: Use nested loops. Sample output for the given program: 1 | 2 | 3 2 | 4 | 6 3 | 6 | 9 """ mult_table = [ [1, 2, 3], [2, 4, 6], [3, 6, 9] ] for row in mult_table: for element in row: list_len = len(row) current_idx = row.index(element) list_end = list_len - current_idx if list_end != 1: next_idx = current_idx + 1 print(element, end=' | ') else: print(element, end='') print()
true
fd3d0f0a14900b339535fc94ef21b59619ba66e1
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_8_2_Histogram.py
797
4.96875
5
""" Here is a nested loop example that graphically depicts an integer's magnitude by using asterisks, creating what is commonly called a histogram: Run the program below and observe the output. Modify the program to print one asterisk per 5 units. So if the user enters 40, print 8 asterisks. num = 0 while num >= 0: num = int(input('Enter an integer (negative to quit):\n')) if num >= 0: print('Depicted graphically:') for i in range(num): print('*', end=' ') print('\n') print('Goodbye.') """ num = 0 while num >= 0: num = int(input('Enter an integer (negative to quit):\n')) if num >= 0: print('Depicted graphically:') for i in range(0, num, 5): print('*', end=' ') print('\n') print('Goodbye.')
true
6da6609432fd57bc89e4097da96dcd60e80cb94c
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_15_1_Nested_Dictionaries.py
2,843
4.96875
5
""" The following example demonstrates a program that uses 3 levels of nested dictionaries to create a simple music library. The following program uses nested dictionaries to store a small music library. Extend the program such that a user can add artists, albums, and songs to the library. First, add a command that adds an artist name to the music dictionary. Then add commands for adding albums and songs. Take care to check that an artist exists in the dictionary before adding an album, and that an album exists before adding a song. """ music = { 'Pink Floyd': { 'The Dark Side of the Moon': { 'songs': [ 'Speak to Me', 'Breathe', 'On the Run', 'Money'], 'year': 1973, 'platinum': True }, 'The Wall': { 'songs': [ 'Another Brick in the Wall', 'Mother', 'Hey you'], 'year': 1979, 'platinum': True } }, 'Justin Bieber': { 'My World':{ 'songs': ['One Time', 'Bigger', 'Love Me'], 'year': 2010, 'platinum': True } } } def menu(): print('Select an option from the menu below') print('0: Quit') print('1: Add an artist') print('2: Add an album') print('3: Add a song') print('4: Print music') def add_artist(artist): music[artist] = {} print(artist, 'has been added') def add_album(artist,album): music[artist][album] = [] print(album, 'has been added') def add_song(artist,album,song): music[artist][album].append(song) print(song, 'has been added') while True: menu() selection = input() if selection == '0': break if selection == '1': artist = input('Enter an artist\'s name to add: ') if artist in music: print(artist, 'already exists') else: add_artist(artist) elif selection == '2': artist = input('Enter the artist\'s name: ') album = input('Enter the album name: ') if artist not in music: add_artist(artist) add_album(artist,album) elif album not in music[artist]: add_album(artist,album) else: print(album, 'already exists') elif selection == '3': artist = input('Enter the artist\'s name: ') album = input('Enter the album name: ') song = input('Enter the song name: ') if artist not in music: add_artist(artist) add_album(artist,album) add_song(artist,album,song) elif album not in music[artist]: add_album(artist,album) add_song(artist,album,song) elif song not in music[artist][album]: add_song(artist,album,song) else: print(song, 'already exists') elif selection == '4': print(music)
true
ffd50de6b5a8965a8b34db611bd115d2939df135
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_3_1_Iteration.py
1,068
4.4375
4
""" Here is another example computing the sum of a list of integers. Note that the code is somewhat different than the code computing the max even value. For computing the sum, the program initializes a variable sum to 0, then simply adds the current iteration's list element value to that sum. Run the program below and observe the output. Next, modify the program to calculate the following: Compute the average, as well as the sum. Hint: You don't actually have to change the loop, but rather change the printed value. Print each number that is greater than 21. """ # User inputs string w/ numbers: '203 12 5 800 -10' user_input = input('Enter numbers: ') tokens = user_input.split() # Split into separate strings # Convert strings to integers print() nums = [] for pos, token in enumerate(tokens): nums.append(int(token)) print('%d: %s' % (pos, token)) sum = 0 count = 0 for num in nums: sum += num count += 1 if num > 21: print('Greater than 21:', num) average = sum / count print('Sum:', sum) print('Average:', average)
true
f1b2c6a2815b2621cab190582196521ec04da9e2
brian-sherman/Python
/C859 Intro to Python/Challenges/07 Functions/7_17_1_Gas_Volume.py
678
4.375
4
""" Define a function compute_gas_volume that returns the volume of a gas given parameters pressure, temperature, and moles. Use the gas equation PV = nRT, where P is pressure in Pascals, V is volume in cubic meters, n is number of moles, R is the gas constant 8.3144621 ( J / (mol*K)), and T is temperature in Kelvin. """ gas_const = 8.3144621 def compute_gas_volume(pressure, temperature, moles): volume = (moles * gas_const * temperature) / pressure return volume gas_pressure = 100.0 gas_moles = 1.0 gas_temperature = 273.0 gas_volume = 0.0 gas_volume = compute_gas_volume(gas_pressure, gas_temperature, gas_moles) print('Gas volume:', gas_volume, 'm^3')
true
0c123a95902de5efa3ecb815f22a3d242e376623
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_4_2_Print_Output_Using_Counter.py
330
4.46875
4
""" Retype and run, note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks. while num_printed != num_stars: print('*') Sample output for the correct program when num_stars is 3: * * * """ num_stars = 3 num_printed = 0 while num_printed != num_stars: print('*') num_printed += 1
true
de8809d34f4bd91b00fb0b56d2835b3464c6ce3a
brian-sherman/Python
/C859 Intro to Python/Challenges/08 Strings/8_4_5_Area_Code.py
256
4.21875
4
""" Assign number_segments with phone_number split by the hyphens. Sample output from given program: Area code: 977 """ phone_number = '977-555-3221' number_segments = phone_number.split('-') area_code = number_segments[0] print('Area code:', area_code)
true
2f13722b0bd4d477768080b375bdd904af9da065
brian-sherman/Python
/C859 Intro to Python/Challenges/08 Strings/8_6 Additional Practice/Task_2_Reverse.py
294
4.21875
4
# Complete the function to return the last X number of characters # in the given string def getLast(mystring, x): str_x = mystring[-x:] return str_x # expected output: IT print(getLast('WGU College of IT', 2)) # expected output: College of IT print(getLast('WGU College of IT', 13))
true
0416f7bd9af4ef2845a77eb966ab0a21afd7fd64
brian-sherman/Python
/C859 Intro to Python/Boot Camp/Week 1/2_Calculator.py
1,871
4.4375
4
""" 2. Basic Arithmetic Example: Write a simple calculator program that prints the following menu: 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Quit The user selects the number of the desired operation from the menu. Prompt the user to enter two numbers and return the calculation result. Example One: Please select operation - 1. Add 2. Subtract 3. Multiply 4. Divide 5. Exit Select 1, 2, 3, 4, or 5: 1 Enter the first number: 4 Enter the second number: 5 The Sum of 4 and 5 is: 9 Example Two: Please select operation - 1. Add 2. Subtract 3. Multiply 4. Divide 5. Exit Select 1, 2, 3, 4, or 5: 5 GoodBye """ while True: print("Please select operation -") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Exit") selection = input("Select 1, 2, 3, 4, or 5: ") if selection == '5': print("GoodBye") break elif selection == '1' or selection == '2' or selection == '3' or selection == '4': num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if selection == '1': sum = num1 + num2 print("The Sum of %d and %d is: %d" % (num1, num2, sum)) elif selection == '2': difference = num1 - num2 print("The difference of %d and %d is: %d" % (num1, num2, difference)) elif selection == '3': product = num1 * num2 print("The product of %d and %d is: %d" % (num1, num2, product)) elif selection == '4': quotient = num1 / num2 print("The product of %d and %d is: %d" % (num1, num2, quotient)) else: print("Sorry I didn't understand that. Please select an option from the menu.")
true
444195237db2c8f053a44b172038335f9d02567e
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_8_1_Print_Rectangle.py
256
4.5
4
""" Write nested loops to print a rectangle. Sample output for given program: * * * * * * """ num_rows = 2 num_cols = 3 for row in range(num_rows): print('*', end=' ') for column in range(num_cols - 1): print('*', end=' ') print('')
true
3cf756ebdd38a6a5ff233af1ba998c12f7ed1fa3
brian-sherman/Python
/C859 Intro to Python/Boot Camp/Week 1/8_Tuple_Example.py
534
4.625
5
""" 8. Tuple Example: Read a tuple from user as input and print another tuple with the first and last item, and your name in the middle. For example, if the input tuple is ("this", "is", "input", "tuple"), the return value should be ("this", "Rabor", "tuple") Example One: Enter your name to append into the tuple: Rabor Expected Result: ('this', 'Rabor', 'tuple') """ string = input("Enter a tuple seperated by spaces: ") name = input("Enter your name: ") list = string.split() new_t = (list[0], name, list[-1]) print(new_t)
true
68150df94d2940bb980649e15c56a07194cb59fb
imharrisonlin/Runestone-Data-Structures-and-Algorithms
/Algorithms/Sorting/Quick_Sort.py
2,138
4.21875
4
# Quick sort # Uses devide and conquer similar to merge sort # while not using additional storage compared to merge sort (creating left and right half of the list) # It is possible that the list may not be divided in half # Recursive call on quicksortHelper # Base case: first < last (if len(list) <= 1 list is sorted) # # The partition function occurs at the middle it will be O(logn) divisions # Finding the splitpoint requires n items to be checked # O(nlogn) on average # Worst case: the split may be skewed to the left or the right # resulting in dividing the list into 0 items and n-1 items # the overhead of the recursion required # O(n^2) time complexity # ---------------------------------------------------------------------------------------------------------- # Can eleviate the potential of worst case uneven division # by using different ways of choosing the pivot value (ex. median of three) # Median of three: consider first, middle, and last element in the list # pick the median value and use it for the pivot value def quickSort(nlist): quickSortHelper(nlist, 0, len(nlist)-1) def quickSortHelper(nlist, first, last): if first < last: splitpoint = partition(nlist, first, last) quickSortHelper(nlist,first,splitpoint-1) quickSortHelper(nlist,splitpoint+1,last) def partition(nlist,first,last): pivotValue = nlist[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and nlist[leftmark] < pivotValue: leftmark = leftmark + 1 while nlist[rightmark] > pivotValue and rightmark >= leftmark: rightmark = rightmark - 1 if rightmark < leftmark: done = True else: temp = nlist[leftmark] nlist[leftmark] = nlist[rightmark] nlist[rightmark] = temp temp = nlist[first] nlist[first] = nlist[rightmark] nlist[rightmark] = temp return rightmark alist = [54,26,93,17,77,31,44,55,20] quickSort(alist) print(alist) print(partition.__doc__)
true
ce1e57eb3168263137047a967c2223b65017ec89
kzmorales92/Level-2
/M3P2a.py
250
4.3125
4
#Karen Morales # 04/22/19 #Mod 3.2b #Write a recursive function to reverse a list. fruitList = ["apples", "bananas", "oranges", "pears"] def reverse (lst) : return [ lst[-1]]+ reverse (lst[:-1]) if lst else [] print (reverse(fruitList))
true
85d986e6a42307635cd237b666f0724a27537b16
claudiogar/learningPython
/problems/ctci/e3_5_sortStack.py
1,024
4.15625
4
# CTCI 3.5: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure. The stack supports the following operations: push, pop, peek, and isEmpty. class SortedStack: def __init__(self): self.stack = [] self.side = [] pass def push(self, e): if self.isEmpty(): self.stack.append(e) pass p = self.peek() while p < e: v = self.pop() self.side.push(v) p = self.peek() self.stack.append(e) while len(self.side) > 0: v = self.side.pop() self.stack.push(v) def pop(self): if len(self.stack) > 0: return self.pop() return None def peek(self): if len(self.stack) == 0: return None return self.stack[-1] def isEmpty(self): return len(self.stack) == 0
true
4e9dcaa32b8662fb64d27faa933a01d47cc0caf8
Harjacober/HackerrankSolvedProblems
/Python/Regex Substitution.py
311
4.15625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import re def substitution(string): string = re.sub(r'((?<=\s)&&(?=\s))','and', string) string = re.sub(r'(?<=\s)\|\|(?=\s)','or', string) return string N = int(input()) for i in range(N): print(substitution(input()))
true
45063d790455032ec43c9407c1e71b4453845f5d
adityarsingh/python-blockchain
/backend/util/cryptohash.py
799
4.15625
4
import hashlib #it is library that includes the sha256 function import json def crypto_hash(*args): """ This function will return SHA-256 hash of the given arguments. """ stringed_args = sorted(map(lambda data: json.dumps(data),args)) #Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required. joined_data = ''.join(stringed_args) return hashlib.sha256(joined_data.encode('utf-8')).hexdigest() #here only encoded data can be hashed so we are encoding it into utf-8 def main(): print(f"crypto_hash(one ,2, 3): {crypto_hash('test',2,3)}") print(f"crypto_hash(2 ,one, 3): {crypto_hash(2,'test',3)}") if __name__=='__main__': main()
true
968e67c487bc93767de11e74957b8af63e716fe9
vjishnu/python_101
/quadratic.py
591
4.15625
4
from math import sqrt #import sqrt function from math a = int(input("Enter the 1st coifficient")) # read from user b = int(input("Enter the 2st coifficient")) # read from user c = int(input("Enter the 3st coifficient")) # read from user disc = b**2 - 4*a*c # to find the discriminent disc1 = sqrt(disc)# thn find the square root of discriminent # in a quadratic equation there are postive and negative solution post = (-b+disc1) /(2*a) # postive solution neg = (-b-disc1) / (2*a) # negative solution print("The postive solution is {} and the negative solution {}".format(post,neg))
true
fd7b805579cf158999eebd8cb269c0de1f288b80
lucasgcb/daily
/challenges/Mai-19-19/Python/solution.py
815
4.15625
4
def number_finder(number_list): """ This finds the missing integer using 2O(n) if you count the set operation. """ numbers = list(set(number_list)) ## Order the list # Performance of set is O(n) # https://www.oreilly.com/library/view/high-performance-python/9781449361747/ch04.html expected_in_seq = None # We go through the list again. 2*O(n) for i in range(0,len(numbers)): expected_in_seq = numbers[i] + 1 ## Check if we are at the end of the list. try: next_in_seq = numbers[i+1] except IndexError: # Return the next positive expected in sequence if we are. return 0 if numbers[i] < 0 else expected_in_seq if expected_in_seq != next_in_seq: return expected_in_seq
true
9fbf85740e7f3aa9f1e438ff0a51c5939294dac4
Meenawati/competitive-programming
/dict_in_list.py
522
4.40625
4
# Write a Python program to check if all dictionaries in a list are empty or not def dict_in_list(lst): for d in lst: if type(d) is not dict: print("All Elements of list are not dictionary") return False elif d: return False return True print(dict_in_list([{}, {}, {}])) # returns True print(dict_in_list([{}, {1, 2}, {}])) # prints All Elements of list are not dictionary and returns False print(dict_in_list([{}, {1: 'one', 2: 'two'}, {}])) # returns False
true
40d9f9e8e046e5b41d83213bbea3540365d123e0
alfem/gamespit
/games/crazy-keys/__init__.py
1,577
4.15625
4
#!/usr/bin/python # -*- coding: utf8 -*- # Crazy Keys # My son loves hitting my keyboard. # So I made this silly program to show random colors on screen. # And maybe he will learn the letters! :-) # Author: Alfonso E.M. <alfonso@el-magnifico.org> # License: Free (GPL2) # Version: 1.0 - 8/Mar/2013 import random from Game import Game class Menu(Game): def start(self): self.vowels='aeiou' def loop(self): while True: input_type=self.CONTROLLER.wait_for_user_action() if input_type == "K": #Keyboard char=self.CONTROLLER.key_name if char == "escape": #quit game break elif char in self.vowels: #you hit a vowel! self.SOUNDS['vowel'].play() elif char.isdigit(): #you hit a number! self.SOUNDS['number'].play() elif len(char) == 1: #you hit a consonant! self.SOUNDS['consonant'].play() else: #you hit return, tab, or any other special key! self.SOUNDS['other'].play() bgcolor=(random.randint(0,255), random.randint(0,255),random.randint(0,255)) charcolor=(random.randint(0,255), random.randint(0,255),random.randint(0,255)) self.fill(bgcolor) self.DISPLAY.print_textbox(char, self.FONTS["embosst1100"],self.COLORS["text"], self.COLORS["text_background"]) self.DISPLAY.show() # Main def main(name, CONF, DISPLAY, CONTROLLER): menu=Menu(name, CONF,DISPLAY,CONTROLLER) menu.start() menu.loop()
true
da4199473308b99e312b5b542252423592417d85
nabrink/DailyProgrammer
/challenge_218/challenge_218.py
342
4.15625
4
def to_palindromic(number, step): if len(number) <= 1 or step > 1000 or is_palindromic(number): return number else: return to_palindromic(str(int(number) + int(number[::-1])), step + 1) def is_palindromic(number): return number == number[::-1] number = input("Enter a number: ") print(to_palindromic(number, 0))
true
5c5625cca2c934141df40410f1496302c699da06
brasqo/pyp-w1-gw-language-detector
/language_detector/main.py
846
4.125
4
#!/usr/bin/python # -*- coding: utf-8 -*- from collections import defaultdict import operator """This is the entry point of the program.""" def detect_language(text, languages): """Returns the detected language of given text.""" # implement your solution here # create dictionary with same keys as languages result_languages = defaultdict(int) for word in text.split(): for lang in languages: if word in lang['common_words']: result_languages[lang['name']] += 1 #if so increase count for language # for result in result_languages: # if lang['name'] count save count number and name result = max(result_languages, key=result_languages.get) return result # return name
true
3f115dc4d77c49f3827e26674bac162ae8613b57
CodesterBoi/My-complete-works
/File Handling.py
2,273
4.125
4
''' #Reading from a file: car_name = input("Which car's stats do you want to display?") t = open("Car_stats.txt","r") end_of_file = False print(car_name) car_name = True while True: car_name = t.readline().strip() speed = t.readline().strip() acceleration = t.readline().strip() handling = t.readline().strip() nitro = t.readline().strip() break if bool(car_name): print(car_name) print("speed: ",speed) print("acceleration: ",acceleration) print("handling: ",handling) print("nitro: ",nitro) t.close() ''' ''' #Appending from a file: t = open("Car stats.txt","a") car_name = input("Enter the name of your chosen car: ") speed = input("Enter the value of the car's top speed: ") acceleration = input("Enter the value of your car's acceleration: ") handling = input("Enter the value of your car's handling: ") nitro = input("Enter the value of your car's nitro: ") print("car_name: "+car_name) print("speed: "+speed) print("acceleration: "+acceleration) print("handling: "+handling) print("nitro: "+nitro) t.close() ''' ''' #Writing from a file: t = open("Car stats.txt","w") car_name = input("Enter the name of your chosen car: ") speed = input("Enter the value of the car's top speed: ") acceleration = input("Enter the value of your car's acceleration: ") handling = input("Enter the value of your car's handling: ") nitro = input("Enter the value of your car's nitro: ") print("car_name: "+car_name) print("speed: "+speed) print("acceleration: "+acceleration) print("handling: "+handling) print("nitro: "+nitro) t.close() ''' ''' #Overwriting a file. filecontent = open(Car_stats.txt,"w") filecontent.write("I solemnly swear that these stats are true.") filecontent.close() filecontent = open(Car_stats.txt, "r") print(filecontent.read()) ''' ''' #Creating a file from scratch. f = open("Python Mechanics.py", "x") ''' ''' #Current Working Directory and creating a new folder. import os curDir = os.getcwd() print(curDir) os.mkdir('Asphalt9') ''' ''' #Deleting a file import os if os.path.exists("12 days of christmas.txt"): os.remove("12 days of christmas.txt") else: print("This file doesn't exist.") '''
true
067dc51bc622e4e7514fc72c0b8b4626db950da5
amitp29/Python-Assignments
/Python Assignments/Assignment 3/question12.py
1,237
4.34375
4
''' Read 10 numbers from user and find the average of all. a) Use comparison operator to check how many numbers are less than average and print them b) Check how many numbers are more than average. c) How many are equal to average. ''' num_list = [] sum_of_num = 0 for i in range(10): while True: try: i = int(raw_input("Enter the numbers : ")) break except: print "You entered incorrectly, Please eneter integers " continue sum_of_num += i num_list.append(i) average = sum_of_num/float(len(num_list)) print "Average of the numbers is :", sum_of_num/float(len(num_list)) smaller_num_list =[] equal_num_list= [] bigger_num_list= [] for j in num_list: print j if(j<average): smaller_num_list.append(j) if(j==average): equal_num_list.append(j) if(j>average): bigger_num_list.append(j) print " Total %s number/numbers are greater than average, they are: %s"%(len(bigger_num_list),bigger_num_list) print " Total %s number/numbers are equal than average, they are: %s"%(len(equal_num_list),equal_num_list) print " Total %s number/numbers are lesser than average, they are: %s"%(len(smaller_num_list),smaller_num_list)
true
45bcaf8e7ddb54e50dc916ee8ae1604345c27072
amitp29/Python-Assignments
/Python Assignments/Assignment 3/question20.py
835
4.34375
4
''' Write a program to generate Fibonacci series of numbers. Starting numbers are 0 and 1, new number in the series is generated by adding previous two numbers in the series. Example : 0, 1, 1, 2, 3, 5, 8,13,21,..... a) Number of elements printed in the series should be N numbers, Where N is any +ve integer. b) Generate the series until the element in the series is less than Max number. ''' a=0 b=1 n=int(raw_input("Enter the number of terms needed ")) list1 = [a,b] while(n-2): c=a+b a=b b=c list1.append(c) n=n-1 for integer in list1: print integer m=int(raw_input("Enter the number until which the series is to be printed ")) a=0 b=1 list1 = [a,b] while(m-2): c=a+b if(c>m): break a=b b=c list1.append(c) m=m-1 for integer in list1: print integer
true
874f3d5621af8a3cd128bd2d06e30cfe6bb3f0c5
amitp29/Python-Assignments
/Python Assignments/Assignment 3/question7.py
430
4.21875
4
''' Create a list with at least 10 elements in it :- print all elements perform slicing perform repetition with * operator Perform concatenation wiht other list. ''' #perform repetition with * operator list1 = [1]*7 list2 = [4,5,6] #Perform concatenation with other list list3 = list1+list2 print list3 #print all elements for i in list3: print i #perform slicing print "Sliced list",list3[2:]
true
7545be7a5decce69dd33717fc7a77ca5848e6a3d
amitp29/Python-Assignments
/Python Assignments/Assignment 2/question3.py
942
4.15625
4
''' 4. Given a list of strings, return a list with the strings in sorted order, except group all the strings that begin with 'x' first. e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']. Hint: this can be done by making 2 lists and sorting each of them before combining them. i. ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] ii. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] ''' list1 = ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] list2 = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] super_list = [list1, list2] #Iterating through both lists for lists in super_list: lst = [] lst2 = [] #Sorting the list lists = sorted(lists) for word in lists: if(word[0]=='x'): lst.append(word) else: lst2.append(word) #Combining the lists lists = lst+lst2 print lists
true
1dca7820586525dcd22cebeb2d851eb1d2bf8c42
SJasonHumphrey/DigitalCrafts
/Python/Homework004/word_histogram.py
958
4.3125
4
# 2. Word Summary # Write a word_histogram program that asks the user for a sentence as its input, and prints a dictionary containing # the tally of how many times each word in the alphabet was used in the text. wordDict = {} sentence = input('Please enter a sentence: ') def wordHistogram(sentence): for word in sentence: if word not in wordDict: wordDict[word] = 1 else: wordDict[word] += 1 return wordDict sentence = sentence.upper().split() result = wordHistogram(sentence) print(result) # collections module from collections import Counter # 3. Sorting a histogram # Given a histogram tally (one returned from either letter_histogram or word_histogram), print the top 3 words or letters. def histogramTally(): counter = Counter(result) # 3 highest values top = counter.most_common(3) print("The top 3 words are:") for i in top: print(i[0]," : ",i[1]," ") histogramTally()
true
f37f41087fd970146217e4b32a16f0d3af7d9b5e
naolwakoya/python
/factorial.py
685
4.125
4
import math x = int(input("Please Enter a Number: ")) #recursion def factorial (x): if x < 2: return 1 else: return (x * factorial(x-1)) #iteration def fact(n, total=1): while True: if n == 1: return total n, total = n - 1, total * n def factorial(p): if p == 0: return 1 else: return p * factorial(p-1) x = dict () def cachedfactorial(num): #if the number is in key we return to the value if num in x: return x[num] elif num == 0 or num == 1: #i assume that the number >=1 but just in case the number is zero return 1 else: x[num] = num*cachedfactorial(num -1) return x[num] print(factorial(x))
true
05bf4280a7750cf207609ae63ed15f1cee96843f
jkfer/Codewars
/logical_calculator.py
1,602
4.40625
4
""" Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50. Links referring to logical operations: AND, OR and XOR. You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequentially. First Example: Input: true, true, false, operator: AND Steps: true AND true -> true, true AND false -> false Output: false Second Example: Input: true, true, false, operator: OR Steps: true OR true -> true, true OR false -> true Output: true Third Example: Input: true, true, false, operator: XOR Steps: true XOR true -> false, false XOR false -> false Output: false """ from collections import Counter def logical_calc(array, op): if op == "AND": return False if False in array else True elif op == "OR": return True if True in array else False else: # op == "XOR" if len(array) == 1: return array[0] else: stack = [] i = 0 while i < len(array): if stack == []: if array[i] != array[i+1]: stack.append(True) else: stack.append(False) i += 1 else: stack.append(True) if stack[0] != array[i] else stack.append(False) stack.pop(0) i += 1 return stack[0] x = logical_calc([True, False], "XOR") print(x) # alternate is use operator module .and_ .or_ feature
true
b3a0608ad6899ac13e9798ecf4e66c597f688bd1
jkfer/Codewars
/valid_paranthesis.py
1,071
4.3125
4
""" Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Constraints 0 <= input.length <= 100 Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. [], {}, <>). """ def valid_parentheses(string): stack = [] i = 0 while i < len(string): if string[i] == "(": stack.append(string[i]) elif string[i] == ")": if len(stack) > 0 and stack[-1] == "(": stack.pop() else: stack.append(string[i]) i += 1 #print(stack) return True if len(stack) == 0 else False x = valid_parentheses("hi())(") print(x)
true
f6d7508e322f3248106378483dd377e9ee7ac9e8
YaserMarey/algos_catalog
/dynamic_programming/count_factors_sets.py
1,410
4.15625
4
# Given a number 'n' # Count how many possible ways there are to express 'n' as the sum of 1, 3, or 4. # Notice that {1,2} and {2,1} are two methods and not counted as one # Pattern Fibonacci Number def CFS(Number): dp = [0 for _ in range(Number + 1)] dp[0] = 1 # if number = 0 then there is only set of factors which the empty set dp[1] = 1 # if number = 1 then there is only set of factors {1} dp[2] = 1 # if number = 2 then there is only set of factors {1,1} dp[3] = 2 # if number = 2 then there is only set of factors {1,1,1} & {3} # Now starting from third step, until the end we calculate the number of possible sets of steps # by summing the count of the possible sets of steps for i in range(4, Number + 1): dp[i] = dp[i - 1] + dp[i - 3] + dp[i - 4] return dp[Number] def main(): Number = 4 print(" Number {0}, possible factors 1,3,4 , Test case {1} " "since it has calculated possible set of factors to {2} {3}" .format(Number, 'Pass' if CFS(Number) == 4 else 'Fail', CFS(Number), ' and it is 4')) Number = 6 print(" Number {0}, possible factors 1,3,4 , Test case {1} " "since it has calculated possible set of factors to {2} {3}" .format(Number, 'Pass' if CFS(Number) == 9 else 'Fail', CFS(Number), ' and it is 9')) if __name__ == '__main__': main()
true
5871c7a813bddf1480a681d08b2ee5d1d76c52d7
YaserMarey/algos_catalog
/dynamic_programming/count_of_possible_way_to_climb_stairs.py
1,035
4.1875
4
# Given a stair with ‘n’ steps, implement a method to count how many # possible ways are there to reach the top of the staircase, # given that, at every step you can either take 1 step, 2 steps, or 3 steps. # Fib Pattern def CS(S): T = [0 for i in range(S + 1)] T[0] = 1 T[1] = 1 T[2] = 2 for i in range(3, S + 1): T[i] = T[i - 1] + T[i - 2] + T[i - 3] return T[S] def main(): S = 3 print("Testcase 1 is {0} for a stairs of {1}, since it is calculated as {2} and it should be {3}" .format('Pass' if CS(S) == 4 else 'Fail', S, CS(S), '4')) S = 4 print("Testcase 1 is {0} for a stairs of {1}, since it is calculated as {2} and it should be {3}" .format('Pass' if CS(S) == 7 else 'Fail', S, CS(S), '7')) S = 5 print("Testcase 1 is {0} for a stairs of {1}, since it is calculated as {2} and it should be {3}" .format('Pass' if CS(S) == 13 else 'Fail', S, CS(S), '13')) if __name__ == '__main__': main()
true
5d671a339e350f8a3c039ed153667496f6f5850c
burnbrigther/py_practice
/ex15_2.py
687
4.46875
4
# imports the argv feature from the sys package from sys import argv # Takes input values from argv and squishes them together (these are the two command line items) # then unpacks two arguments sent to argv and assigns them to script and filename script, filename = argv # Takes the value from the command line argument (filename), open reads what's in filename # and assigns the value to the variable txt txt = open(filename) # Print the string and value of the variable substitution given from filename above. print "Here's your file %r:" % filename print txt.read() print "Here is your file again:" file_again = open(filename) txt_again = open(file_again) print txt_again.read()
true
978a2fdf4c8dd6ec10b53d88591c18b452ec29ca
OluchiC/PythonLab1
/Lab1.py
925
4.21875
4
sentence = 'I can’t wait to get to School_Name! Love the idea of meeting new Noun and making new Noun! I know that when Number years pass, I will be Age and I will have a degree in Profession. I hope to make my family proud! Am I done with this MadLib Yet?: Boolean.' school_name = input('What\'s the school name?') meeting = input('What\'s the thing you\'re meeting at school?') making = input('What\'s the thing you\'re making at school?') number = str(input('What\'s the number?')) age = str(input('What\'s the Age?')) dream = input('What\'s you\'r dream profession?') decision = str(input('What\'s Are you done (True/False)?')) print('I can’t wait to get to ',school_name,'! Love the idea of meeting new ',meeting,' and making new ',making,'! I know that when ',number,' years pass, I will be ',age,' and I will have a degree in ',dream,'. I hope to make my family proud! Am I done with this MadLib Yet?:',decision)
true
9bf71c7546e14fcade018ff905880acd633547e9
rainakdy1009/Prog11
/dragon games.py
2,525
4.21875
4
import random import time def displayIntro(): #Explain the situation print('''You are in a land full of dragons. In front of you, you see two caves. In one cave, the dragon is friendly and will share his treasure with you. The other dragon is greedy and hungry, and will eat you on sight.''') print() def chooseWay(): #Choose one among 2 choices (Choose the way you'll go) way = '' while way != '1' and way != '2': print('Which way do you want to choose? (1 or 2)') way = input() return way def checkWay (chosenWay): #It checks the way you chose print('You are walking down the street...') time.sleep(2) print('Now you can see the door of the entrance...') time.sleep(2) print('You are trying to open the door...') time.sleep(2) GoodWay = random.randint (1, 2) if chosenWay == str(GoodWay): #First option: The door doesn't open print('Oh No! The door is not open!') playAgain = input('Do you want to play again? (yes or no): ') if playAgain == 'yes' or playAgain == 'y': displayIntro() wayNumber = chooseWay() checkWay(wayNumber) caveNumber = chooseCave() checkCave(caveNumber) playAgain = input() else: exit() else: #Second option: The door opens print('Great! You opened the door!') def chooseCave(): #Choose one cave among two cave = '' while cave != '1' and cave != '2': print('There are two caves!') print('Which cave will you go into? (1 or 2)') cave = input() return cave def checkCave(chosenCave): #It checks the cave you chose print('You approach the cave...') time.sleep(2) print('It is dark and spooky...') time.sleep(2) print('A large dragon jumps out in front of you! He opens his jaws and...') print() time.sleep(2) friendlyCave = random.randint(1, 2) if chosenCave == str(friendlyCave): #friendly cave print('Gives you his treasure!') else: print('Gobbles you down in one bite!') #You're eaten playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': displayIntro() wayNumber = chooseWay() checkWay(wayNumber) caveNumber = chooseCave() checkCave(caveNumber) print('Do you want to play again? (yes or no)') playAgain = input()
true
342ca3b9f92f9adf562bf6fd4b5278305e466255
jessegtz7/Python-Learning-Files
/Strings.py
1,018
4.15625
4
name = 'Ivan' age = 29 #**Concateante** ''' print('His name is ' + name + ' and he is ' + age) -- this will result as a "TypeError: can only concatenate str (not "int") to str" age mus be cast in to a str ''' print('His name is ' + name + ' and he is ' + str(age)) #**String format** #1.- Arguments by position. print('His name is {nombre} and he is {edad}'.format(nombre=name, edad=age)) #2.- F-Strings (On Python 3.6+) print(f'His name is {name} and he is {age}') #**String methods** g = 'blue printer' print(g) #Capitalize string print(g.capitalize()) #All Uppercase print(g.upper()) #All Lower print(g.lower()) #Swap case print(g.swapcase()) #Get length print(len(g)) #Replace print(g.replace('blue', 'orange')) #Count sub = 'p' print(g.count(sub)) #Starts with print(g.startswith('printer')) #Ends with print(g.endswith('r')) #Split into a last print(g.split()) #Find position print(g.find('e')) #Is all alphanumeric print(g.isalpha()) #Is all numeric print(g.isnumeric()) #Look for the outputs
true
76ab13972c5734bc324efb8b53482705ae990746
irtefa/bst
/simple_bst.py
1,142
4.1875
4
from abstract_bst import AbstractBst class SimpleBst(AbstractBst): # A simple compare method for integers # @given_val: The value we are inserting or looking for # @current_val: Value at the current node in our traversal # returns an integer where # -1: given_val is less than current_val # 1: given_val is greater than current_val # 0: given_val and current_val are equal def compare(self, given_val, current_val): if given_val < current_val: return -1 elif given_val > current_val: return 1 return 0 if __name__ == "__main__": simple_bst = SimpleBst() root = simple_bst.insert(None, 10) for i in [5, 15, 1, 7, 12, 20]: simple_bst.insert(root, i) print "A balanced tree:" simple_bst.level_order(root) root = simple_bst.insert(None, 10) insert_these = [20, 5, 15, 22, 1, 7, 6, 23, 25, 30] for i in insert_these: simple_bst.insert(root, i) print "A sparse tree which is heavier on the right:" simple_bst.level_order(root) root = simple_bst.insert(None, 15) for i in [12,11,10,9,8,1]: simple_bst.insert(root, i) print "A sparse tree which is heavier on the left:" simple_bst.level_order(root)
true
c1ad1d4d22f1edfe5bd439118e7c79fc67d7567d
romanticair/python
/basis/Boston-University-Files/AllAnswer/Assignment_9_Answer/a3_task1.py
2,967
4.125
4
# Descriptive Statistice # Mission 1. def mean(values): # Take as a parameter a list of numbers, calculates4 # and returns the mean of those values sumValues = 0 for value in values: sumValues += value return sumValues / len(values) # Mission 2. def variance(values): # Take as a parameter a list of numbers, calculated # and returns the population variance of the values # in the list. which was defined as : # o² = (1 / N) * ∑(Xi - u)² u = mean(values) deviation = 0 for value in values: deviation += (value - u) ** 2 return deviation / len(values) # Mission 3. def stdev(values): # Takes as parameter a list of numbers, calculates # and returns the popution standard deviation of the # values in the list, which was the square-root of the # population variance. return variance(values) ** 0.5 # Mission 4. def covariance(x, y): # Takes as parameters two lists of values, calculates # and returns the population covariance for those two # list, which was defined as : # Oxy = (1 / N) * ∑(Xi - Ux)(Yi - Uy) assert len(x) == len(y), print("Two lists length is'nt equal") Ux = mean(x) Uy = mean(y) twoDeviation = 0 for i in range(len(x)): twoDeviation += (x[i] - Ux) * (y[i] - Uy) return twoDeviation / len(x) # Mission 5. def correlation(x, y): # Takes as parameters two lists of values,calculates # and returns the correlation coefficient between # these data series, which was defined as: # Pxy = Oxy / (Ox * Oy) Ox = stdev(x) Oy = stdev(y) Oxy = covariance(x, y) return Oxy / (Ox * Oy) # Mission 6. def rsq(x, y): # Takes as parameters two lists of values,calculates # and returns the square of the coefficient between # those two data series, which is a measure of the # goodness of fit measure to explain variation in # y as a function of variation of x return correlation(x, y) ** 2 # Mission 7 def simple_regression(x, y): # Take as parameters two lists of values, calculate # the regreesion coefficients between these data series, # and return a list containing two values: the intercept # and regression coefficients, A and B # Bxy = Oxy / Ox², Axy = Uy - Bxy * Ux Oxy = covariance(x, y) Ox = stdev(x) Oy = stdev(y) Ux = mean(x) Uy = mean(y) Bxy = Oxy / (Ox ** 2) Axy = Uy - Bxy * Ux return [Axy, Bxy] def Test(): x = [4, 4, 3, 6, 7] y = [6, 7, 5, 10, 12] print(mean(x)) print(variance(x)) print(stdev(x)) print(covariance(x, y)) print(correlation(x, y)) print(correlation(list(range(10)), list(range(10, 0, -1)))) print(rsq(x, y)) print(simple_regression(x, y)) """ Test : import random a = list(range(30)) b = list(range(30)) random.shuffle(a) random.shuffle(b) print(correlation(a, b)) print(rsq(a, b)) """
true
dff8367263ee46866a30dd2fcb8e241d07968d21
chsclarke/Python-Algorithms-and-Data-Structures
/coding_challenge_review/array_practice.py
885
4.28125
4
def mergeSorted(arr1, arr2): #code to merge two sorted arrays sortedArr = [None] * (len(arr1) + len(arr2)) i = 0 j = 0 k = 0 #iterate through both list and insert the lower of the two while(i < len(arr1) and j < len(arr2)): # <= allows function to support duplicate values if (arr1[i] <= arr2[j]): sortedArr[k] = arr1[i] i += 1 k += 1 else: sortedArr[k] = arr2[j] j += 1 k += 1 #merge the leftovers of the larger list while i < len(arr1): sortedArr[k] = arr1[i] i += 1 k += 1 while j < len(arr2): sortedArr[k] = arr2[j] j += 1 k += 1 return sortedArr if __name__ == '__main__': arr1 = [1,3,5,7,9] arr2 = [2,4,6,7,7,8,10,12,13,14] print(mergeSorted(arr1,arr2))
true
589ff4948bafda92c5f6007c693dd42b4ec5853c
Abel237/automate-boring-stuffs
/automate_boring_stuffs/automate.py
1,384
4.15625
4
# This program says hello and asks for my name. # print('Hello, world!') # print('What is your name?') # ask for their name # myName = input() # print('It is good to meet you, ' + myName) # print('The length of your name is:') # print(len(myName)) # print('What is your age?') # ask for their age # myAge = input() # print('You will be ' + str(int(myAge) + 1) + ' in a year.') # print(int(99.99)) # name = input("what is your name:") # age = int(input("How old are you?: ")) # if name == 'Alice': # print('Hi, Alice.') # elif age < 12: # print('You are not Alice, kiddo.') # elif age > 2000: # print('Unlike you, Alice is not an undead, immortal vampire.') # elif age > 100: # print('You are not Alice, grannie.') # spam = 0 # while spam < 5: # print('hi', spam, '') # spam += 1 # name = '' # while name != 'your name': # print('Please type your name.') # name = input() # if name == 'your name': # break # print('Thank you!') # name = '' # while True: # print('Who are you?') # name = input() # if name != 'Joe': # continue # print('hello Joe! What is your password? it is a fish') # password = input() # if password == 'swordfish': # break # print('acces granted.') total = 0 for num in range(101): total = total + num print(total)
true
d8326d7dd0f2ea05957104c482bacf2776968aff
optionalg/HackerRank-8
/time_conversion.py
987
4.125
4
''' Source: https://www.hackerrank.com/challenges/time-conversion Sample input: 07:05:45PM Sample output: 19:05:45 ''' #!/bin/python import sys def timeConversion(s): meridian = s[-2] time = [int(i) for i in s[:-2].split(':')] # Converting each time unit to integer and obtaining # each unit by splitting it using ':' hour = time[0] minute = time[1] second = time[2] if meridian == 'P': if hour == 12: final_time = str(hour) + ':' else: hour += 12 final_time = str(hour) + ':' else: if hour == 12: hour -= hour final_time = '0' + str(hour) + ':' else: final_time = '0' + str(hour) + ':' if minute < 10: minute = '0' + str(minute) if second < 10: second = '0' + str(second) final_time += str(minute) + ':' + str(second) return final_time s = raw_input().strip() result = timeConversion(s) print(result)
true
9bc2d5011ccdacbf7e172ab4c0245c8b5f437f3f
harrowschool/intro-to-python
/lesson3/task2.py
620
4.3125
4
# Task 2a # Add comments to the code to explain: # What will be output when the code is run? # In what circumstances would the other output message be produced num1 = 42 if num1 == 42: print("You have discovered the meaning of life!") else: print("Sorry, you have failed to discover the meaning of life!") # Task 2b # Add to the code below so that it outputs 'You're not Dave!' if the user does not input 'Dave' name = input("What’s your name?") if name == "Dave": print("Hello Dave") #EXTRA CHALLENGE - Adapt the code so that it works in the same way but uses a not equal to Boolean operator.
true
9c6a978c2595de1301aef97991389bb02cb9855f
skipdev/python-work
/assignment-work/jedi.py
554
4.15625
4
def jedi(): #Display the message "Have you fear in your heart?" print("Have you fear in your heart?") #Read in the user’s string. response = input(str()) #The program will then decide if the user can be a Jedi or not, based on their response. if response.lower() == "yes": print("Fear is the path to the dark side. You cannot be a Jedi apprentice.") elif response.lower() == "no": print("The force is strong in you. You may be a Jedi apprentice.") else: print("You need to decide... yes or no?") jedi() jedi()
true
b76cdc2e8a3bf58989bd280c7f3d82810c67f153
skipdev/python-work
/assignment-work/jumanji.py
543
4.28125
4
number = 0 #Display the message "How many zones must I cross?" print("How many zones must I cross?") #Read in the user’s whole number. number = int(input()) #Display the message "Crossing zones...". print("Crossing zones...") #Display all the numbers from the user's whole number to 1 in the form "…crossed zone [number]" where [number] is the zone number. while int(number) > 0: print("... crossed zone" , number) number = int(number) - 1 #Display the message "Crossed all zones. Jumanji!" print("Crossed all zones. Jumanji!")
true
072bac7e650722c717a17abfa2bc288fde93e0f2
skipdev/python-work
/work/repeating-work.py
219
4.25
4
#Get the user's name name = str(input("Please enter your name: ")) #Find the number of characters in the name (x) x = len(name) #Use that number to print the name x amount of times for count in range(x): print(name)
true
04a15af1fcb1ffccb529a4321c499c5bd1b88d04
skipdev/python-work
/work/odd-even.py
238
4.375
4
#Asking for a whole number number = (int(input("Please enter a whole number: "))) #Is the number even or odd? evenorodd = number % 2 #Display a message if evenorodd == 0: print("The number is even") else: print("The number is odd")
true
f2b76267a6fcd9f60e5c1c4745a8362ed3c9bd27
MrT3313/Algo-Prep
/random/three_largest_numbers/✅ three_largest_numbers.py
1,413
4.34375
4
# - ! - RUNTIME ANALYSIS - ! - # ## Time Complexity: O(n) ## Space Complexity: O(1) # - ! - START CODE - ! - # # - 1 - # Define Main Function def FIND_three_largest_numbers(array): # 1.1: Create data structure to hold final array finalResult = [None, None, None] # 1.2: Loop through each item in the check array and all helper method for num in array: updateLargest(finalResult, num) print(finalResult) # 1.3: Return final array return finalResult # - 2 - # Define Update Helper Function def updateLargest(finalResult, num): # 2.1: Check Largest in finalResult if finalResult[2] is None or num > finalResult[2]: # 2.1.1 Shift is needed shift_and_update(finalResult, num, 2) # 2.2: Check Middle in finalResult elif finalResult[1] is None or num > finalResult[1]: # 2.2.1 Shift is needed shift_and_update(finalResult, num, 1) # 2.3: Check First in finalResult elif finalResult[0] is None or num > finalResult[0]: #2.3.1 Shift is needed shift_and_update(finalResult, num, 0) # - 3 - # Define SHIFT AND UPDATE helper function def shift_and_update(array, num, idx): for i in range(idx + 1): if i == idx: array[i] = num else: array[i] = array[i + 1] # FIND_three_largest_numbers([12,5,7,5,35,187,45,3]) FIND_three_largest_numbers([10,5,9,10,12])
true
3c84466bc01a6b2a5ddbd595fbb6dcb107b40e74
MrT3313/Algo-Prep
/⭐️ Favorites ⭐️/Sort/⭐️ bubbleSort/✅ bubbleSort.py
590
4.21875
4
def bubbleSort(array): isSorted = False counter = 0 # @ each iteration you know the last num is in correct position while not isSorted: isSorted = True # -1 : is to prevent checking w/ out of bounds # counter : makes a shorter array each iteration for i in range(len(array) - 1 - counter): if array[i] > array[i + 1]: swap(i, i + 1, array) isSorted = False counter += 1 return array def swap(i, j, array): array[i], array[j] = array[j], array[i] print(bubbleSort([8,5,2,9,5,6,3]))
true
71dc3f9110ad21660a526284e6b58b8834729e7a
ashNOLOGY/pytek
/Chapter_3/ash_ch3_coinFlipGame.py
799
4.25
4
''' NCC Chapter 3 The Coin Flip Game Project: PyTek Code by: ashNOLOGY ''' import math import random #Name of the Game print("\nThe Coin Flip Game" "\n------------------\n") #Set up the Heads & Tails as 0 h = 0 t = 0 #ask user how many flips should it do howMany = int(input("How many flips? ")) #Set up the random FLIPPER to flip 100 times #While Loop for the flips? i = 0 while (i < howMany): f = random.randint(1,2) #The flip # If loop for the Heads & Tails? # If its 1 its/add to Heads # If its 2 its/add Tails if f == 1: h = h + 1 else: t = t + 1 i = i +1 #print(f) #Display the result for H & T print("\nHeads: ", h) print("Tails: ", t) #ENTER to Exit input("\nENTER to EXIT")
true
a494320f224a78e13f565b69e7aebd406709c979
RanabhatMilan/SimplePythonProjects
/GussingNum/guessing.py
880
4.25
4
# This is a simple guessing game. # At first we import a inbuilt library to use a function to generate some random numbers import random def guess_num(total): number = random.randint(1, 10) num = int(input("Guess a number between 1 to 10: ")) while num != number: if num > number: num = int(input("Guess a number lower than "+str(num)+"! Try Again: ")) if num < number: num = int(input("Guess a number higher than "+str(num)+"! Try Again: ")) if num == number: yn = input("Ohh..Your guess is Correct. \nYou WIN. Your total score is "+str(total)+". Do you want to play Again?[y/n] ") return yn name = input("What's your name? ") yn = input("Hello "+name+"!! Do you want to play some game?[y/n]") total = 10 while yn == 'y': yn = guess_num(total) total += 10 if yn == 'n': print ("Okaay.. Cool")
true
cf64c6a26c86f5af34c39f617763757d4ab270ed
bushki/python-tutorial
/tuples_sets.py
1,801
4.53125
5
# tuple - collection, unchangeable, allows dupes ''' When to use tuples vs list? Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order. Using this distinction makes code more explicit and understandable. One example would be pairs of page and line number to reference locations in a book, e.g.: my_location = (42, 11) # page number, line number https://stackoverflow.com/questions/626759/whats-the-difference-between-lists-and-tuples ''' # create tuple - use parenthese fruits = ('apples', 'oranges', 'grapes') print (type(fruits)) print (fruits) # if only one item and no trailing comma, type will be string test_tuple = ('orange') print (test_tuple, type(test_tuple)) # always use trailing comma if you want to make tuple with single item test_tuple = ('orange',) print (test_tuple, type(test_tuple)) # get a value - zero-based print(fruits[1]) # cannot change value # fruits[0] = 'something else' # TypeError: 'tuple' object does not support item assignment # delete entire tuple del test_tuple #print (test_tuple) # length print(len(fruits)) # SETS - collection of unordered and unidexed. No dupes. #create set (use curly braces) fruits_set = {'Apples', 'Oranges', 'Mango'} # check if element is in set print ('Apples' in fruits_set) # add to set fruits_set.add('grape') print(fruits_set) # add dupe - will not add and no error fruits_set.add('grape') print(fruits_set) # remove from set (will throw error if element not found) fruits_set.remove('grape') print(fruits_set) # clear set fruits_set.clear() print(fruits_set) # delete set del fruits_set
true
757c5b54164ebe279401ef9cb63e920715352258
xatrarana/python-learning
/PYTHON programming/3.dictonary in python/dict problemss.py
269
4.15625
4
## i have to get the sentance as input form the user and cout the user input.. #sentence -> input,key->word, value->length of the word sent=input("Enter the sentence") words=sent.split(" ") count_words={words:len(words) for words in words} print(count_words)
true
635385f3da34913511846c5f0010347b260aa5fa
houckao/grade-calculator-python
/grades_calculator.py
1,598
4.15625
4
""" This is a library of functions designed to be useful in a variety of different types of grade calculations. """ # import support for type hinting the functions from typing import List, Dict def average(grades: List[float]) -> float: """Calculates the average of an array of grades, rounded to 2 decimal places Args: grades (List[float]): An array of number grades Returns: float: The average of the grades """ sum = 0 for x in grades: sum = sum + x average = sum/len(grades) return round(average,2) def drop_lowest(grades: List[float]) -> List[float]: """Drops the lowest number and returns the pruned collection Args: grades (List[float]): An array of number grades Returns: List[float]: The pruned list of grades """ new_grades = grades.copy() new_grades.remove(min(new_grades)) return new_grades def calculate_gpa(grades: List[str], weights: Dict[str, float]) -> float: """ Takes a list of letter grades, and a dictionary that provides the relative weights of those letter grades in GPA format. It calculates a GPA based on the number of grades and their weights rounded to two decimal places. Args: grades (List[str]): A list of letter grades, e.g. A, B+, C, A-, etc. weights (Dict[str, float]): The dictionary equating letter grades to their weight Returns: float: The calculated GPA """ total = 0 for x in grades: total += weights[x] gpa = total/len(grades) gpa = round(gpa, 2) return gpa
true
7bda8a77649f5832e637e38a7f7564cc0b2fd4d1
qihong007/leetcode
/2020_03_04.py
1,138
4.3125
4
''' Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). Example 1: Input: "aabcccccaaa" Output: "a2b1c5a3" Example 2: Input: "abbccd" Output: "abbccd" Explanation: The compressed string is "a1b2c2d1", which is longer than the original string. 执行用时:212 ms 内存消耗:14.4 MB ''' class Solution(object): def compressString(self, S): if len(S) <= 1: return S s = S[0] num = 1 for i in range(0, len(S)-1): s0 = S[i] s1 = S[i+1] if s0 == s1: num = num + 1 else: s = s + str(num) + s1 num = 1 if i+1 == len(S)-1: s = s + str(num) if len(S) > len(s): return s return S
true
3761089895083f5fb8111f5b8db218c81fa86d71
khushalj/GOOGLE-HASH-CODE-2021
/pizza.py
2,318
4.1875
4
#!/usr/bin/python3 #Function that prints the solution to send to the judge def imprimirsolucion(deliveries): # We print number of shipments print (len (deliveries)) for between in deliveries: #We print each shipment generating a string and finally printing it #First, we put the shipment if it goes to a group of 4, 3 or 2 cad = str (between [0]) # We will go through the list to print which pizzas were in that shipment for element in between [1:]: cad = cad + "" + str (element) #We print the solution print (cad) #Main program def main (): # We declare variables to read total pizzas and total of each type of equipment nPizzas = 0 nEq2 = 0 nEq3 = 0 nEq4 = 0 # We read number of pizzas, teams of 2, 3 and 4 members nPizzas, nEq2, nEq3, nEq4 = map (int, input (). split ()) # We declare a list with the pizzas that we will read pizzas = [] # We read all the pizzas. We put them in a list each, ignoring the first element # The reason for ignoring the first element is that it tells us how many ingredients there are, but for # save space we do not put it and we can always calculate with the "len" function for _ in range (nPizzas): pizzas.append (input (). split () [1:]) #List that will contain the result of assigned pizzas res = [] #As long as there are Pizzas and groups left, I create deliveries pizzaActual = 0 #We assign pizzas first to groups of 4 while (pizzaActual + 4 <= nPizzas and nEq4> 0): # Add the result res.append ([4, pizzaActual, pizzaActual + 1, pizzaActual + 2, pizzaActual + 3]) pizzaActual = pizzaActual + 4 nEq4 = nEq4-1 #Then groups of 3 while (pizzaActual + 3 <= nPizzas and nEq3> 0): res.append ([3, pizzaActual, pizzaActual + 1, pizzaActual + 2]) pizzaActual = pizzaActual + 3 nEq3 = nEq3-1 #last groups of 2 while (pizzaActual + 2 <= nPizzas and nEq2> 0): res.append ([2, pizzaActual, pizzaActual + 1]) pizzaActual = pizzaActual + 2 nEq2 = nEq2-1 #print the result of res imprimirsolucion (res) # Code to execute initial main ()
true
9a20562783968cda53b51396d3a55fc0072ff9d0
pouya-mhb/My-Py-projects
/OOP Practice/prac1.py
1,658
4.15625
4
# A class for dog informations dogsName = [] dogsBreed = [] dogsColor = [] dogsSize = [] dogsInformation = [dogsName, dogsBreed, dogsColor, dogsSize] #Create the class class Dog (): #methods # init method for intialization and attributes in () def __init__(self, dogBreed, name, dogColor, dogSize): # self refers to itself (the class) # sth = self.atrribute self.dogBreed = dogBreed self.name=name self.dogColor=dogColor self.dogSize=dogSize ''' def barking (self,sound): self.sound=sound print("woof .. woofh ") ''' n = int(input("How many Dogs ? : ")) for i in range (0,n): a = input("breed : ") b = input("name : ") c = input("dogColor : ") d = input("size : ") dogObject = Dog(dogBreed=a, name=b, dogColor=c, dogSize=d) dogsBreed.append(dogObject.dogBreed) dogsName.append(dogObject.name) dogsColor.append(dogObject.dogColor) dogsSize.append(dogObject.dogSize) #myDog = Dog(dogBreed='labrador', name='jakie', dogColor='golden', dogSize='big') #objects #myFriendDog = Dog(dogBreed='huskie', name='jousef',dogColor='balck', dogSize='small') print(type(Dog)) print("dogsBreed : ", dogsBreed,'\n' "dogsName : ", dogsName,'\n' "dogsSize : ", dogsSize,'\n' "dogsColor : ", dogsColor) #for i in dogsInformation: #print(i) # calling like object.attributes ''' print("my dog information : " ,myDog.dogBreed,myDog.name,myDog.dogColor,myDog.dogSize) print("my dad's dog information : ", myDadsDog.dogBreed, myDadsDog.name, myDadsDog.dogColor, myDadsDog.dogSize) '''
true
d779c188dbd38b81d162f126fe2f502e2dd671d6
adityagrg/Intern
/ques2.py
234
4.3125
4
#program to calculate the no. of words in a file filename = input("Enter file name : ") f = open(filename, "r") noofwords = 0 for line in f: words = line.split() noofwords += len(words) f.close() print(noofwords)
true
343677c250f436b5095c72985eadd30da635da00
Young-Thunder/RANDOMPYTHONCODES
/if.py
206
4.1875
4
#!/usr/bin/python car = raw_input("Which car do you have") print "You have a " + car if car == "BMW": print "Its is the best" elif car =="AUDI": print "It is a good car" else: print "UNKNOWN CAR "
true
e535d1c452c734ab747fda28d116d4b5fe2f9325
gia-bartlett/python_practice
/practice_exercises/odd_or_even.py
431
4.375
4
number = int(input("Please enter a number: ")) # input for number if number % 2 == 0: # if the number divided by 2 has no remainder print(f"The number {number} is even!") # then it is even else: print(f"The number {number} is odd!") # otherwise, it is odd ''' SOLUTION: num = input("Enter a number: ") mod = num % 2 if mod > 0: print("You picked an odd number.") else: print("You picked an even number.")'''
true
8596578006399b3095b2a572e3f08aa0789031ba
JavaPhish/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
340
4.28125
4
#!/usr/bin/python3 """ Adds 2 integers """ def add_integer(a, b=98): """ Adds A + B and returns """ if (type(a) is not int and type(a) is not float): raise TypeError("a must be an integer") if (type(b) is not int and type(b) is not float): raise TypeError("b must be an integer") return (int(a) + int(b))
true
a6b0b97119142fff91d2b99dc01c945d5409c799
JavaPhish/holbertonschool-higher_level_programming
/0x06-python-classes/4-square.py
873
4.125
4
#!/usr/bin/python3 """ AAAAAAHHHHH """ class Square: """ Square: a class. """ def __init__(self, size=0): """ Init - init method """ if type(size) is not int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size def area(self): """ area - Returns the area of the square """ return self.__size * self.__size # getter def get_size(self): """ get_size - getter """ return self.__size # setter def set_size(self, n_size=0): """ set_size - setter """ if type(n_size) is not int: raise TypeError("size must be an integer") if n_size < 0: raise ValueError("size must be >= 0") self.__size = n_size size = property(get_size, set_size)
true
649b70c784a4bebd56897ba1f7b89fc98277a6e8
OlayinkaAtobiloye/Data-Structures
/Data Structures With OOP/linkedlist.py
2,391
4.3125
4
class Node: def __init__(self, value, next_=None): self.value = value self.next = next_ class LinkedList: """A linked list is a linear data structure. It consists of nodes. Each Node has a value and a pointer to a neighbouring node(i.e it links to it's neighbor) hence the name linked list. They are used in cases where constant time insertion and deletion are required.""" def __init__(self, head=None): self.head = head def insert(self, value, position): count = 0 current = self.head while current: previous = current current = current.next count += 1 if count == position: previous.next = value value.next = current break def append(self, value): """takes in the head of the linked list and the value to be appended in the linked list. """ current = self.head previous = current if current: while current: previous = current current = current.next else: previous.next = value else: self.head = value def remove(self, position): """removes element at given position""" current = self.head count = 0 if current: while current: previous = current current = current.next count += 1 if count == position: previous.next = current.next break def pop(self): """removes the last element from the linked list. """ current = self.head previous = current last = previous while current: last = previous previous = current current = current.next else: last.next = None def __repr__(self): """representation of the linked list""" x = self.head a = f'{str(x.value)}' if x: while x.next: x = x.next a += f"-->{str(x.value)}" return a l = LinkedList(Node(6)) l.append(Node(5)) l.append(Node(7)) l.append(Node(10)) l.append(Node(1)) l.append(Node(3)) l.insert(Node(8), 2) l.append(Node(9)) l.remove(3) # print(l.head.value) # print(l.head.next.value) print(l)
true
59c9e4ce10bbfcff84f1d0b23d2938ea98e67783
motleytech/crackCoding
/RecursionAndDyn/tripleStep.py
568
4.1875
4
'''Count ways to get to nth step, given child can take 1, 2 or 3 steps at a time''' # let f(n) be the ways to get to step n, then # f(n) = f(n-1) + f(n-2) + f(n-3) def tripleStep(n): 'return number of ways to get to nth step' if 1 <= n <= 3: return n a, b, c = 1, 2, 3 n = n-3 while n > 0: n -= 1 a, b, c = b, c, (a + b + c) return c def test_tripleStep(): 'test for tripleStep method' for x in range(1, 20): res = tripleStep(x) print x, res if __name__ == '__main__': test_tripleStep()
true
0eaabc6474396fc098c038667a838bf486705375
motleytech/crackCoding
/arraysAndStrings/uniqueCharacters.py
1,703
4.21875
4
''' determine if a string has all unique characters 1. Solve it. 2. Solve it without using extra storage. Key idea: Using a dictionary (hashmap / associative array), we simply iterate over the characters, inserting each new one into the dictionary (or set). Before inserting a character, we check if it already exists in the dictionary/set. If it exists, then that character is repeated, and we return False. If we reach the end of the string while repeating this process, it implies that all characters are unique (else we would have returned False at some point). We return True. ''' def hasUniqueChars(s): ''' checks if a string is composed of unique characters (using a set to store seen characters) ''' existing = set() for c in s: if c in existing: return False existing.add(c) return True def hasUniqueCharsNoBuf(s): ''' checks if a string consists of unique characters This version uses no extra storage. Works by iterating over characters and comparing each character with all the others to make sure none other matches. ''' ls = len(s) for x in range(ls - 1): for y in range(x+1, ls): if s[x] == s[y]: return False return True def testMethod(func): ''' test unique verification methods ''' print 'Testing %s: ' % func.__name__, assert func('') assert not func('aa') assert func('abcde') assert not func('abcdea') assert not func('aagdjflk') assert not func('gdjfklaa') assert not func('gdjfjkl') print 'Passed' if __name__ == '__main__': testMethod(hasUniqueChars) testMethod(hasUniqueCharsNoBuf)
true
e7d7975306ff4dc19aace83acc35a0b95172a3e0
motleytech/crackCoding
/arraysAndStrings/isStringRotated.py
788
4.125
4
''' Given 2 strings s1 and s2, and a method isSubstring, write a method to detect if s1 is a rotation of s2 The key ideas are... 1. len(s1) == len(s2) 2. s1 is a substring of s2 + s2 If the above 2 conditions are met, then s2 is a rotation of s1 ''' def isSubstring(s1, s2): ''' Returns True if s1 is a substring of s2 ''' return s1 in s2 def isRotation(s1, s2): ''' Returns True if s1 is a rotation of s2 ''' if len(s1) == len(s2): if isSubstring(s1, s2 + s2): return True return False def test_isRotation(): ''' test for isRotation ''' print 'Testing isRotation...', assert isRotation('abcd', 'bcda') assert isRotation('a', 'a') print 'Passed' if __name__ == '__main__': test_isRotation()
true