blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a6ce2c96ee05be77b390674cd3fee3ab39771cd8
ralevn/Python_scripts
/hackerranked/evallistcmd.py
1,351
4.3125
4
""" Lists onsider a list (list = []). You can perform the following commands: nsert i e: Insert integer e at position i. rint: Print the list. emove e: Delete the first occurrence of integer e. ppend e: Insert integer e at the end of the list. ort: Sort the list. op: Pop the last element from the list. reverse: Reverse the list. Initialize your list and read in the value of n followed by n lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list. Input Format The first line contains an integer, n, denoting the number of commands. Each line i of the n subsequent lines contains one of the commands described above. Constraints The elements added to the list must be integers. Output Format For each command of type print, print the list on a new line. Enter your code here. Read input from STDIN. Print output to STDOUT """ if __name__ == '__main__': N = int(raw_input()) lst=[] for i in xrange(N): a = raw_input().split() if len(a) == 3: eval("lst." + a[0] + "(" + a[1] + "," + a[2] + ")") elif len(a) == 2: eval("lst." + a[0] + "(" + a[1] + ")") elif a[0] == "print": print lst else: eval("lst." + a[0] + "()")
true
039a21334b04575a8bfe49c7c2e70bdefa68314a
rkmsh/Cracking-The-Coding-Interview
/Linked LIsts/Kth_to_last.py
2,117
4.40625
4
# It is an iterative solution # Defining the Node class Node: def __init__(self, data = None): self.data = data self.next = None #Defining the Linked List class class linkedList: def __init__(self): self.head = None self.tail = None # Method to add data to the linked List def append(self, data): node = Node(data) # If the linked List is not empty then we add # data to the head of the List if self.head: self.head.next = node self.head = node # If the Linked List is empty we add data to the tail # of the list else: self.tail = node self.head = self.tail # Method to display() the Linked List def display(self): current = self.tail while current: print(current.data, end = ' ') current = current.next print() # Method to return the data Kth to the last def KthToLast(self, k): lst1 = self.tail lst2 = self.tail # Move the lst1 to the Kth Position from the beginning of the List for i in range(k): if lst1.data == None: print("Out of bound") return 0 else: lst1 = lst1.next # Move the lst1 and lst2 until lst1 == None # Then the position of lst2 will be the Kth Node to the last while(lst1): lst1 = lst1.next lst2 = lst2.next print("Data in the {}th node to the last: {}".format(k, lst2.data)) # Defining the main() function def main(): lst = linkedList() # Calling the append() method to add data to the Linked List lst.append(2) lst.append(3) lst.append(89) lst.append(67) lst.append(90) lst.append(45) lst.append(10) # Calling the display() method to display the Linked List lst.display() # Calling the KthToLast() method to know the Kth node's data from the last lst.KthToLast(3) lst.KthToLast(7) # Calling the main() function if __name__ == "__main__": main()
true
fe7ee2f14a108ec6b2916047bd78a9d2de814b7b
rkmsh/Cracking-The-Coding-Interview
/Stacks_and_Queues/Stack_min.py
1,767
4.15625
4
#!/usr/bin/python3 # # # This program always return the minnimum element in the stack # Defining the class min_stack() # class min_stack: def __init__(self): self.stack = [] self.stack_min = [] self.tail = -1 self.small = None # Defining a method push() to add data into the stack def push(self, data): self.stack.append(data) self.tail = self.tail + 1 self.stack_min.append(data) self.min(self.stack_min) # Defining a method pop() to remove data from the stack def pop(self): value = self.stack[self.tail] del(self.stack[self.tail]) self.tail = self.tail - 1 del(self.stack_min[self.stack_min.index(value)]) self.min(self.stack_min) # Defining a method min() to print the minnimum element in the stack def min(self, ls1): ls1.sort(reverse = True) try: if len(ls1) == 1: self.small = ls1[0] elif ls1[-1] < self.small: self.small = ls1[-1] print("Minnimum : {}".format(self.small)) except IndexError: print("No Data") # Defining the main() function def main(): # Creating an object of the class min_stack() ls2 = min_stack() # Calling the push() method to add data into the stack ls2.push(4) ls2.push(10) # Calling the pop() function to remove data from the stack ls2.pop() # Calling the push() method to add data into the stack ls2.push(2) # Calling the pop() function to remove data from the stack ls2.pop() ls2.pop() # Calling the push() method to add data into the stack ls2.push(5) ls2.push(3) # Calling the main() function if __name__ == "__main__": main()
true
38366a23768de52af0ed9bb449b7acb1abc2a6a3
saqibwaheed786/100DayofCode
/Day22/exercise6.3.py
916
4.5
4
# 6-3. Glossary: A Python dictionary can be used to model an actual dictionary. # However, to avoid confusion, let’s call it a glossary. # • Think of five programming words you’ve learned about in the previous # chapters. Use these words as the keys in your glossary, and store their # meanings as values. # • Print each word and its meaning as neatly formatted output. You might # print the word followed by a colon and then its meaning, or print the word # on one line and then print its meaning indented on a second line. Use the # newline character (\n) to insert a blank line between each word-meaning # pair in your output. # ----------------------------------------------------------------------------- glossary ={ 'algorithm':'value', 'array':'type', 'bug':'mistake', 'comment':'arbitrary text'} for word,meaning in glossary.items(): print("The word " + word+ " meaning is "+"\n"+meaning.title() )
true
0af09664e9f0f59c9d9cceb3acdc6544f5e9034c
saqibwaheed786/100DayofCode
/Day18/cars.py
1,010
4.625
5
#Organizing a List #Sorting a List Permanently with the sort() Method #.................................................................. cars = ['bmw', 'audi', 'toyata', 'subaru'] #cars.sort() #print(cars) #reverse alphabetical order #................................................................... #cars.sort(reverse=True) #print(cars) #print('Here is the original list:') #print(cars) #print('\n Hear is the sorted list:') #print(sorted(cars)) #print("\n Here is the original list again: ") #Printing a List in Reverse Order #........................................................................ #print(cars) #cars.reverse() #print(cars) #can revert to the original order anytime by applying reverse() to the same #list a second time. #cars.reverse() #print(cars) #Finding the Length of a List #........................................................................ cars = ['bmw', 'audi', 'toyata', 'subaru'] len(cars) #........................................................................
true
f6997fa0958705d2caa9a09634288764f93ff4fb
saqibwaheed786/100DayofCode
/DAY28/exercise8.4.py
646
4.625
5
# 8-5. Cities: Write a function called describe_city() that accepts the name of # a city and its country. The function should print a simple sentence, such as # Reykjavik is in Iceland. Give the parameter for the country a default value. # Call your function for three different cities, at least one of which is not in the # default country. # _________________________________________________________________________________ def describe_city(city, country='pakistan'): """Describe city.""" msg= city.title() + " is in " + country.title() + "." print(msg) describe_city("lahore") describe_city("karachi") describe_city('dhali ', 'india')
true
99120e4273b991b291d2b93c757488d1d70a9ae6
AnkithaBH/Python
/Basics/Armstrong.py
300
4.3125
4
#Armstrong number is a number that is equal to the sum of cubes of its digits num=int(input("Enter any number:")) num=str(num) sum=0 for i in num: sum=sum+((int(i))**3) num=int(num) if num==sum: print("It is an armstrong number") else: print("It is not an armstrong number")
true
7c2dc69e4f05e974d0bce71d6f50f2cb1f1c07ab
MrVJPman/Teaching
/ICS3U1/Exercise Solutions/Exercise 15 Solutions.py
1,621
4.40625
4
#Question 1) https://www.w3schools.com/python/exercise.asp?filename=exercise_functions1 #Question 2) #Create a function with no input that also return None as an output. You must write the return statement! #Call the function, and verify that the function call output None via print() def no_input_return_None() : return None print(no_input_return_None()) #Question 3) #Hint : Use code from Homework 12-14 to help you with this #a)Create a function that accepts only one input. The input will be a data structure (a list or a string). #The function prints all the values in a data structure one-by-one. #The function builds a list of every single character/value from the data structure #The function builds a new string from the values of the data structure. #you will need type conversion. Use str() #The function then adds the new string at the end of the list #The function finally returns the list def str_list_combination(input_data_structure): new_list = [] new_string = "" for value in input_data_structure: print(value) new_list.append(value) new_string = new_string + str(value) new_list.append(new_string) return new_list my_list=["a","b","c"] print(list_function(my_list)) #b) Call this function with this example input List. You should display the correct output. : #input : [1, 2, 3] #output : [1, 2, 3, 123] print(str_list_combination([1, 2, 3])) #c) Call this function with this example input String. You should display the correct output. : #input : abc #output : [a, b, c, abc] print(str_list_combination("abc"))
true
f2ef69222b15ad8d9ec8c27914e8efb207960082
ursstaud/PCC-Basics
/admin.py
1,251
4.21875
4
class Users: """simple class example with users""" def __init__(self, first_name, last_name, age, location): self.first_name = first_name self.last_name = last_name self.age = age self.location = location def describe_user(self): """describing the user example""" print(f"This user's full name is {self.first_name.title()} {self.last_name.title()}.") print(f"This user's age is {self.age}, and their location is in {self.location.title()}.") def greet_user(self): full_name = f"{self.first_name.title()} {self.last_name.title()}" print(f"Hello {full_name}, welcome!") class Privileges: def __init__(self, privileges = ['can add post', 'can delete post', 'can ban user']): #list needs to be as default part of argument self.privileges = privileges def show_privileges(self): print(f"The admin has the following capabilities that normal users do not:") for privilege in self.privileges: print(f"-{privilege.title()}") class Admin(Users): def __init__(self, first_name, last_name, age, location): super().__init__(first_name, last_name, age, location) self.privileges = Privileges() admin1 = Admin('ursula', 'stauder', 23, 'santa cruz') admin1.privileges.show_privileges()
true
5ba68977acc13f9a1950725fec6801ba75a56364
ursstaud/PCC-Basics
/roller_coaster.py
226
4.21875
4
height = input("How tall are you in inches?") height = int(height) if height >= 48: print("\nYou are tall enought to ride!") else: print("\nSorry, you cannot ride. You'll be able to ride when you're a little older.")
true
b0dd78793d95a2967eaedf9650d6c9d9d5a5346b
samyak1903/Data-Types-1
/A7.py
356
4.1875
4
#Q.1- Count even and odd numbers in that list. l=[] even,odd=0,0 elements=int(input("Enter the number of elements to be added in list")) for num in range(elements): num=int(input("Enter the value")) l.append(num) for n in l: if n%2==0: even=even+1 else: odd=odd+1 print("Even count=%d\n Odd count=%d\n" %(even,odd))
true
39cfb3684e1cbfa747f4791f0a3ee45c2451a60e
tbcodes/Simple_Python_Game_Guess_the_word
/2-Guess_the_word_game.py
1,604
4.21875
4
# Guess the Word - Python Game - Truzz Blogg # Youtube link: https://youtu.be/2kVb0_EJgn4 import random import sys players = 'Cristiano, Hazard, Messi, VanDijk, Neymar, Salah, Dybala, Mbappe, Kane, Mane, Benzema, Kroos, Aguero, Ozil, Oblak, Coutinho, Modric, DeBruyne' players = players.split(',') final_players = [] for x in players: players = x.strip() final_players.append(players) score = 0 def guessThePlayer(): global score print('### Python Football/Soccer Game - Guess the name of the player ###') print("List of players...You have to guess the name of a random player!") print(final_players) random_final_players = random.choice(final_players).casefold() # print("El valor de random player es: ", random_final_players) print(random_final_players[0].capitalize() + '-' * (len(random_final_players) - 2) + random_final_players[-1]) if random_final_players in ['messi', 'cristiano']: print("Hint: D10s or Almost D10s") user_input = str(input('Guess the name of the player: ')).casefold() if user_input == random_final_players: score += 1 print("Score:", score) guessThePlayer() else: print('Upppss! Wrong answer! The correct answer is: {}'.format(random_final_players)) print('Your final score is: {}'.format(str(score))) play_again = str(input("Would you like to try again?")).lower() if play_again in ['yes', 'y']: score = 0 guessThePlayer() else: sys.exit("Bye Bye!!!") guessThePlayer()
false
6a8647d83cd511344e06c8f2519fff71e88f5347
Jackson201325/Python
/Python Crash Course/Chapter 3 Lists/More_guest(3.6).py
824
4.46875
4
# You just found a bigger dinner table, so now more space is available. Think of three more guest to invite # Use insert() to add new guesto to the beginning of your list # Use insert() to add one new guest to the middle of the list # Use append() to add new guest to the end of your list names = ['Jackson', 'David', 'Campos', 'Ale'] for i in names: print("Hi,", i, "I would like to invite you to a Dinner ") print() cant = ['David', 'Ale'] print("{} and {} cant make it".format(cant[0], cant[1])) names.remove('David') names.remove('Ale') dinner = ['Jackson', 'Campos'] print("{} and {} are still available for the dinner.".format(dinner[0], dinner[1])) names.append('Ali') names.insert(3, 'Juan') names.insert(0, 'Jose') print() for i in names: print("Hi,", i, "I would like to invite you to a Dinner ")
true
790e577ae58d26aed9e2806cd77c874ad6056771
Jackson201325/Python
/Python Crash Course/Chapter 3 Lists/Seeing_the_world(3.8).py
989
4.625
5
# Store the locations in a list. Make sure the list is not in alphabetical order # Print your list in its iriginal order # Use sorted() to print your list in alphabetical order # Show that your list is still in its original order by printing it # Use sorted() to print your list in reverse alphaetical order without changing the order of the original list # Show that your list is still in its original order by printing it again # Use reverse() to change the order of your list. Print th elist to show tha tirs order has changed # Use reverse() to change the order of your list again. Print the list to show it's back that its order has been changed # Use sort() to change your list so its stired in alphabetical order. # Use sort() to change your list so its stored in in reverse alphabetical order places = ['London', 'Paris', 'New Zealand', 'Tokyo', 'Vancouver', 'Barcelona', 'California'] print(places) print(sorted(places)) print(places) places.sorted(reverse=True) print(places)
true
d848d874f72772dfdddfb9b90213a6758e19dc75
kmg1905/algorithms
/computer_science/algorithms/sorting/randomized_quick_sort.py
1,820
4.1875
4
""" Intuition: Since quicksort algorithm has a worst case time complexity of O(n*2) for certain input arrays. We need to some how mitigate this problem and make sure the worst case time complexity is made equal to average case time complexity. For this purpose, we can use new sorting algorithm called as "randomized quick sort". In this algorithm, we'll use random index as pivot and note that for any input array the average space and time complexities of this approach are O(log(n)) and O(nlog(n)) respectively. """ import random class Quicksort(object): def quicksort(self, input): self.quicksortHelper(input, 0, len(input) - 1) def quicksortHelper(self, input, low, high): if low < high: pivot = self.getRandomizedPivot(input, low, high) self.quicksortHelper(input, low, pivot - 1) self.quicksortHelper(input, pivot + 1, high) def getRandomizedPivot(self, input, low, high): randomPivot = random.randint(low, high) input[randomPivot], input[high] = input[high], input[randomPivot] return self.getPivot(input, low, high) def getPivot(self, input, low, high): pivot = input[high] pIndex = low for i in range(low, high): if input[i] <= pivot: input[i], input[pIndex] = input[pIndex], input[i] pIndex += 1 input[pIndex], input[high] = input[high], input[pIndex] return pIndex if __name__ == '__main__': obj = Quicksort() input = [9, 8, 7, 6, 5, 4, 3, 2, 1] obj.quicksort(input) print(input) # [1, 2, 3, 4, 5, 6, 7, 8, 9] input = [-1, 10] obj.quicksort(input) print(input) # [-1, 10] input = [9, 8, -7, 6, -5, 4, 3, -2, 1] obj.quicksort(input) print(input) # [-7, -5, -2, 1, 3, 4, 6, 8, 9]
true
6fe3bcd9fafcec2375b35812674090c504b8a68c
clubofcodes/python_codes
/Ass 1.2/O&E_Label_Till_N.py
247
4.125
4
def showNumbers(limit): print("List of Odd & Even Numbers till index :",limit-1) for n in range(0,limit): if n%2==0: print(n,"EVEN") else: print(n,"ODD") showNumbers(int(input("Enter the limit : ")))
true
7a34fa348cb1f5f3a2045a20bbb67f4988d778f0
lerahkp/Tip-Calculator
/main.py
635
4.125
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Tip: You might need to do some research in Google to figure out how to do this. print("Welcome to the tip calculator") bill = float(input("What was the total bill? ")) perc_share = int(input("What percentage tip would you like to give? 10, 12, or 15? ")) people_split = int(input("How many people to split the bill? ")) tip_calc = bill * (perc_share/100) tot_bill = bill+tip_calc each_share = round(tot_bill/people_split,2) print(f"Each person should pay: ${each_share}")
true
037c7de9aadf7a8f204234538d8d1b2ab7c44646
Marcin-Marcinek/Python
/script1.py
292
4.125
4
#!/usr/bin/python3 print("Debt calculator") debt = float(input("Ammount of debt (in PLN):")) daily_interest = float(input("Late fees per day: ")) days = int(input("Number of days since paydate: ")) total_debt = debt + daily_interest * days print("Total ammount of debt: ", total_debt, "PLN")
true
8bd98e5cb50e1c3d290da4520cb9cc41ba5245c6
vinnykuhnel/MethodsToolsUnitTest
/homework4/functions.py
2,146
4.1875
4
#Della Jones dj1069 #Teddy Lander tel127 #Raleigh Bumpers reb560 #Adam Kuhnel vak58 import math ## opens a file in read mode ## filename received as a parameter def openFile(filename): try: infile = open(filename, "r") print("File opened.") except ValueError: print("This is not a valid input. Try again, please") except FileNotFoundError: print("An error occurred") ## takes two numbers and returns ## the result of a division def numbers(num1, num2): if num2 != 0: return float(num1) /float(num2) ## takes in two points ## finds the distance between the points def dist(x1, y1, x2, y2): try: dist = float(x2 - x1) ** 2 + float(y2 - y1) ** 2 dist = math.sqrt(dist) return round(dist) except ValueError: print("This is not a valid input. Try again, please.") ## takes in a string -- reverses it ## then compares the two def isPalindrome(temp): try: test = temp[::-1] if(test == temp): return True else: return False except: print("This is not a valid input") return False ## has input to receive two numbers ## divides the two, then outputs the result def divide(): num1 = int(input("Enter a number: ")) num2 = int(input("Enter another number: ")) if num2 != 0: div = float(num1) /float(num2) print("Your numbers divided is:", div) ## returns the squareroot of a particular number def sq(num): try: return math.sqrt(num) except: print("This is not an allowed value for num") ## grabs user's name ## greets them by their entire name ## names should be strings def greetUser(first, middle, last): print("Hello!") print("Welcome to the program", first, middle, last) print("Glad to have you!") ## takes in a Python list ## attempts to display the item at the index provided def displayItem(numbers, index): if numbers and (len(numbers) + 1) > abs(index): print("Your item at", index, "index is", numbers[index])
true
0b5b5f32bb9c6cfe64bd664e35e0a8c3617efa72
Sarlianth/python-problems
/07-palindrome.py
522
4.46875
4
# Function that tests whether a string is a palindrome # Author: Adrian Sypos # Date: 23/09/2017 # Ask user to input a string print("Please enter a word to check for palindrome: ") # Read in the string word = input() # Bring the string to lower case for obvious comparison reasons word = word.casefold() # Logical statement to check if the string is equal to the same string reversed if(word == word[::-1]): print("This word is a palindrome!") # If it's not a palindrome.. else: print("Sorry, this word isn't a palindrome..")
true
b92a50ad18a8aca63b7c6a6af48fdae124818fb1
jaford/thissrocks
/daily_code/JF_Daily_Code_10:26_input+reverse.py
362
4.4375
4
#Write a Python program which accepts the user's first and last name # and print them in reverse order with a space between them. first_name = input('What is your first name? ') last_name = input('What is your last name? ') print('I will now attempt to print the last name first followed by the first name') print(f'Your output is: {last_name}, {first_name}')
true
43c8784d884e799caf5fba76f59c61f5a1c441b1
jaford/thissrocks
/jim_python_practice_programs/15.60_voting.py
247
4.28125
4
# Write a program that will let the user know if they can vote or not def voting(): age = int(input('How old are you? ')) # check if eligible to vote if age >= 18: print('Can Vote') else: print('Cannot Vote') voting()
true
23ecedd3b431e13c9c9f1048e32db3c55fe86820
jaford/thissrocks
/jim_python_practice_programs/29.60_print_user_input_fibonacci_numbers.py
440
4.34375
4
# Write a program that will list the Fibonacci sequence less than n def fib_num_user(): n = int(input('Enter a number: ')) t1 = 1 t2 = 1 result = 0 # loop as long as t1 is less than n while t1 < n: # print t1 print(t1) # assign sum of t1 and t2 to result result = t1 + t2 # assign t2 to t1 t1 = t2 # assign result to t2 t2 = result fib_num_user()
true
96eef37fd0286a7e063d61a83e1e460007f7bc05
jaford/thissrocks
/daily_code/JF_Daily_Code_8:2.py
744
4.21875
4
#random number guessing game #TODO: add guess counter import random correct_guess = random.randint(1,10) print("Random number is", correct_guess) #error checking for number guess = 0 attempts = 3 while correct_guess != guess: guess = int(input("I'm thinking of a number between 1 and 10, can you guess it in three guesses or less?")) attempts -= 1 if guess > correct_guess: print("Keep guessing! Your guess is too high!") if guess < correct_guess: print("Keep guessing! Your guess is too low!") if attempts == 0 : print("You've used too many guesses! My secret number was", str(correct_guess),"!") break if guess == correct_guess: print('Good job! You guessed my number!')
true
e303b8bcd7c9e2c212617fbc80ea4e5940117734
jaford/thissrocks
/daily_code/JF_Daily_Code_9:23_C_to_f_v2.py
711
4.3125
4
# This program is desgined to convert fahrenheit to celcius user_choice = int(input('Choose 1 or 2. CHOICE 1 will convert Celcius to Fahrenheit. CHOICE 2 will convert Fahrenheit to Celcius.')) if user_choice == 1: celcius_temp = int(input('Enter a temperature in Celcius: ')) f_to_c_temp = (celcius_temp * 9 / 5) + 32 print(f'{celcius_temp} degrees celcius is equal to {f_to_c_temp} degrees fahrenheit.') if user_choice == 2: fahrenheit_temp = int(input('Enter a temperature in fahrenheit: ')) c_to_f_temp = (fahrenheit_temp - 32) * 5 / 9 print(f'The temperature in celcius is: {c_to_f_temp}') else: user_choice < 2 or user_choice == str print('You entered an invalid choice')
true
e836f5453c15f61aec0832439da763dae8278e56
jaford/thissrocks
/programs/shortScripts/characterCounter.py
819
4.28125
4
# Enter a string that starts with a $ for this example # userInput = input('Enter random characters that check how many numbers and symbols there are! ---> ') # Test strings # $samh51jcj # $143718ash userInput = '$143718ash' for i in userInput: print('CHECK 1') print(i) if i[0] == "$": for v in range(1, len(userInput)): print('CHECK 2') print(userInput[v]) if userInput[1].isdigit: print('CHECK 3') print(userInput[v]) print(userInput(1:)) if not userInput[1].isdigit: print('skippings') # for i in userInput: # if i[0] == '$': # for char in i(): # if char.isdigit(): # print(char) # if not i[1].isdigit(): # print('Skipping')
false
2a8a8c3f1ef8ad752ec0d918bd2a4221f12d907d
jaford/thissrocks
/jim_python_practice_programs/26.60_numbers_until_0.py
319
4.375
4
# Write a program that will print the number the user enters except 0. # run a while loop that is always true while True: # take input for number number = int(input('Enter a number: ')) # terminate the loop if the user input is 0 if number == 0: break # print the number print(number)
true
2542a15861404db1e90b01e5bc59f91f49eb58c2
jaford/thissrocks
/jim_python_practice_programs/18.60_smallest_of_three.py
340
4.21875
4
# Replace ___ with your code number1 = int(input('Enter first number: ')) number2 = int(input('Enter second number: ')) number3 = int(input('Enter third number: ')) # check for smallest number using if...elif...else statement if number1 < number3: print(number1) elif number2 < number1: print(number2) else: print(number3)
false
2cd997338553f3d3297869b28418cad32f0f66fb
jaford/thissrocks
/daily_code/JF_Daily_Code_10:13_Interview_Question.py
565
4.125
4
#You have two strings 'abcde' and 'abcdXe' write a function that would print the difference def string_comparison (str1, str2): first_set = set(str1) second_set = set(str2) difference = first_set.symmetric_difference(second_set) print(difference) string_comparison('abcde', 'abcdXe') ## print(first_set.difference(second_set)) # for i in str1: # for j in str2: # #if str1 != str2: # print(f'The difference is {i},{j}') # if str1 != str2: # print('True') string_comparison('abcde','abcdXe')
true
e920adb3de67923a46e151a9c2ebe2742f3f0518
jaford/thissrocks
/Python_Class/py3intro3day 2/EXAMPLES/fmt_params.py
457
4.34375
4
#!/usr/bin/env python person = 'Bob' age = 22 print("{0} is {1} years old.".format(person, age)) # <1> print("{0}, {0}, {0} your boat".format('row')) # <2> print("The {1}-year-old is {0}".format(person, age)) # <3> print("{name} is {age} years old.".format(name=person, age=age)) # <4> print() print("{} is {} years old.".format(person, age)) # <5> print("{name} is {} and his favorite color is {}".format(22, 'blue', name='Bob')) # <6>
false
823b05a2f5f1df65bf2fcb1459db377897c7b2e0
RiflerRick/codemonk2017
/NumberTheory/ClosedGiftFinalSolution.py
1,732
4.25
4
""" This solution uses a very efficient method of finding out whether a number is prime or not. This algorithm is really fast for finding if a number is prime or not. The loop part is executed for numbers greater then 25. We start from 5 and alternately add 2 and 4 at each step. Remember that primes are always in the form 6k+1 or 6k-1. For this one if we start from 5, this would be 5 , (5+2), (5+2+4), (5+2+4+2) and so on. One primality test is that for checking whether a number p is prime or not. First find the smallest value of n such that n*n<=p. Now check if p is divisible by any number less than n. If so then p is prime or not. """ def isprime(n): """Returns True if n is prime.""" if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: print('i*i at the beginning: '+str(i*i)) if n % i == 0: return False i += w w = 6 - w print('i and w at the end: '+str(i)+', '+str(w)) return True def answer(n): if n==0: return 2 elif n==1: return 1 if isprime(n): return 0 num=n-1 while True: # finding the previous prime number if isprime(num): prevPrime=num break num-=1 num=n+1 while True: if isprime(num): nextPrime=num break num+=1 dif1=abs(prevPrime-n) dif2=abs(nextPrime-n) if dif1<dif2: return dif1 else: return dif2 def main(): # a=int(input()) # print(answer(a)) print(isprime(103)) if __name__=="__main__": main()
true
e79d0e8eec67f6f1766f27ef021ad5a2e885970b
yang7988/python-foundation
/function/say_hello.py
1,005
4.125
4
# 函数(Functions)是指可重复使用的程序片段。它们允许你为某个代码块赋予名字,允许你 # 通过这一特殊的名字在你的程序任何地方来运行代码块,并可重复任何次数。这就是所谓的 # 调用(Calling)函数。我们已经使用过了许多内置的函数,例如 len 和 range 。 # 函数概念可能是在任何复杂的软件(无论使用的是何种编程语言)中最重要的构建块,所以 # 我们接下来将在本章中探讨有关函数的各个方面。 # 函数可以通过关键字 def 来定义。这一关键字后跟一个函数的标识符名称,再跟一对圆括 # 号,其中可以包括一些变量的名称,再以冒号结尾,结束这一行。随后而来的语句块是函数 # 的一部分。下面的案例将会展示出这其实非常简单: def say_hello(): # 该块属于这一函数 print('hello world') # 函数结束 say_hello() # 调用函数 say_hello() # 再次调用函数
false
52d3ea61c4b3321e95c03baeec30d6354b8422cb
yang7988/python-foundation
/foreach/break.py
856
4.1875
4
# break 语句用以中断(Break)循环语句,也就是中止循环语句的执行,即使循环条件没有 # 变更为 False ,或队列中的项目尚未完全迭代依旧如此。 # 有一点需要尤其注意,如果你的 中断 了一个 for 或 while 循环,任何相应循环中的 # else 块都将不会被执行。 def while_break(): while True: s = input('Enter something : ') if s == 'quit': break print('Length of the string is', len(s)) print('Done') def while_break1(): while True: s = input('Enter something : ') if s == 'quit': break print('Length of the string is', len(s)) # 如果while被break中断了此处的else将不会被执行 else: print('Done') if __name__ == '__main__': # while_break() while_break1()
false
9e23255dcba3742c9caffbcb17a720e7e5dbb6fd
haptikfeedback/python_basics
/masterticket.py
1,078
4.1875
4
SERVICE_CHARGE = 2 TICKET_PRICE = 10 tickets_remaining = 100 def calculate_price(number_of_tickets): return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining >= 1: print("There are {} tickets remaining".format(tickets_remaining)) name = input("What is your name? ") num_tickets = input("{}, How many tickets would you like? ".format(name)) try: num_tickets = int(num_tickets) if num_tickets > tickets_remaining: raise ValueError("There are only {} ticket's remaining.".format(tickets_remaining)) except ValueError as err: print("Oh no, we ran into an issue. {}. Please try again.".format(err)) else: amount_due = calculate_price(num_tickets) print("Total due is {}".format(amount_due)) should_proceed = input("Do you want to proceed? Y/N ") if should_proceed.lower() == "y": print("Sold") tickets_remaining -= num_tickets else: print("Thank you anyways, {}.".format(name)) print("Sorry, we are sold out")
true
8e4751931f1fc41b1b720e38e2774d0010550e9f
MAMBA-python/course-material
/Exercise_notebooks/Intermediate/04_modules_and_packages/example_package/somepackage/shout.py
655
4.15625
4
from .add import my_add def shout_and_repeat(text): """ Describe here what this function does, its input parameters, and what it returns. In this example the function converts the input string to uppercase and repeats it once. """ t = _shout(text) result = my_add(t, t) return result # the underscore signals that this function is not to be used outside this # module def _shout(text): """ Describe here what this function does, its input parameters, and what it returns. In this example the function converts the input string to uppercase. """ result = text.upper() return result
true
25867f1be45091c3f969ff874c955cf5e417423e
HYnam/Python-basic
/list_length.py
416
4.28125
4
# Write code to create a list of word lengths for the words in original_str using the accumulation pattern # and assign the answer to a variable num_words_list. (You should use the len function). original_str = "The quick brown rhino jumped over the extremely lazy fox" split_str = original_str.split() num_words_list=[] for words in split_str: num_words_list.append(len(words)) print(num_words_list)
true
d2240aea2debd56e1690e736165b184992707785
KayleighPerera/COM411
/Basics/Week2/or_operator.py
394
4.28125
4
# Ask user to enter type of adventure print ("what is the adventure type?") adventure_type = input() # detrmine what the type of adventure is if ( (adventure_type == "scary") or (adventure_type == "short") ): print("\nEntering the dark forest!") elif ( (adventure_type == "safe") or (adventure_type == "long") ): print("Taking the safe route") else: print("Not sure which route to take")
true
32e239e5a27031de5df104824df9f6425f7ce8b7
devmohit-live/Adv_Python_Rev
/Collections files/ordered_dictionaries.py
1,330
4.125
4
# Keeps track of keys order (order in which the key,values are added) from collections import OrderedDict od = OrderedDict() normal_dict = {} od['Name'] = 'Mohit' od['Branch'] = 'IT' od['Year'] = 3 od['City'] = 'xyz' od2=OrderedDict() od2['Year'] = 3 od2['City'] = 'xyz' od2['Name'] = 'Mohit' od2['Branch'] = 'IT' normal_dict['Name'] = 'Mohit' normal_dict['Branch'] = 'IT' normal_dict['Year'] = 3 normal_dict['City'] = 'xyz' nd = {} nd['Branch'] = 'IT' nd['Year'] = 3 nd['City'] = 'xyz' nd['Name'] = 'Mohit' # //passing the normal dictionary to OrderedDict doesn't makes it ordered, since the passed dictionary values will be like city,name,branch and year only # that is OrderedDict(normal_dict) doesn't help you if __name__ == "__main__": print('Order dict ', od) print('Normal dict ', normal_dict) print('Printing Keys::') # since it is a special case of dictionary all the proprties and fuctions can be applied to od too print(od.keys()) print(normal_dict.keys()) print("Comaprison between them == ") print("nd==normal_dict (two dict having same kv in different order)", normal_dict == nd) print("od==od2 (two ordereddict having same kv in different order)", od2 == od) print("od==normal_dict will always be true having same set of k,v", normal_dict == od2)
true
e7b7507a053b8ea026876b12c2cf35e3a4736a03
mkeita94/OOP-Practice
/Python/abstract.py
575
4.1875
4
# Cannot create an instance of an abstract class # Abstraction in Python # ABC- Abstract Base # All classes that extend or inherit an abstract class # should implements all the methods in in the abstract class from abc import ABC, abstractmethod class Computer(ABC): @abstractmethod def process(self): pass class Laptop(Computer): def process(self): print("It's running") class Phone(Computer): def process(self): print("Processing phone data") ph = Phone() #com = Computer() com1 = Laptop() com1.process()
true
638bfda8545df013e944dcad2f3f36eeb43fc72c
guoliangxd/interview
/huawei/Python/findLastWordLen.py
412
4.15625
4
# 返回最后一个单词长度 def findLastWordLen(arg): """ 将输入的字符串去掉首尾空格后按空格分隔为字串列表,返回最后一个字串的长度""" if(arg.find(" ") == -1): #输入无空格时直接返回字符串长度 return len(arg) arg = arg.strip() substr = arg.split(' ') return len(substr[-1]) str = input() print(findLastWordLen(str))
false
05b03f1904bba186449fb93d12db66bc58eb712a
augustomy/Curso-PYTHON-01-03---Curso-em-Video
/desafio033aula10.py
665
4.125
4
n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo número: ')) n3 = float(input('Digite o terceiro número: ')) if n1 >= n2 >= n3: print('Maior número: {}\nMenor número: {}'.format(n1, n3)) if n1 >= n3 >= n2: print('Maior número: {}\nMenor número: {}'.format(n1, n2)) if n2 >= n1 >= n3: print('Maior número: {}\nMenor número: {}'.format(n2, n3)) if n2 >= n3 >= n1: print('Maior número: {}\nMenor número: {}'.format(n2, n1)) if n3 >= n1 >= n2: print('Maior número: {}\nMenor número: {}'.format(n3, n2)) if n3 >= n2 >= n1: print('Maior número: {}\nMenor número: {}'.format(n3, n1))
false
74bae85dd8a1e73c26996a2c80c9a2ed9febd8c3
Luksos9/LearningThroughDoing
/automateboringstuff/someSimplePrograms/TablePrinter.py
928
4.40625
4
#!/usr/bin/python3 tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(table): #Create a list with each element representing columns that will store each column max width columnWithds = [0] * len(table) for list in range(len(table)): #range(len(table)) represents index of list in tableData #for every element in each list in table, we comparing their lenghts(they are string) and choosing the biggest for element in table[list]: if columnWithds[list] < len(element): columnWithds[list] = len(element) # Print list of lists for element in range(len(table[0])): for list in range(len(table)): print(table[list][element].rjust(columnWithds[list]), end = ' ') print() element += 1 printTable(tableData)
true
d10f7b805e2229dad381280cbf2dc817235f08e5
dhananjay-arora/Coin-Changes-Greedy-Algorithm
/Answer3.py
1,002
4.3125
4
# Assumption: One coin_denominations should be penny. # O(nk)-time algorithm that makes change for any set of k different coin denominations n = int(input("Enter the value in cents you want change for:")) denomination_number = int(input("Enter how many coin_denominations you want to enter: ")) print("Enter the coin_denominations: ") coin_denominations = [int(input()) for c in range(denomination_number)] # order will be sorted in decreasing order coin_denominations = sorted(coin_denominations, reverse=True) number_of_coins = [] # Loop will run k times for c in range(denomination_number): number_of_coins.append(0) while(n >= coin_denominations[c]): n -= coin_denominations[c] number_of_coins[c]+=1 print("Denomination value in Descending order : ",coin_denominations) print("Number of times each denomination is occuring respectively: ",number_of_coins)
true
32bf723ebd71f8ae30fa1c5f56d3a712a55280fd
danielscarvalho/FTT-Compiladores-Python-2
/p12.py
401
4.28125
4
while True: number = input("Entre com um valor: ") if len(number) == 0: break number = float(number) if number > 2: print("Number is bigger than 2.") elif number < 2: # Optional clause (you can have multiple elifs) print("Number is smaller than 2.") else: # Optional clause (you can only have one else) print("Number is 2.")
true
dbf474b0b2a9fccb8cd8b3fbe5b5c7379bc4c108
hinsonan/ThinkPython
/ThinkPython/Chap8/8.2.py
428
4.3125
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 21 08:00:54 2018 @author: hinson There is a string method called count that is similar to the function in Section 8.7. Read the documentation of this method and write an invocation that counts the number of a’s in 'banana'. """ def main(): string = 'banana' numberOfSearchedCharacter = string.count('a') print(numberOfSearchedCharacter) main()
true
8ecd0ce4a6322306888bf8b93a06f8091785f63c
hinsonan/ThinkPython
/ThinkPython/Chap3/3.1.py
303
4.125
4
#Write a function named right_justify that takes a string named s as a parameter #and prints the string with enough leading spaces so that the last letter of the string is in column 70 #of the display. def right_justify(s): print (' '*(70-len(s))+s) def main(): right_justify('Becca') main()
true
62383654407fafcea774eb6a7928e564efd143be
adang1345/Project_Euler
/5 Smallest Multiple.py
855
4.25
4
"""Computes the smallest number that is divisible by 1 through 20""" def isdivisible(num): """Determines whether num is divisible by 1 through 20. If and only if num is divisible by 11, 13, 14, 16, 17, 18, 19, and 20, then num must be divisible by all numbers from 1 through 20. Assume num is a positive integer.""" for divisor in [11, 13, 14, 16, 17, 18, 19, 20]: if num % divisor != 0: return False return True # Answer is known to be larger than 2520, which is divisible by 20. Start at 2520 and test whether it is divisible by # all numbers from 1 to 20. If not, start testing the integer 20 greater. a = 2520 while not isdivisible(a): a += 20 # perform final test and raise error if answer given is wrong for x in range(1, 21): if a % x != 0: raise Exception("Logical error in code.") print(a)
true
f5b3a50f2885bc847caf3b55daca9c58b7b241d0
adang1345/Project_Euler
/3 Largest Prime Factor.py
1,379
4.15625
4
"""Computes the largest prime factor of 600851475143""" def isprime(num): """Determine whether num is prime. If any integer from 2 to the square root of num divides evenly into num, then num is composite. Otherwise, num is prime. Assume that num is an int greater than or equal to 2.""" for x in range(2, int(num ** 0.5) + 1): if num % x == 0: return False return True def primefactors(num): """Return list containing prime factorization of num. Begin with a list containing only num. While the last element of this list is not prime, find the smallest prime number that divides into the last element. Replace that last element with its smallest prime divisor and its cofactor. The cofactor is the former last element divided by its smallest prime factor. In the search for smallest prime factor of a number, it is necessary to test only the ints from 2 to the square root of the number.""" factors = [num] while not isprime(factors[-1]): for y in range(2, int(factors[-1] ** 0.5) + 1): if num % y == 0 and isprime(y): del factors[-1] factors.append(y) leftover = num // y factors.append(leftover) num = leftover break return factors # print result print(primefactors(600851475143))
true
55280d87e90267b0f9d9355ef944f72b32afa817
adang1345/Project_Euler
/60 Prime Pair Sets.py
2,383
4.25
4
"""The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.""" def is_prime(num): """Determine whether num is prime. If any integer from 2 to the square root of num divides evenly into num, then num is composite. Otherwise, num is prime. Assume that num is an int greater than or equal to 2.""" for x in range(2, int(num ** 0.5) + 1): if num % x == 0: return False return True def prime_after(n): """return smallest prime greater than n""" n += 1 while not is_prime(n): n += 1 return n def concatenate(a, b): """Return a concatenation of ints a and b.""" return int(str(a) + str(b)) def concatenate_prime(a, b): """Return True if a and b concatenate in either order to form primes, False otherwise.""" return is_prime(concatenate(a, b)) and is_prime(concatenate(b, a)) # generate list of primes up to 100000 primes = [2] while primes[-1] < 10000: primes.append(prime_after(primes[-1])) # search for 5 primes that concatenate for p1 in range(len(primes)): for p2 in range(p1 + 1, len(primes)): if concatenate_prime(primes[p1], primes[p2]): for p3 in range(p2 + 1, len(primes)): if concatenate_prime(primes[p1], primes[p3]) and concatenate_prime(primes[p2], primes[p3]): for p4 in range(p3 + 1, len(primes)): if concatenate_prime(primes[p1], primes[p4]) and concatenate_prime(primes[p2], primes[p4]) and concatenate_prime(primes[p3], primes[p4]): for p5 in range(p4 + 1, len(primes)): if concatenate_prime(primes[p1], primes[p5]) and concatenate_prime(primes[p2], primes[p5]) and concatenate_prime(primes[p3], primes[p5]) and concatenate_prime(primes[p4], primes[p5]): answer = [primes[p1], primes[p2], primes[p3], primes[p4], primes[p5]] print(answer, sum(answer)) break
true
b8043956a641116eaf01cf334bd15e01bf5d5e8c
adang1345/Project_Euler
/41 Pandigital Prime.py
1,301
4.1875
4
"""We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists?""" from itertools import permutations def isprime(num): """Determine whether num is prime, given that num is int >= 1 If any integer from 2 to the square root of num divides evenly into num, then num is composite. Otherwise, num is prime. Assume that num is an int greater than or equal to 2.""" if num == 1: return False for x in range(2, int(num ** 0.5) + 1): if num % x == 0: return False return True # make sorted list (from largest to smallest) of all pandigital numbers that might be prime perms = list(permutations("123456789")) + list(permutations("12345678")) + list(permutations("1234567")) + \ list(permutations("123456")) + list(permutations("12345")) + list(permutations("1234")) + \ list(permutations("123")) + list(permutations("12")) perms = [int("".join(a)) for a in perms if int("".join(a))%2==1] perms.sort(reverse=True) # test each value in list of pandigital numbers until first (and therefore largest) prime is found for x in perms: if isprime(x): print(x) break
true
ad9134b038e359b4ebdf81b9b797db5cbe768576
OcanoMark/CodingBat
/Python/String-1/03_make_tags.py
346
4.34375
4
# The web is built with HTML strings like "<i>Yay</i>" which draws Yay # as italic text. In this example, the "i" tag makes <i> and </i> which # surround the word "Yay". Given tag and word strings, create the HTML # string with tags around the word, e.g. "<i>Yay</i>". def make_tags(tag, word): return "<" + tag + ">" + word + "</" + tag + ">"
true
462ac9a85d6bc6fb7b67357293dc32fc8f1a8490
shouliang/Development
/Python/LeetCode/102_binary_tree_level_order_traversal.py
2,498
4.21875
4
''' 二叉树按层次遍历 102. Binary Tree Level Order Traversal:https://leetcode.com/problems/binary-tree-level-order-traversal/ 思路: 使用队列这种数据结构:首先根节点进入队列,然后在队列头部弹出节点的同时,将其左右分支依次插入队列的尾部, 直至队列为空 其实这就是图的bfs,但是二叉树就是一种特殊的图 ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] result = [] queue = [] # 队列 queue.append(root) # 根节点进入队列 while queue: cur_level = [] level_size = len(queue) for _ in range(level_size): # 遍历当前层,处理完当前层,再将当前层的一维数组加入到二维结果中 node = queue.pop(0) # 在队列头部弹出节点的同时,将其左右分支依次append()到队列的尾部 cur_level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(cur_level) return result class Solution2(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] result = [] queue = [] # 队列 queue.append(root) # 根节点进入队列 while queue: node = queue.pop(0) # 在队列头部弹出节点的同时,将其左右分支依次append()到队列的尾部 result.append(node.val) # 处理结点,访问其相邻的节点并进入队列 if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result s = Solution() root = TreeNode(3) treeNode1 = TreeNode(9) treeNode2 = TreeNode(20) root.left = treeNode1 root.right = treeNode2 treeNode3 = TreeNode(15) treeNode4 = TreeNode(7) treeNode2.left = treeNode3 treeNode2.right = treeNode4 ret = s.levelOrder(root) print(ret) s2 = Solution2() ret = s2.levelOrder(root) print(ret)
false
b6fb84a877ad38392216216fd2b11b53fdefdd21
shouliang/Development
/Python/LeetCode/ByteDance/103_zigzag_level_order_in_bs.py
2,246
4.125
4
''' Z字型遍历二叉树 103. Binary Tree Zigzag Level Order Traversal:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 解释: 给定一个二叉树,返回其节点值的锯齿形层次遍历。 (即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回锯齿形层次遍历如下: [ [3], [20,9], [15,7] ] ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] result = [] queue = [] # 队列 queue.append(root) # 根节点进入队列 flag = True while queue: cur_level = [] level_size = len(queue) for _ in range(level_size): node = queue.pop(0) if flag else queue.pop() cur_level.append(node.val) if flag: # 加入队列尾部:left->right,出队列时反而从队列头部开始 if node.left: queue.append(node.left) if node.right: queue.append(node.right) else: # 加入队列头部:right->left, 出队列时反而从队列尾部开始 if node.right: queue.insert(0, node.right) if node.left: queue.insert(0, node.left) flag = not flag # 隔行变换标志 result.append(cur_level) return result s = Solution() root = TreeNode(3) treeNode1 = TreeNode(9) treeNode2 = TreeNode(20) root.left = treeNode1 root.right = treeNode2 treeNode3 = TreeNode(15) treeNode4 = TreeNode(7) treeNode2.left = treeNode3 treeNode2.right = treeNode4 ret = s.zigzagLevelOrder(root) print(ret)
false
78a7aac950c98a644b7a40f02dd91d1dd750ec95
shouliang/Development
/Python/LeetCode/ByteDance/122_best_time_to_buy_sell_stock_II.py
2,939
4.34375
4
''' 买卖股票的最佳时机(最大利润):可以交易多次 122. Best Time to Buy and Sell Stock II:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 解释: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 思路: 贪心法:既然能买卖任意次,那最大收益的方法就是尽可能多的低入高抛。只要明天比今天价格高,就应该今天买入明天再卖出。 ''' class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ maxProfit = 0 for i in range(1, len(prices)): if prices[i] > prices[i - 1]: # 贪心算法:只要明天比今天价格高,就应该今天买入明天再卖出。 maxProfit += prices[i] - prices[i - 1] return maxProfit prices = [7, 1, 5, 3, 6, 4] s = Solution() mp = s.maxProfit(prices) print(mp) # 动态规划的解法 # dp[i][0],dp[i][1]代表 the i day, have or not stock,即第i天是否拥有股票哟,0代表没有,1代表当天持有股票。 # dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) # #即第i天没股票的最大收益,dp[i-1][0]代表前一天没有股票,dp[i-1][1]+prices[i]前一天有股票并卖出,而第i天的最大收益会是这两者之间的最大值。 # dp[i][1] = max(dp[i - 1][0] - prices[i], dp[i - 1][1]) # #即第i天持有股票时的最大收益,dp[i-1][0]-prices[i]代表前一天没有股票并买入,dp[i-1][1]表示前一天持有股票的最大收益 class Solution2: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 # 错误处理 dp = [[0, 0]] * len(prices) # 初始化 dp[0][0] = 0 # 第0天没有股票,收益为0 dp[0][1] = -prices[0] # 第0天有股票, 收益为负数 for i in range(1, len(prices)): # 第i天没有股票:取(第i-1天也没有股票) 和 (第i-1天有股票并卖出的收益之和,因为卖出故收益需要加上当天股票价格)的最大值 dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) # 第i天有股票 : 取(第i-1天也有股票) 和 (第i-1天没有股票并买入的收益之和,因为买入故收益需要减去当天股票价格)的最大值 dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + (-prices[i])) return dp[len(prices) - 1][0] # 返回最后一天没有股票的情况 prices = [7, 1, 5, 3, 6, 4] s = Solution2() mp = s.maxProfit(prices) print(mp)
false
a8659f5d1210f3b9259a8b64456aca02b02c3549
shouliang/Development
/Python/PythonBasic/range.py
429
4.375
4
# coding=utf-8 # range()返回一个可迭代对象, # range(start,stop[, step]) # start:默认0 # end:计数到stop结束,但是不包括stop # step:默认1 # list()函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表 for i in range(5): print(i) print('----------') r1 = list(range(5)) print(r1) r2 = list(range(0, 10, 2)) print(r2) r3 = list(range(0, 11, 2)) print(r3)
false
111695137d815680b1701cd420e75a34ba89e801
DrCarolineClark/CtCI-6th-Edition
/Python/Chapter2/24Partion.py
1,656
4.15625
4
class node: def __init__(self): self.data = None # contains the data self.next = None # contains the reference to the next node class linked_list: def __init__(self): self.head = None self.last_element = None def add_node(self, data): new_node = node() # create a new node new_node.data = data new_node.next = self.head # link the new node to the 'previous' one self.head = new_node # set the current node to the new one. if not self.last_element: self.last_element = self.head def list_print(self): node = self.head while node: print node.data node = node.next def partition_list(self, partitionvalue): less = linked_list() more = linked_list() node = self.head while node: if node.data < partitionvalue: less.add_node(node.data) else: more.add_node(node.data) node = node.next less.last_element.next = more.head return less def fill_list(): ll = linked_list() ll.add_node(1) ll.add_node(2) ll.add_node(3) ll.add_node(7) ll.add_node(4) ll.add_node(2) ll.add_node(2) ll.add_node(7) ll.add_node(7) ll.add_node(9) ll.add_node(3) ll.add_node(3) return ll def Partition(partitionvalue): ll=fill_list() print "Initial List" ll.list_print() ll = ll.partition_list(partitionvalue) print "Final List" ll.list_print() partitionvalue = 4#node number to partition around Partition(partitionvalue)
true
8584ffe1668412fb151552496023ce7ca32a3721
alexh13/practicing-using-pandas
/pandas-intro.py
1,188
4.5625
5
# -pandas is a library used for data structures and data analysis tools. # -used for loading data, web-scraping, loading & analyzing data from excel files # * type ipython into to terminal * import pandas df1 = pandas.DataFrame([[2, 4, 6], [10, 20, 30]]) # Create a dataframe named df1 print(df1) # output dataFrame, numbers on left top - bottom are indexes, top left - right are columns print() # in pandas we can name columns individually using column= like this df1 = pandas.DataFrame([[2, 4, 6], [10, 20, 30]], columns=["Price", "Age", "Value"]) print(df1) print() # we can pass custom names for indexes as well using index=, like this df1 = pandas.DataFrame([[2, 4, 6], [10, 20, 30]], columns=["Price", "Age", "Value"], index=["First", "Second"]) print(df1) print() # we can pass dictionaries too like this df2 = pandas.DataFrame([{"Name": "Alex"}, {"Name": "Jack"}]) print(df2) print() # add a surname like this df2 = pandas.DataFrame([{"Name": "Alex", "Surname": "Alexx"}, {"Name": "Jack"}]) print(df2) print() # we can get the mean like this df1.mean() print(df1.mean()) print() # or the mean of the entire data frame like this df1.mean().mean() print(df1.mean().mean())
true
08fcdf096a5476868f6c0c66a7db9619003f306d
Nvardharutyunyan/group-sudo
/nvard/python/#2/sumDigits_R.py
297
4.21875
4
#!usr/bin/env python3 def sumOfNum_R(number): if number == 0: return 0 else: return (number % 10) + sumOfNum_R(number // 10) num = int(input("Enter the number : ")) if num < 0 : print ("Your number is not natural!") else : print("The sum of number is equal ", sumOfNum_R(num))
true
8a651d47bd71be5a3b86d3c74ac7d07959bd516d
LaKeshiaJohnson/MasterTicket
/masterticket.py
1,547
4.3125
4
#Run code until tickets run out #Output how many tickets remaining using tickets_remaining variable #Gather the user's name and assign it to a new variable #Prompt user by name to ask how many tickets they would like #Calculate price and output to screen #Prompt user if they want to continue. Y/N #if they want to proceed print out to the "SOLD!" to confirm purchase and updated number of tickets remaining #otherwise, thank them by name #Notify users when tickets are sold out TICKET_PRICE = 10 tickets_remaining = 100 def calculate_price(quantity): return quantity * TICKET_PRICE while tickets_remaining >= 1: print("There are {} tickets remaining.".format(tickets_remaining)) name = raw_input("Welcome. What is your name? ") quantity = raw_input("Hello, {}. How many tickets would you like to purchase? ".format(name)) try: quantity = int(quantity) #Raise ValueError if the request is for more tickets than available if quantity > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) except ValueError as err: print("We ran into an issue. {} Please try again.".format(err)) else: amount_due = calculate_price(quantity) print("The total due is ${}".format(amount_due)) proceed = raw_input("To contunue with your order? Y/N ") if (proceed.lower() == "y"): #TODO: Gather credit card info and process print("SOLD!") tickets_remaining -= quantity else: print("Thank you anyways, {}!".format(name)) print("Sorry the tickets are all sold out :(")
true
20af00eb4cef13ab24fa2ca2705b743383d20b39
colknives/basic-python
/sample/test.py
2,647
4.3125
4
''' Sample print function ''' print('This is an example of a print function') ''' Sample variable ''' testVar = "Sample text" print(testVar) ''' Sample packing ''' x,y = (3,5) print(x) print(y) ''' Sample while condition ''' condition = 1 while condition < 10: print(condition) condition += 1 ''' Sample for loop ''' exampleList = [1,2,3,4,5,6,7,8,9] for x in exampleList: print(x) for y in range(1,11): print(y) ''' Sample if condition ''' x = 1 y = 8 z = 5 a = 5 if x < y: print('x is less than y') if x < y > z: print('x is less than to y and y is greater than z ') if a == z: print('a is equal to z') ''' Sample if else condition ''' x = 5 y = 8 if x > y: print('x is greater than y') else: print('y is greater than x') ''' Sample if elif else condition ''' x = 5 y = 10 z = 22 if x > y: print('x is grater than y') elif x < z: print('x is less than z') else: print('none') ''' Sample function ''' def sample(): print('sample function') sample() ''' Sample function w/ parameters ''' def addition(num1,num2 = 5): answer = num1 + num2 return answer print(addition(1,3)) def window(width, height, font = 'TNR', bgc='w'): print(width, height, font, bgc) window(500, 200, 'Calibri') window(200, 700, bgc='r') ''' Sample local and global variables ''' x = 6 def example(): globx = x globx += 5 return globx print(example()) ''' Sample write to file ''' text = 'Sample Text to Save \nnew line!' saveFile = open('exampleFile.txt','w') saveFile.write(text) saveFile.close() ''' Sample append to file ''' appendMe = '\nNew information' appendFile = open('exampleFile.txt','a') appendFile.write('\n') appendFile.write(appendMe) appendFile.close() ''' Sample read to file ''' readMe = open('exampleFile.txt','r').read() print(readMe) ''' Sample convert each line on file into a list ''' readList = open('exampleFile.txt','r').readlines() print(readList) ''' Sample class ''' class calculator: def addition(num1, num2): added = num1 + num2 return added def subtraction(num1, num2): subtract = num1 - num2 return subtract def multiplication(num1, num2): multiply = num1 * num2 return multiply def division(num1, num2): divide = num1 / num2 return divide print(calculator.division(15,3)) ''' Sample custom modules / importing modules ''' import calculator2 as calc print(calc.addition(15,3)) from calculator2 import * print(subtraction(12,4)) ''' Sample get user input ''' x = input('What\'s your name: ') print('Hello ',x)
false
753d7fba1cc4654f8f184342bc35258becc8cb3f
nutcheer/pythonlearning
/pr4_10.py
291
4.5625
5
names = ['one','two','three','four','five'] print("The first three names are ") for name in names[:3]: print(name) print("Three items from the middle of the list are ") for name in names[1:4]: print(name) print("The last three items in the list are ") for name in names[-3:]: print(name)
false
a2dd2109b50309900c072eec2a595f18527b4339
nutcheer/pythonlearning
/pr6_6.py
346
4.15625
4
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } names = ['jen', 'sarah', 'tiffany', 'nutcheer'] for name in favorite_languages.keys(): if name in names: print(name+", thank you for your attending!") else: print(name+", I am glad to invite you to our survey.")
true
7e54459b7677906d392f6da4cc03e9662128de8e
sinitsa2001/h_work
/Lesson2/Home2.2.py
1,175
4.25
4
#Для списка реализовать обмен значений соседних элементов, т.е. # Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). # не понимаю - как завести в цикл...не работает, # ну и с нечетным тоже не все понятно # ...вроде как должно...проверяю = не понятно)) my_list = [1,2,3,4,5,6,7,8,9] print(my_list[-1]) #i=(my_list[0]) #n=(my_list[1]) #print(i,n) #while True: for item in range(len(my_list)): my_list[0], my_list[1] = my_list[1], my_list[0] my_list[2], my_list[3] = my_list[3], my_list[2] my_list[4], my_list[5] = my_list[5], my_list[4] my_list[6], my_list[7] = my_list[7], my_list[6] if my_list[-1] // 2 != 0: break elif my_list[-1] //2 ==0: continue print(my_list)
false
cd045d94572fd6ae5c50ef2a06c5d33055411977
AYAN-AMBESH/learning-Python
/ex17.py
391
4.1875
4
#Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum. num1 = input("ENTER NUMBER: ") num3 = input("ENTER NUMBER: ") num2 = input("ENTER NUMBER: ") def Sum_of_num(num1,num2,num3): sum = num1 + num2 + num3 if num1 == num2 == num3: sum *= 3 return sum print(Sum_of_num(1,2,3)) print(Sum_of_num(3,3,3))
true
7d0b68ff37e131779042de77c5510b177cc86fba
AYAN-AMBESH/learning-Python
/ex25.py
281
4.40625
4
#Write a Python program to find whether a given number (accept from the user) is even or odd, #print out an appropriate message to the user n = int(input("Enter a number: ")) if n%2==0: print("{} is a even number. ".format(n)) else: print("{} is a odd number. ".format(n))
true
296f5548557486ae7a0e4127e179e4944ed2ff03
AYAN-AMBESH/learning-Python
/ex7.py
245
4.125
4
#Write a short Python function that takes a positive integer n and returns #the sum of the squares of all the positive integers smaller than n def Square(n): Sum=0 for i in range(0,n): Sum += i**2 return Sum print(Square(5))
true
34047e9fb0c2f4e04c39edb80bc590794d34c027
atavener68/intro_to_python
/problem4.py
806
4.34375
4
# Write a function named reverse_me that # takes a string as a parameter, # and returns the reversed string. # # Do this without using pythons [::-1] slice shortcut, # or the built in reversed() method # # You will need to count down from the length of the string, # and build up the output one piece at a time. # # The input ABC should return BCA as output def reverse_me(input_text): output = "" text_length = len(input_text) offset = 0 while offset < text_length: index = text_length - offset - 1 letter = input_text[index] output = output + letter offset += 1 return output # TEST result = reverse_me("ABC") assert ("CBA" == result) #DEMO # print("ENTER TEXT TO BE REVERSED:") # data = input() # result = reverse_me(data) # print(result)
true
0a7cb008779c84830c21a282b2e9ded30dfb3aeb
GRustle00/pathofpython
/lpthw/ex19/ex19.py
1,304
4.125
4
#call defined function cheese_and_crackers where the argumens are cheese_count, boxes_of_crackers def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a blanket.\n") #print message below, call function cheese_and_crackers directly adding (20, 30) as the values print("We can just give the function numbers directly:") cheese_and_crackers(20, 30) #print message below, setting variables to then call it on the defined function print("OR, we can use variables from our script:") amount_of_cheese = 10 amount_of_crackers = 50 #calling the defined function using the variables set previously on line 13 an 14 (amount_of_cheese, amount_of_crackers) cheese_and_crackers(amount_of_cheese, amount_of_crackers) #print message below, call defined function directly setting the value as a sum print("We can even do math inside this too:") cheese_and_crackers(10 + 20, 5 + 6) #print message bewlo, calling defined function using a sum with the values set in the variables in line 13 and 14 and provided numbers. print("And we can combine the two, variables and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
true
ae277b3a45616ff0f07b57049489dd243cafdfb8
MAdisurya/data-structures-algorithms
/questions/reverse_words.py
2,775
4.6875
5
""" Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault. The message has been mostly deciphered, but all the words are backward! Your colleagues have handed off the last step to you. Write a function reverse_words() that takes a message as a list of characters and reverses the order of the words in place. Why a list of characters instead of a string? The goal of this question is to practice manipulating strings in place. Since we're modifying the message, we need a mutable type like a list, instead of Python 3.6's immutable strings. For example: message = [ 'c', 'a', 'k', 'e', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 's', 't', 'e', 'a', 'l' ] reverse_words(message) # Prints: 'steal pound cake' print(''.join(message)) When writing your function, assume the message contains only letters and spaces, and all words are separated by one space. """ import unittest def reverse_words(message): left, right = 0, 0 reverse_chars(message, 0, len(message) - 1) while right < len(message): if message[right] == ' ': reverse_chars(message, left, right-1) right += 1 left = right if right == len(message) - 1: reverse_chars(message, left, right) right += 1 def reverse_chars(message, left, right): while left < right: message[left], message[right] = message[right], message[left] left += 1 right -= 1 # Tests class Test(unittest.TestCase): def test_one_word(self): message = list('vault') reverse_words(message) expected = list('vault') self.assertEqual(message, expected) def test_two_words(self): message = list('thief cake') reverse_words(message) expected = list('cake thief') self.assertEqual(message, expected) def test_three_words(self): message = list('one another get') reverse_words(message) expected = list('get another one') self.assertEqual(message, expected) def test_multiple_words_same_length(self): message = list('rat the ate cat the') reverse_words(message) expected = list('the cat ate the rat') self.assertEqual(message, expected) def test_multiple_words_different_lengths(self): message = list('yummy is cake bundt chocolate') reverse_words(message) expected = list('chocolate bundt cake is yummy') self.assertEqual(message, expected) def test_empty_string(self): message = list('') reverse_words(message) expected = list('') self.assertEqual(message, expected) unittest.main(verbosity=2)
true
624a613e35444aa6259e6de55f6210228b86f6b1
dallasmcgroarty/python
/General_Programming/strings/strings.py
437
4.28125
4
#f-strings in python3 #places a value in a string x = 10 print(f"I've told you {x} times already") #join function #can use logic in the join argument #takes a list and joins them together in a string names = ["hey","there","tom"] names_str = ' '.join(names) print(names_str) #takes a list of numbers and converts them into a string using join numbers = [1,2,3,4,5,] number_str = ''.join(str(num) for num in numbers) print(number_str)
true
64f357e4af0bd381e65e4fc98ae074303a8cad4d
dallasmcgroarty/python
/DataStructures_Algorithms/trees/bst_problems.py
2,459
4.15625
4
# bst problems from bst import * # problem 1 # given a binary tree, determine if its a binary search tree or not def bst_check(tree): # binary search tree orders lower to left and greater to right # therefore if we do a inorder traversal the values should be sorted # if not then we dont have a bst values = inorder(tree) if sorted(values) == values: return True else: return False def inorder(tree): values = [] if tree != None: inorder(tree.leftChild) values.append(tree.value) inorder(tree.rightChild) return values # above solution for problem 1 is correct # problem 2 # given a binary tree of integers, print it in level order # that is to each level of the tree is on a new line # ex: 0 # 1 2 # 3 4 5 6 import collections class Node(object): def __init__(self, value=None): self.value = value self.left = None self.right = None def level_order(tree): if not tree: return nodes = collections.deque([tree]) current_count = 1 next_count = 0 while len(nodes) != 0: current_node = nodes.popleft() current_count -= 1 print (current_node.value, end=' ') if current_node.left: nodes.append(current_node.left) next_count += 1 if current_node.right: nodes.append(current_node.right) next_count += 1 if current_count == 0: print () current_count, next_count = next_count, current_count root = Node(1) root.left = Node(2) root.right = Node(3) level_order(root) #problem 3 - Trim BST # given a tree and a min and max value # ensure the tree contains values between min and max inclusive def trim_bst(tree, min_val, max_val): if not tree: return # recursive calls to check each branch tree.left = trim_bst(tree.left, min_val, max_val) tree.right = trim_bst(tree.right, min_val, max_val) if min_val <= tree.val <= max_val: return tree # if val is lower than min, return right subtree, because we know # everything to the left will be lower, and right is greater if tree.val < min_val: return tree.right #if val is greater than max, return left subtree, because we know # everythign to the left will be lower, and right is greater if tree.val > max_val: return tree.left
true
e32d47e35b1cc18e29f8a3d9baaf20707befcb20
dallasmcgroarty/python
/General_Programming/BI_Functions/zip.py
1,618
4.46875
4
# zip function # makes an iterable that takes elements from each of the iterables # takes elements from each iterable at the same positon and creates a pair,triplet,etc nums1 = [1,2,3,4,5] nums2 = [6,7,8,9,10] z = zip(nums1,nums2) z1 = zip(nums1,nums2) p = zip(nums1,nums2) # use list or dict to convert zip object print(list(z)) print(dict(z1)) words = ['hi','lol','haha','smiley'] z2 = zip(words, nums1,nums2) print(list(z2)) # use zip and * in front of the iterable to unpack it and get the orignal iterables print(list(zip(*p))) #********* # more complex zip usage print("more complex zipping---") midterms = [80,91,78] finals = [98,89,53] students = ['dan','ang','kate'] #final grades = {'dan': 98,'ang':91,'kate':78} # create a dict with each students name and their highest grade using zip final_grades = {t[0]:max(t[1],t[2]) for t in zip(students,midterms,finals)} print(final_grades) # same thing but using map and lambda final_scores = dict( zip( students, map( lambda pair: max(pair), zip(midterms,finals) ) ) ) print(final_scores) # same thing but getting the average score final_avg_grades = {t[0]:(t[1] + t[2])/2 for t in zip(students,midterms,finals)} print(final_avg_grades) # problem 1 # given two strings, interweave them together and return them # back as one string # ie. given s1='hey',s2='hoe; return 'hheoye' def interleave(s1,s2): z = zip(s1,s2) zl = list(z) j = ["".join(item) for item in zl] return "".join(j) # or do: # return ''.join(''.join(x) for x in (zip(s1,s2))) print(interleave('hey','hoe'))
true
b575310940f81b968bd1662c9d9936579f93f701
dallasmcgroarty/python
/General_Programming/OOP/grumpy_dict.py
665
4.40625
4
# overriding dictionary object in python # using magic methods we can override how a dictionary functions # this can also be applied to other objects as well class grumpyDict(dict): def __repr__(self): print("None of Your Business") return super().__repr__() def __missing__(self, key): print(f"You Want {key}? Well It Aint Here!") def __setitem__(self, key, value): print("You want to change the dictionary?") print("Okay fine!") super().__setitem__(key, value) data = grumpyDict({"first":"Tom", "animal": "cat"}) print(data) data['city'] = 'Tokyo' print(data) data['city'] = 'SF' print(data)
true
c848222cb081dc5f99321f079447b6ee37f36395
stasDomb/PythonHomeworkDombrovskyi
/Lesson3Homework/LessoneExerc4.py
635
4.28125
4
# Задача-4 # Изменить исходную строку на новую строку в которой первый и последний символы строки поменяны местами. def modify_string(example_string): the_begin = example_string[:1] the_end = example_string[len(example_string) - 1:] new_string = the_end + example_string[1:] + the_begin return new_string example_string = "How. are you? Eh, ok. Low or Lower? Ohhh." print(modify_string(example_string)) #alternative solution #array = list(my_string) #array[0], array[-1] = array[-1], array[0] #print("".join(array))
false
437fa5e62f044e2799791dc91a80c1a0af0a1766
shuvava/python_algorithms
/permutations/heap_algorithm.py
1,794
4.1875
4
#!/usr/bin/env python # encoding: utf-8 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright (c) 2020-2022 Vladimir Shurygin. All rights reserved. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ Heap's algorithm https://en.wikipedia.org/wiki/Heap%27s_algorithm https://www.geeksforgeeks.org/heaps-algorithm-for-generating-permutations/ """ from typing import List def heap_permutation(elements: List[int], size: int, res: List[List[int]]): """Generating permutation using Heap Algorithm """ # if size becomes 1 then prints the obtained # permutation if size == 1: res.append(elements[:]) return for i in range(size): heap_permutation(elements, size - 1, res) # if size is odd, swap first and last # element # else If size is even, swap ith and last element if size & 1: elements[0], elements[size - 1] = elements[size - 1], elements[0] else: elements[i], elements[size - 1] = elements[size - 1], elements[i] def all_perms(elements: List[int], n: int): if n == 1: yield elements[:] else: for i in range(n - 1): for hp in all_perms(elements, n - 1): yield hp if n % 2 == 0: elements[i], elements[n - 1] = elements[n - 1], elements[i] else: elements[0], elements[n - 1] = elements[n - 1], elements[0] for hp in all_perms(elements, n - 1): yield hp def permute(nums: List[int]) -> List[List[int]]: result = [] for s in all_perms(nums, len(nums)): result.append(s) return result if __name__ == '__main__': data = [1, 2, 3] _res = permute(data) print(_res)
true
e4d68156d2c5e8dfe2299b94ed6373fbff14f555
Rhabersh/brown-repo
/oscar_project/oscar_table_create.py
1,822
4.25
4
import sqlite3 from sqlite3 import Error #Create class, pass through def sqlite_connect(): """ This function will use the sqlite3 module to connect to a database. If the specified database is not found in the local directory, a new one with the given name will be created. :return sqlite_con: The active connection """ try: sqlite_con = sqlite3.connect('slurm_database.db') print 'Connection valid - Database active' return sqlite_con except Error: print Error def create_table(sqlite_con): """ This function creates a table in the sqlite database and establishes the primary key as well as the other columns. :param sqlite_con: The active connection to the database is needed so this function knows where to create/update the table. :return None: """ py_cursor = sqlite_con.cursor() py_cursor.execute('CREATE TABLE IF NOT EXISTS resources(jobID integer PRIMARY KEY, memory integer, cores integer, ' 'time integer)') sqlite_con.commit() def insert_data(sqlite_con, ph): """ This function will insert the parsed data from pysqlite_parser into the table. :param sqlite_con: The active connection to the database. :param ph: Placeholder variable for when pysqlite_parser is actually finished. Will be replaced by other variables for necessary fields. :return None: """ py_cursor = sqlite_con.cursor() py_cursor.execute('INSERT OR IGNORE INTO resources(jobID, memory, cores, time) VALUES(?, ?, ?, ?)', ph) sqlite_con.commit() con = sqlite_connect() create_table(con) ph = (1, 2, 3, 4,) insert_data(con, ph)
true
ea7609c525852a1e26b665cf8ff0ac4322e9fbce
thefirstcomma/Learn-Python-the-Hard-Way
/flowcharts/astronaut.py
1,883
4.125
4
def alien(): print "Are You really just in it to meet the Aliens? (y/n)" alien = raw_input('> ') if alien == 'y': print "Seti Researcher, until all the funding is pulled out." elif alien == 'n': print "They won't live up to the hype huh." print "Sci-Fi Writer for you." def not_input(): print "Not an input" def plane(): print "Can you fly a plane?" fly = raw_input('> ') if fly == 'y': print "Dude, just be a pilot!\n" print "But if you hate space, then" print "Type 'No, I hate space' to keep looking." spacepilot = raw_input('> ') if spacepilot == 'No, I hate space': # function russian is used here russian() else: print "Dream job found" exit(0) elif fly == 'n': russian() else: not_input() def russian(): print "Do you speak russian? (y/n)" russian_speaker = raw_input('> ') if russian_speaker == 'y': print "Be an Astronaut, but hitch a ride with the Ruskies." elif russian_speaker == 'n': # function alien() is used within this function alien() else: not_input() def star_wars(): print "Does your favorite movie have 'Star' in the title? (y/n)" star = raw_input('> ') if star == 'n': print "GIVE UP THE DREAM!" print "You don't really love space anyways." exit(0) elif star == 'y': print "Can you withstand long hours staring at a computer screen?" print "(y/n)" screen = raw_input('> ') if screen == 'y': print "Duh, Obviously" # calls function alien() alien() elif screen == 'n': # calls function plane() plane() else: not_input() def start(): print "What is the ideal space career for you?" print "Do you have a degree in science or enginnering? (y/n)" degree = raw_input("> ") if degree == 'y': plane() elif degree == 'n': star_wars() else: not_input() start()
false
a5c1d3bf022385a9b65a5b6216f5bc007b8d4584
cielliyuanpeng/learn_Python_in_hard_way
/ex39.py
1,214
4.21875
4
# create a mapping of state to abbreviation states = { 'Oregon':'OR', 'Florida':'FL', 'California':'CA', 'New York':'NY', 'Michigan':'MI' } cities = { 'CA':'San Francisco', 'MI':'Detroit', 'FL':'Jacksoville' } cities['NY'] = 'New York' cities['OR'] = 'Portland' #print cities print('-'*10) print('NY state has',cities['NY']) print("OR state has",cities['OR']) #print states print('-'*10) print('Michigan`s abbreviation is:',states['Michigan']) #print all state print('-'*10) for state,abbrev in list(states.items()): print(f"{state} is abbreviated {abbrev}") pass #print all city print('-'*10) for city, abbrev in list(cities.items()): print(f"{abbrev} has the city {city}") pass #do both at same time print("-"*10) for state,abbrev in list(states.items()): print(f"{state} state is abbreviated {abbrev}") print(f"and has city {cities[abbrev]}") pass #safety get a abbreviation by state that might not be there print('-'*10) state = states.get('Texas') if not state: print("not have texas") pass # get a city with default value city = cities.get('TX','Do not Exist') print(f"The city for the state 'TX' is :{city}") print(cities.items())
false
aea792baa1a8e9cee6611f2a5409c5bdb036b88b
Sam-Whitley/petrikuittinen_assignments
/lesson_python_basics/for_reversed.py
278
4.125
4
names = ["Bill", "James", "Paul", "Paula", "Jenny", "Kate"] # normal order for name in names: print(name) print("Reverse order:") for name in reversed(names): print(name) print("Don't code like this") i = len(names)-1 while i >= 0: print(names[i]) i = i-1
true
dc567267261b2cf45c92e9d7dc6926ec1ae28432
Zivilevs/Python-programming
/temp_graf.py
1,244
4.25
4
#!/usr/bin/python # Program to convert Celsius to Fahrenheit using a simple # graphical interface. from graphics import * def main() : win = GraphWin( "Celsius Converter" , 400 , 300) win.setCoords (0.0, 0.0 , 3.0, 4.0) win.setBackground("white") # Draw the interface label1 = Text(Point(1,3), " Celsius Temperature : "). draw(win) label2 = Text(Point(1,1), "Fahrenheit Temperature : "). draw(win) label1.setTextColor("purple") label2.setTextColor("purple") inputText = Entry(Point(2.25,3),6) inputText.setText("0.0") inputText.setFill("azure") inputText.draw(win) outputText = Text(Point(2.25,1)," ") outputText.draw(win) button = Text(Point(1.5,2.0),"Convert It ") button.draw(win) box = Rectangle(Point(1,1.5),Point(2,2.5)).draw(win) # wait for a mouse click win.getMouse () # convert input celsius = float(inputText.getText()) fahrenheit = 9.0/5.0 * celsius + 32 # display output and change button outputText.setText(round(fahrenheit,2)) outputText.setText(round(fahrenheit,2)) button.setText("Quit ") # wait for click and then quit win.getMouse () win.close() main() if __main__==__name__: main()
true
b901ec9ccec8c27a6010deae9cd372c7f19261f7
ryanlkraemer/RK-engineering-class
/LearningPythonTheHardWay/ex7.py
916
4.28125
4
#prints a straight string print("Mary had a little lamb") #prints a string by leaving a { in a string, then .formatting to fill it with 'snow'. Format takes whatever is in front, either a variable #defined to be a string or a string (always with a {} and puts the thing in the parentheses after the format into the {} print("It's fleece was white as {}.".format('snow')) #string print('And everywhere that Mary went') #prints a string ten times print("." * 10) #defines all of these as different strings. I'm gonna see if i can use just one for each e end1 = 'C' end2 = 'h' end3 = 'e' #end4 = 'e' end5 = 's' #end6 = 'e' end7 = 'b' end8 = 'u' end9 = 'r' end10 = 'g' #end11 = 'e' end12 = 'r' #prints all the variables together like the old (w+e) in order, and makes the end a space instead of a return?? print(end1 + end2 + end3 + end3 + end5 + end3,end = ' ') print(end7 + end8 + end9 + end10 + end3 + end12)
true
de6237b74bb8eeda49cbdd2a7bb42968fe79815c
ryanlkraemer/RK-engineering-class
/LearningPythonTheHardWay/ex29.py
444
4.15625
4
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats!") if people > cats or dogs < cats: print("idc bro") if people > dogs and dogs != cats: print("wet world") if people > dogs: print("dry world") dogs += 5 if people >= dogs: print("people are greater than or equal to dogs.") if people <= dogs: print("people are less than or equal to dogs.") if people == dogs: print("people are dogs.")
false
0830ef6c3d547d2ade1beb51446e9b4648b27743
ryanlkraemer/RK-engineering-class
/LearningPythonTheHardWay/ex15.py
671
4.15625
4
#takes the module argv from system, allowing me to input the meat of the matter from sys import argv #defines the things in that order for me to input with argv script, filename = argv #defines txt as the file that i input txt = open(filename) #says a useless thing print(f"""Here's your file {filename}. """) #reads and subsequently prints the file print(txt.read()) txt.close() #another way of me inputting the file name, but a separate way altogether, using input instead of argv file2 = input("Print the file name again\n> ") #defines txt2 as the file txt2 = open(file2) #reads and prints the file print(txt2.read()) print(open(filename).read()) txt2.close()
true
7764bd7f4d1dc3ebb76b6fe154fc5055282be820
cjreynol/willsmith
/willsmith/action.py
1,394
4.28125
4
from abc import ABC, abstractmethod class Action(ABC): """ Abstract base class for game actions. Subclasses are convenient containers to remove the reliance on nested tuples and the copious amounts of packing and unpacking required by them. The parse_action method is used to convert strings to the action subclass, and the INPUT_PROMPT attribute is used to convey the format to a user. """ INPUT_PROMPT = None def __init__(self): if self.INPUT_PROMPT is None: raise RuntimeError("Actions must set an input prompt.") @staticmethod @abstractmethod def parse_action(input_str): """ Parse an input string, returning an instance of the Action subclass if the string was valid. """ pass @abstractmethod def __eq__(self, other): """ Compare the two object to check if they are equal. Required to ensure proper behavior comparing actions, such as testing if an action is an element of a list. """ pass @abstractmethod def __hash__(self): """ Return the hash of the object. A custom equality implementation requires a custom hash implementation. A simple default is to create a tuple of the instance attributes and call hash() on it. """ pass
true
5933bc9b90a669e673ab82ed3b7b2893f96e7ddc
bingely/PythonLearning
/函数/函数的参数.py
1,116
4.21875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 默认参数 def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s print(power(2, 5)) print(power(3)) def add_end(L=[]): L.append('END') return L def add_end_improve(L=None): # 定义默认参数要牢记一点:默认参数必须指向不变对象! if L is None: L = [] L.append('END') return L ''' 为什么要设计str、None这样的不变对象呢?因为不变对象一旦创建,对象内部的数据就不能修改,这样就减少了由于修改数据导致的错误。 此外,由于对象不变,多任务环境下同时读取对象不需要加锁,同时读一点问题都没有。我们在编写程序时,如果可以设计一个不变对象,那就尽量设计成不变对象。 ''' result = add_end([1, 2, 3]) print(result) add_end() print(add_end()) add_end_improve() print(add_end_improve()) # 可变参数 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc(1, 2)) s = [1, 2, 3] print(calc(*s))
false
f5020fc8bb541dbfc85b1372ea762a19360983fb
DarkCron/PythonBvP
/Oefenzitting4/E2B.py
442
4.15625
4
def FibonNum (n): if(n==1): return 1 fibonMinus1 = 1 fibonMinus2 = 1 highestFibon = 2 counter = 1 while n > highestFibon: highestFibon = fibonMinus1+fibonMinus2 fibonMinus2 = fibonMinus1 fibonMinus1 = highestFibon counter+=1 if(n==highestFibon): return counter else: return -1 total = int(input("Please give fibon num: ")) print(FibonNum(total))
false
a282df0e875513863718d2b3f2a8ba6cc4390a60
DarkCron/PythonBvP
/Oefenzitting2/Letters to grades P3.12.py
1,655
4.15625
4
print("Enter a letter grade: ") lettergrade = input("") numberGrade = 0.0 DEFAULT_A = 4.0 DEFAULT_B = 3.0 DEFAULT_C = 2.0 DEFAULT_D = 1.0 DEFAULT_F = 0.0 DEFAULT_MOD = 0.3 currentValue = 0.0 printValue = "" if (lettergrade).startswith("A"): currentValue = DEFAULT_A elif (lettergrade).startswith("B"): currentValue = DEFAULT_B elif (lettergrade).startswith("C"): currentValue = DEFAULT_C elif (lettergrade).startswith("D"): currentValue = DEFAULT_D elif (lettergrade).startswith("F"): currentValue = DEFAULT_F if (lettergrade).endswith("-"): currentValue -= DEFAULT_MOD elif (lettergrade).endswith("+"): currentValue += DEFAULT_MOD if lettergrade[0].isdecimal(): numberGrade = float(lettergrade) bHasSign = False bHasPlus = False letterValue = 0.0 if not (numberGrade % 1 == 0): bHasSign = True if bHasSign: if (numberGrade + 0.3) % 1 == 0: bHasPlus = False letterValue = numberGrade + 0.3 else: bHasPlus = True letterValue = numberGrade - 0.3 letterValue = int(letterValue + 0.1) letterValue = float(letterValue) if letterValue == DEFAULT_A: printValue = "A " elif letterValue == DEFAULT_B: printValue = "B " elif letterValue == DEFAULT_C: printValue = "C " elif letterValue == DEFAULT_D: printValue = "D " elif letterValue == DEFAULT_F: printValue = "F " if bHasSign: if bHasPlus: printValue += "+" else: printValue += "-" else: printValue = str(currentValue) print("Numeric value: "+ printValue)
false
b6f0bb3b88752eecdccd8ccda259bd94e33f6bca
DarkCron/PythonBvP
/Oefenzitting1/Extra/P2-11p81.py
553
4.25
4
gallons_gas = float(input("The number of gallons of gas in tank: ")) miles_per_gallon = float(input("The fuel efficiency in miles per gallon: ")) price_per_gallon = float(input("The price of gas per gallon: ")) DISTANCE = 100 drivable_distance = gallons_gas * miles_per_gallon; # x miles = 1 gallon # 100 miles = 1 / x * 100 gallons DISTANCE_to_gallons = 100 // miles_per_gallon price_per_DISTANCE = DISTANCE_to_gallons * price_per_gallon print("Cost per 100 miles: %.2f" % price_per_DISTANCE) print("Tank drive distance: %.2f" % drivable_distance)
true
f8dd76c62b60151dcf6e3d4b1dfdcfdc45ede397
reneafranco/Course
/POO/main.py
2,204
4.46875
4
"""CLASE una clase es un molde para crear varios objetos con caracteristicas parecidas ATRIBUTOS son las particulidades de la clase como nombre y propiedades METODOS son las funciones de la clase basicamente las funciones que le otorgues para que pueda realizarse""" #Definir una clase (Molde para crear mas objetos de ese tipo) (coche ejemplo) class Coche: #crear propiedades(Variables) #Caracteristicas del objetos color = "Rojo" marca = "Ferrari" modelo = "Aventador" velocidad = int(300) caballaje = 500 plazas = 2 #Metodos son acciones que hace el objeto creado (funciones) def accelerar(self): self.velocidad += 1 def frenar(self): self.velocidad -= 1 def getvelocidad(self): return self.velocidad #tambien puedes definirte una funcion seter que es la encargada de cambiar el valor def setColor(self, color): self.color = color #tambien puedes hacer un metodo geter que es el encargado de conseguir informacion def getColor(self): return self.color #mas ejemplos def setModelo(self, modelo): self.modelo = modelo def getModelo(self): return self.modelo def setMarca(self, marca): self.marca = marca def getMarca(self): return self.marca # Instanciar un objeto es crear un objeto fisico basado en el modelo de la clase coche = Coche() coche.setColor("amarillo") coche.setModelo("Portofino") print(coche.getMarca(), coche.getModelo(), coche.getColor()) print(coche.velocidad) #llamar metodos(llamar funciones)(Ojo aqui interactuar directamente con el modelo) #lo recomendable es alterar las propiedades del objeto en especifico para no alterar el molde coche.accelerar() coche.accelerar() coche.accelerar() coche.accelerar() coche.frenar() #crear multiples objetos con el mismo molde pero con propiedades y metodos parecidos mas no iguales lambo = Coche() lambo.setColor("negro") lambo.setModelo("murcielago") lambo.setMarca("Lamborgini") print(lambo.getMarca(), lambo.getModelo(), lambo.getColor()) lambo.accelerar() lambo.accelerar() lambo.accelerar() lambo.accelerar() lambo.frenar() print(lambo.getvelocidad())
false
7938b5edcf60ed84bf79296e95e40a41533f8909
hugolribeiro/Python_Projects
/Dice Rolling Simulator.py
1,493
4.5625
5
# 1. Dice Rolling Simulator The Goal: Like the title suggests, this project involves writing a program that simulates # rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or #whatever other integer # you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should # then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your # dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function # that randomly grabs a number within that range and prints it. Concepts to keep in mind: Random Integer Print While # Loops import random def rolling(side): number = random.randint(1, side) print(f'In a {side} sides dice, we got randomly the number {number}') return try: repeat = True sides = 0 while repeat or sides < 3: sides = int(input("Input here the number of sides of this dice: ")) if sides < 3: print('A dice need to have a minimum of 3 sides. Please, try again') else: rolling(sides) repeat = (str(input('\nIf do you want to roll again press "y"'))) if repeat.lower() == 'y': repeat = True else: repeat = False print('Goodbye ^^') except ValueError: print('Sorry, wrong inputed value!') except Exception as e: print(f'We got {e} error')
true
2139b3e6a019ead6728fbb21595cb7ac2ce2d70a
Cabottega/python_exercises
/python_index_based_interpolation.py
907
4.5
4
# instructor notes from python documentation website. # str.format(*args, **kwargs) # Perform a string formatting operation. The string on which this method is called can contain literal text or >replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional >argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is >replaced with the string value of the corresponding argument. name = 'Kristine' age = 12 product = 'Python eLearning course' from_account = 'Jordan' # Instructor notes - python understands index of variables same as executed code below. # greeting = "Product Purchase: {2} - Hi {0}, you are listed as {1} years old. - {3}".format(name, age, product, 'Jordan') greeting = f"Product Purchase: {product} - Hi {name}, you are listed as {age} years old. - {from_account}" print(greeting)
true
baec7769933fea8a98842aab9d80a8ff7f88d545
Cabottega/python_exercises
/looping_over_characters.py
290
4.6875
5
alphabet = 'abcdef' for letter in alphabet: print(letter) # instructor notes: # alphabet = 'abcdef' # for letter in alphabet: # print(letter) # """ # you have a string here # a for in loop allows you to access them just like a string/collection # 'a', 'b', 'c', 'd' ect # """
true
0985ed07d4a2dd7331e6b4a978fe8e1a75d00b30
Cabottega/python_exercises
/tuples_delete_elements.py
994
4.3125
4
post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published') # Removing elements from end post = post[:-1] # Removing elements from beginning post = post[1:] # Removing specific element (messy/not recommended) post = list(post) post.remove('published') post = tuple(post) print(post) # Instructor notes: # users = ["kristnine", 'Tiffany', 'Jordan', 'Leann'] #list of users-database query # print(users) # users.remove('Jordan') #remove function takes an arguement- the value we are removing # print(users) # popped_user = users.pop() #pop returns the last item of the list so you can use it! # #and stores in the variable # print(popped_user) # print(users) # del users[0] # print(users) # #working with list that you know the value -remove is perfect to use-searches entire collect_incoming_data( # #pop is if you want the very last element in the list # #del or delete only use if you know the list and you are deleting
true
6e44076369067e868300c1341c8e1856c0449253
bglajchen/MIT-Intro-to-Python-6.0001
/ps1/ps1c.py
1,839
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 7 13:35:24 2020 @author: bglajchen """ annual_salary = float(input("Enter your annual salary: ")) total_cost = 1000000 semi_annual_raise = 0.07 portion_down_payment = total_cost * 0.25 current_savings = 0 number_of_months = 0 possible = True steps = 0 low = 0 high = 10000 while True: steps += 1 guess = ((high + low) / 2.0) #print("Down Payment:",portion_down_payment) #print("Low:",low,"| Guess:",guess,"| High:",high) current_savings = 0 number_of_months = 0 test_salary = annual_salary while number_of_months < 36: if (number_of_months % 6) == 0 and number_of_months > 0: test_salary += test_salary * semi_annual_raise monthly_salary = (test_salary / 12) interest = current_savings * 0.04 / 12 current_savings += interest current_savings += (monthly_salary * (guess / 10000)) number_of_months += 1 #print(steps, "| Current Savings:",round(current_savings,4),"| No. Months:",number_of_months) if (low == high): #if impossible to accomplish print("It is not possible to pay the down payment in three years.") possible = False break if (portion_down_payment - 100) < current_savings and current_savings < (portion_down_payment + 100): #if just right break if (portion_down_payment + 100) < current_savings: #if too high #print("TOO HIGH!",guess) high = guess continue if current_savings < (portion_down_payment - 100): #if too low #print("TOO LOW!",guess) low = guess continue if possible == True: print("Best savings rate: ", round((guess/10000),4)) print("Steps in bisection search: ", steps)
true
f6abe0260a989a51b762704a4e995e5def0a787a
venkatsvpr/Problems_Solved
/LC_Smallest_String_With_Swaps.py
2,349
4.15625
4
""" 1202. Smallest String With Swaps You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to after using the swaps. Example 1: Input: s = "dcab", pairs = [[0,3],[1,2]] Output: "bacd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[1] and s[2], s = "bacd" Example 2: Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]] Output: "abcd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[0] and s[2], s = "acbd" Swap s[1] and s[2], s = "abcd" Example 3: Input: s = "cba", pairs = [[0,1],[1,2]] Output: "abc" Explaination: Swap s[0] and s[1], s = "bca" Swap s[1] and s[2], s = "bac" Swap s[0] and s[1], s = "abc" Constraints: 1 <= s.length <= 10^5 0 <= pairs.length <= 10^5 0 <= pairs[i][0], pairs[i][1] < s.length s only contains lower case English letters. """ """ - Keep track of the connected pairs - All connected nodes can be moved form anywhere to anywhere. """ class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: root = [i for i in range(len(s))] def find(x): if x == root[x]: return x root[x] = find(root[x]) return root[x] def union(u,v): rootu = find(u) rootv = find(v) root[rootu] = rootv return # Perform union find for [u,v] in pairs: union(u,v) #keep track of root-node and all the characters in the connected component m = collections.defaultdict(list) for i in range(len(s)): m[find(i)].append(s[i]) # Create an iterator, insstead of sorted we can do bucket sort iterm = dict() for k in dict(m): iterm[k] = iter(sorted(m[k])) # go through nodes, get the root-node and pull a character from the iterator ans = "" for i in range(len(s)): ans += next(iterm[root[i]]) return ans
true
7dcc423ef57281c3b751539fd5f7d0a3c61ec863
awalGaurab/fahrenheit_to_celsius
/converter.py
388
4.21875
4
def converter(fahren): converted_value = (fahren - 32)/1.8 return converted_value try: input_val = float(input("Enter temperature in fahrenheit: ")) converted_temp = converter(input_val) print("{} fahrenheit is equivalent to {} degree celsius value.".format(round(converted_temp,2),input_val)) except Exception: print("Please enter integer or float number only.")
false
c031dddd3c3e0685e82ef5f5934654765ddb7ab7
alakamale/888
/Tree/src/internal_node.py
530
4.21875
4
# 1. Find internal nodes # Let's assume we have a generic tree, such as follows (node values are simply identifiers): # Then we define this tree with a list L: [4, 2, 4, 5, -1, 4, 5] such as L(i) identifies the parent of i (the root has no parent and is denoted with -1). # An internal node is any node of a tree that has at least one child, so in this case the total number of internal nodes is 3 . def find_internal_nodes_num(tree): if tree.count(-1) == 1 and len(tree) >= 1: return len(set(tree)) - 1 return 0
true
e43de700059c31e5db0c7a7f6e837c0556186b3b
ChiselD/pyglatin
/pyglatin.py
2,946
4.21875
4
# THINGS TO FIX # 1. multiple consonants at start of word - DONE! # 2. printing on separate lines - DONE! # 3. non-alphabetical strings # 3a. if user includes numbers, return error - DONE! # 3b. if user includes punctuation, move it to correct location # 4. omitted capitalization # separate variables for the two possible endings ay = 'ay' yay = 'yay' # create list to hold words of sentence in order sentence = [] # reference list that tracks all vowels vowels = ['a','e','i','o','u','y'] # function to run on words starting with vowels def vowel(word): vowel_word = word + yay sentence.append(vowel_word) # function to run on words starting with consonants def consonant(word, first): # this variable will hold all letters before first vowel first_chunk = '' # I don't think there are any words in English that start with 'y' + another consonant (?) if first == 'y': first_chunk = first elif word[0] == 'q' and word[1] == 'u': first_chunk = 'qu' else: for letter in word: # look at each letter in word to see if it is a vowel if letter not in vowels: # as long as it's not, add it onto the end of the 'first_chunk' variable first_chunk += letter else: # as soon as you reach the first vowel in the word, break the loop break # consonant_word = all letters from first vowel to end + all letters before that + ay consonant_word = word[len(first_chunk):len(word)] + first_chunk + ay sentence.append(consonant_word) # function to check if user input contains any digits def has_number(input): # returns True if the string contains a digit return any(char.isdigit() for char in input) # function to turn the user input into its Pig Latin equivalent def pig_latinize_string(input): # lowercase user-entered string for practical purposes text = input.lower() # split original text into array of separate words words = text.split() # check each word: is it vowel-category or consonant-category? for word in words: # make variable to hold first letter only first = word[0] # if first letter is vowel, run vowel function if first in vowels and first != 'y': vowel(word) # if first letter is consonant, run consonant function else: consonant(word, first) # print each word in final 'sentence' list for item in sentence: print item, # function that runs all the other functions (ALL HAIL MASTER FUNCTION) def main(): # reset sentence list to empty sentence = [] # prompt user for text to Pig-Latinize original = raw_input("Enter your text: ") # confirm that user-entered string is not empty if len(original) > 0: # if string contains numbers, refuse it and re-prompt if has_number(original): print "Please enter a string that contains only letters and punctuation." main() # otherwise, let's DO this thing else: pig_latinize_string(original) else: # if user-entered string is empty, throw error and re-prompt print "No input!" main() main()
true
513be128e24652eb1eef63f752fbabcae68c7437
junweitan1999/csci1100
/homework/hw4/hw4Part1.py
2,225
4.40625
4
# function to define the word is alternating or not def is_alternating(word): #initializing vowels = [] letter=['a','b','c','d','e','f','g','h','j','k','l','i','o','u','m','n','p','q','r','s','t','v','w','x','y','z'] judge = True same_or_not = True judgment =False word_copy=word word=word.lower() if len(word) <8: print("The word '{0}' is not alternating".format(word)) return False for i in word: if i not in letter: print("The word '{0}' is not alternating".format(word)) return False else: #see the first letter is vowel or not if word[0] == "a" or word[0]== "e" or word[0]=="o" or word[0]=="u" or word[0]=="i": judgement = True else: judgement = False # the following loop make sure that the next letter is different from the previous letter by changing from vowel to consonant for i in word: if i == "a" or i== "e" or i=="o" or i=="u" or i=="i": vowels.append(i) judge =False else : judge =True # if the next word has the same judge as the previous one , then it is not alternating if judgement ==judge : print("The word '{0}' is not alternating".format(word_copy)) return False judgement=judge # copy the vowel list and sort it to see whether the sequence of the vowels follows the rule check_vowels = vowels.copy() vowels.sort() # if two list is inconsistent then the word is not alternating if vowels != check_vowels: print("The word '{0}' is not alternating".format(word_copy)) return False # else, it is else: print("The word '{0}' is alternating".format(word_copy)) return True # the main program # unless the word is "" , the program will pop up Enter a word until the user enter"" while True: word = input("Enter a word: ") if word =="": break print(word) is_alternating(word) print()
true
2f1757c8454ec56b1cf3360f486c54ab8230eb2f
chandni-s/NewsFlash
/src/model.py
1,538
4.3125
4
class Model(): """A database model. Objects that interact with the database (add, get, delete, etc...) should be derived from this class. This helps create a consistent interface for the database to use to implement its functions (and prevents lots of repetition in queries as a bonus).""" # (str) # The table name for the class. db_table = "" # (str) # The name of the members of the class that the database stores. The # class must have every field listed in this string after renaming # columns, or the conversion from dict to the Model will fail. db_fields = "" # (str) # The labels to use after performing select operations. It is important # that these match all required elements in the constructor of the # class, since a conversion from a database row (represented by a # dictionary) to the constructor parameters happens after getting rows # from the database. db_labels = "" # (str) # Where to get the data for the class from. May contain joins onto other # tables. db_from = "" def __repr__(self): """(Model) -> str Returns the string representation of a model. """ # Convert the internal dictionary into something that looks like a # parameter to list, for better readability. params = [] for k, v in self.__dict__.iteritems(): params.append('%s=%r' % (k, v)) params = ", ".join(params) return "%s(%s)" % (self.__class__.__name__, params)
true