blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3c41155cbab16bb91e4387aa35d49e1832ce5b72
codedsun/LearnPythonTheHardWay
/ex32.py
525
4.25
4
#Exercise 32: Loops and List the_count = [1,2,3,4,5] fruits = ['apples','oranges','pears','apricots'] change = [1,'pennies',2,'dimes',3,'quaters'] #for loop in the list for number in the_count: print("This is %d count"%number) for fruit in fruits: print("A fruit of type %s"%fruit) for i in change: print("I got %r"%i) #Building empty list and then appending it element=[] for i in range(0,6): print("Adding the %d in the list"%i) element.append(i) for i in element: print("Element %d"%i)
true
8c3788b2fc95ce08c9dc6165b6f5de91e7d7d448
semihyilmazz/Rock-Paper-Scissors
/Rock Paper Scissors.py
2,933
4.40625
4
import random print "********************************************************" print "Welcome to Rock Paper Scissors..." print "The rules are simple:" print "The computer and user choose from Rock, Paper, or Scissors." print "Rock crushes scissors." print "Paper covers rock." print "and" print "Scissors cut paper." print "You will play the computer...the first to reach 3 wins wins the match." print "Good luck!" print "************************************************************""" user_win = 0 computer_win= 0 user_name= raw_input("Whats Your Name? ") while True: computer_choice = "" user_choice = raw_input("Please choose (R) Rock, (P) Paper, or (S) Scissors: ").upper() random_number = random.randint(1,3) if random_number == 1: computer_choice = "R" if random_number == 2: computer_choice = "P" if random_number == 3: computer_choice = "S" if computer_choice == "R": print(""" _______ ---' ____) (_____) (_____) (____) ---.__(___) The computer chose rock.""") elif computer_choice == "P": print(""" _______ ---' ____)____ ______) _______) _______) ---.__________) The computer chose paper.""") elif computer_choice == "S": print(""" _______ ---' ____)____ ______) __________) (____) ---.__(___) The computer chose scissors.""") print "" if (computer_choice == "R" and user_choice == "P") or \ (computer_choice == "P" and user_choice == "S") or \ computer_choice == "S" and user_choice == "R": print "You win!" user_win +=1 print user_name, user_win print "computer=", computer_win elif (computer_choice == "R" and user_choice == "S") or \ (computer_choice == "P" and user_choice == "R") or \ (computer_choice == "S" and user_choice == "P"): print "You lose!" computer_win +=1 print user_name, user_win print "computer=", computer_win else: print "Ties" print user_name, user_win print "computer=", computer_win if computer_win == 3: print user_name,"LOST" user_win =0 computer_win = 0 delay = raw_input("You want to play another game Y/N ? ") if delay == "y": continue else: break elif user_win == 3: print user_name,"WON" user_win = 0 computer_win = 0 delay = raw_input("You want to play another game Y/N ? ") if delay == "y": continue else: break
true
9a6fe2ffbb280d239d50001e637783520b8d4aef
songseonghun/kagglestruggle
/python3/201-250/206-keep-vowels.py
272
4.1875
4
# take a strign. remove all character # that are not vowels. keep spaces # for clarity import re s = 'Hello, World! This is a string.' # sub = substitute s2 = re.sub( '[^aeiouAEIOU ]+', #vowels and # a space '', #replace with nothing s ) print(s2)
true
b5363f3d6c5b6e55b3d7607d055a266b215c28ab
dianamenesesg/HackerRank
/Interview_Preparation_Kit/String_manipulation.py
2,979
4.28125
4
""" Strings: Making Anagrams Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number? Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings. For example, if and , we can delete from string and from string so that both remaining strings are and which are anagrams. Function Description Complete the makeAnagram function in the editor below. It must return an integer representing the minimum total characters that must be deleted to make the strings anagrams. makeAnagram has the following parameter(s): a: a string b: a string Input Format The first line contains a single string, . The second line contains a single string, . Constraints The strings and consist of lowercase English alphabetic letters ascii[a-z]. Output Format Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other. Sample Input cde abc Sample Output 4""" import math import os import random import re import sys # Complete the makeAnagram function below. def makeAnagram(a, b): for character_a in a: if character_a in b: a = a.replace(character_a,"",1) b = b.replace(character_a,"",1) num_deleted = len(a) + len(b) return num_deleted #print(makeAnagram("jxwtrhvujlmrpdoqbisbwhmgpmeoke", "fcrxzwscanmligyxyvym")) """ Alternating Characters A Shashank le gustan las cadenas donde los caracteres consecutivos son diferentes. Por ejemplo, le gusta , mientras que no le gusta. Dada una cadena que solamente contiene caracteres y , él quiere cambiarla a una cadena que le guste. Para hacerlo, solo se le permite borrar los caracteres en la cadena. Tu tarea es encontrar la mínima cantidad requerida de borrados. Formato de Entrada La primera linea contiene un enter que quiere decir el número de casos de prueba. Luego siguen lineas , con una cadena en cada linea. Formato de Salida Imprimie la mínima cantidad requerida de pasos en cada caso de prueba. Restricciones Ejemplo de Entrada 5 AAAA BBBBB ABABABAB BABABA AAABBB Ejemplo de Salida 00 3 4 0 0 4 """ def alternatingCharacters(s): #return len([1 for x in range(len(s)-1) if s[x]==s[x+1]]) case = 0 for i in range(len(s)-1): if s[i] == s[i+1]: case += 1 return case #alternatingCharacters('AAABBBAABB')
true
c5d1e2535e6e8d9ac0218f06a44e437b3358049b
michaelschung/bc-ds-and-a
/Unit1-Python/hw1-lists-loops/picky-words-SOLUTION.py
543
4.3125
4
''' Create a list of words of varying lengths. Then, count the number of words that are 3 letters long *and* begin with the letter 'c'. The count should be printed at the end of your code. • Example: given the list ['bat', 'car', 'cat', 'door', 'house', 'map', 'cyst', 'pear', 'can', 'spike'], there are exactly 3 qualifying words. ''' words = ['bat', 'car', 'cat', 'door', 'house', 'map', 'cyst', 'pear', 'can', 'spike', 'ace', 'cpe'] count = 0 for word in words: if len(word) == 3 and word[0] == 'c': count += 1 print(count)
true
c9a7bdeb85a94afc6b17c2b6ddf3be0d78de6206
yangju2011/udacity-coursework
/Programming-Foundations-with-Python/turtle/squares_drawing.py
755
4.21875
4
import turtle def draw_square(some_turtle): i = 0 while i<4: # repeat for squares some_turtle.forward(100) some_turtle.right(90) i=i+1 def draw_shape():#n stands for the number of edge windows = turtle.Screen()#create the background screen for the drawing windows.bgcolor("red") brad = turtle.Turtle() #move around, def __init__ stand for initialize brad.shape("turtle")#https://docs.python.org/2/library/turtle.html#turtle.shape brad.color("white","blue")#two color, first outline, second filled; can't do three colors brad.speed(5) for i in range(0,36): brad.right(10) draw_square(brad) windows.exitonclick() draw_shape()
true
1bb3d699d6d1e7ef8ea39a5cdc7d55f79ac4ed3d
theelk801/pydev-psets
/pset_lists/list_manipulation/p5.py
608
4.25
4
""" Merge Lists with Duplicates """ # Use the two lists below to solve this problem. Print out the result from each section as you go along. list1, list2 = [2, 8, 6], [10, 4, 12] # Double the items in list1 and assign them to list3. list3 = None # Combine the two given lists and assign them to list4. list4 = None # Replace the first 3 items in list 3 with the numbers 4, 3, 12. # Create a variable list5. Merge list3 and list4 to create a list containing no duplicates. list5 = None # Take a look at your printed statements to see the evolution of your lists with each step of this problem.
true
d7aa917a00b2f582c7b15c8b40de0462ca274a66
theelk801/pydev-psets
/pset_classes/fromagerie/p6.py
1,200
4.125
4
""" Fromagerie VI - Record Sales """ # Add an instance method called "record_sale" to the Cheese class. Hint: You will need to add instance attributes for profits_to_date and sales (i.e. number of items sold) to the __init__() method in your Cheese class definition BEFORE writing the instance method. # The record_sale method should do the following: ### Add the sale's profits to profits_to_date attribute. ### Add the number sold to the running total in the sales attribute. ### Subtract the number sold from the stock attribute. ### Check the stock (Hint: Call the check_stock method within the record_sale method.) # Once finished, call record_sale on each sale from the sales_today dict below and print out the name of the cheese, whether it has a low stock alert, the remaining stock value, the running total of units of that cheese sold, and the running total of your profits to date. It should look something like this: """ Parmigiano reggiano - Low stock alert! Order more parmigiano reggiano now. Remaining Stock: 14 Total Sales: 10 Profits to Date: 20 """ sales_today = {provolone: 8, gorgonzola: 7, mozzarella: 25, ricotta: 5, mascarpone: 13, parmigiano_reggiano: 10, pecorino_romano: 8}
true
1859b100bd9711dfa564f8d3a697202bc42d96c2
theelk801/pydev-psets
/pset_conditionals/random_nums/p2.py
314
4.28125
4
""" Generate Phone Number w/Area Code """ # import python randomint package import random # generate a random phone number of the form: # 1-718-786-2825 # This should be a string # Valid Area Codes are: 646, 718, 212 # if phone number doesn't have [646, 718, 212] # as area code, pick one of the above at random
true
278cfd9000b17eaf249eebad07b11d078e934c35
theelk801/pydev-psets
/pset_classes/bank_accounts/solutions/p2.py
1,377
4.21875
4
""" Bank Accounts II - Deposit Money """ # Write and call a method "deposit()" that allows you to deposit money into the instance of Account. It should update the current account balance, record the transaction in an attribute called "transactions", and prints out a deposit confirmation message. # Note 1: You can format the transaction records like this - "Deposit: <starting balance>, <ending balance>" # Note 2: You can format the deposit confirmation message like this - "$<amount> deposit complete." class Account(): def __init__(self, name, account_number, initial_amount): self.name = name self.acc_num = account_number self.balance = initial_amount self.transactions = {} int_rate = 0.5 def acc_details(self): print(f'Account No.: {self.acc_num}\nAccount Holder: {self.name}\nInterest Rate: {self.int_rate}\nBalance: ${self.balance}\n') def deposit(self, amount): start_amount = self.balance self.balance += amount end_amount = self.balance label = 'Deposit' self.transactions.update({label: [start_amount, end_amount]}) print(f'${amount} deposit complete.') alejandra = Account('Alejandra Ochoa', 554951, 20000) alejandra.deposit(500) print(f'${alejandra.balance}') # 20500 print(alejandra.transactions) # {'Deposit': [20000, 20500]} alejandra.acc_details()
true
9d9d044b0bff764cc3a8f4e31634f1138f05e2b4
Arin-py07/Python-Programms
/Problem-11.py
888
4.1875
4
Python Program to Check if a Number is Positive, Negative or 0 Source Code: Using if...elif...else num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") Here, we have used the if...elif...else statement. We can do the same thing using nested if statements as follows. Source Code: Using Nested if num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number") else: print("Negative number") The output of both programs will be the same. Output 1 Enter a number: 2 Positive number Output 2 Enter a number: 0 Zero A number is positive if it is greater than zero. We check this in the expression of if. If it is False, the number will either be zero or negative. This is also tested in subsequent expression.
true
5b428c1de936255d8a787f6939528031fa3ddc9b
Arin-py07/Python-Programms
/Problem-03.py
1,464
4.5
4
Python Program to Find the Square Root Example: For positive numbers # Python Program to calculate the square root # Note: change this value for a different result num = 8 # To take the input from the user #num = float(input('Enter a number: ')) num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) Output The square root of 8.000 is 2.828 In this program, we store the number in num and find the square root using the ** exponent operator. This program works for all positive real numbers. But for negative or complex numbers, it can be done as follows. Source code: For real or complex numbers # Find square root of real or complex numbers # Importing the complex math module import cmath num = 1+2j # To take input from the user #num = eval(input('Enter a number: ')) num_sqrt = cmath.sqrt(num) print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag)) Output The square root of (1+2j) is 1.272+0.786j In this program, we use the sqrt() function in the cmath (complex math) module. Note: If we want to take complex number as input directly, like 3+4j, we have to use the eval() function instead of float(). The eval() method can be used to convert complex numbers as input to the complex objects in Python. To learn more, visit Python eval() function. Also, notice the way in which the output is formatted. To learn more, visit string formatting in Python.
true
e6dead53cca8e5bef774435616a2dd02452e6389
ejoconnell97/Coding-Exercises
/test2.py
1,671
4.15625
4
def test_2(A): # write your code in Python 3.6 ''' Loop through S once, saving each value to a new_password When a numerical character is hit, or end of S, check the new_password to make sure it has at least one uppercase letter - Yes, return it - No, reset string to null and continue through S If new_password is empty, return -1 ''' current_password = "" new_password = "" has_upper = False password_length = 0 #loop through all of S for x in A: #if the current character is not a number if (x.isalpha()): current_password += x #update the new password if needed new_password, has_upper = update_string(current_password, new_password, has_upper) else: #update new_password if S ends with a number new_password, has_upper = update_string(current_password, new_password, has_upper) #otherwise, reset the current_password because you've reached a number current_password = "" if not new_password: return -1 print (new_password) password_length = len(new_password) return password_length #make sure that the current_password has at least one uppercase character and is longer than new_password before updating it def update_string(current, new, has_upper): for x in current: if x.isupper(): has_upper = True if (has_upper == True and (len(current) > len(new))): new = current has_upper = False return new, has_upper A = "a00000000000000aA9AAA" test_2(A)
true
0860ed14b0d55e8a3c09aeb9e56075354d1e1298
npandey15/CatenationPython_Assignments
/Task1-Python/Task1_Python/Q3.py
547
4.15625
4
Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> x=6 >>> y=10 >>> >>> Resultname=x >>> x=y >>> y=Resultname >>> print("The value of x after swapping: {}".format(x)) The value of x after swapping: 10 >>> print("The value of y after swaaping:{}".format(y)) The value of y after swaaping:6 >>> >>> >>> # without using third variable >>> >>> x=6 >>> y=10 >>> >>> x,y=y,x >>> print("x=",x) x= 10 >>> print("y=",y) y= 6 >>>
true
8a99191f6780e06be6e14501b671cc981f42bf0d
npandey15/CatenationPython_Assignments
/Passwd.py
1,188
4.34375
4
# Passwd creation in python def checker_password(Passwd): "Check if Passwd is valid" Specialchar=["$","#","@","*","%"] return_val=True if len(passwd) < 8: print("Passwd is too short, length of the password should be at least 8") return_val=False if len(passwd) > 30: print("Passwd is too long, length of the password should not be greater than 8") return_val=False elif len(passwd) > 8 and len(passwd) <= 30: print("Passwd OK") return_val=True if not any(char.isdigit() for char in passwd): print("Passwd should have atleast one numerical input") return_val=False if not any(char.isupper() for char in passwd): print("Passwd should have at least one UPPERCASE Letter") return_val=False if not any(char in Specialchar for char in passwd): print("Passwd should have at least one Special character $#@*%") return_val=False if return_val: print("OK") return return_val else: print("Invalid Passwd") print(checker_password.__doc__) passwd=input("Enter the password: ") print(checker_password(passwd))
true
6da25701a40c8e6fce75d9ab89aaf63a45e2ecfe
aparna-narasimhan/python_examples
/Strings/shortest_unique_substr.py
1,322
4.15625
4
''' Smallest Substring of All Characters Given an array of unique characters arr and a string str, Implement a function getShortestUniqueSubstring that finds the smallest substring of str containing all the characters in arr. Return "" (empty string) if such a substring doesn’t exist. Come up with an asymptotically optimal solution and analyze the time and space complexities. Example: input: arr = ['x','y','z'], str = "xyyzyzyx" output: "zyx" See here for more examples: https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/ TODO: This is a working brute force solution. Need to come up with an optimal solution ''' from collections import defaultdict def get_shortest_unique_substring(arr, str): arr_dict = defaultdict(int) max_count = len(arr) min_len = 32768 result = "" for c in range(len(str)): length = 0 count = 0 start = 0 for char in arr: arr_dict[char] = 1 for i,ch in enumerate(str[c:]): if arr_dict[ch] == 1: arr_dict[ch] -= 1 count += 1 if start == 0: start = c length += 1 if count == max_count: if length < min_len: min_len = length result = str[start:start+length] #print result break return result
true
0111fd00103f42a032074e0c3b4d40006f1029f9
aparna-narasimhan/python_examples
/Arrays/missing_number.py
866
4.28125
4
''' If elements are in range of 1 to N, then we can find the missing number is a few ways: Option 1 #: Convert arr to set, for num from 0 to n+1, find and return the number that does not exist in set. Converting into set is better for lookup than using original list itself. However, space complexity is also O(N). Option#2: Sum of all elements from 1 to N - Sum of all elements in the array = Missing number Adv: No space complexity Option#3: XOR all elements in the array + XOR all elements from 1 to N = Missing number Provided no duplicates? Adv: No space complexity XOR is fast operation ''' #[1,2,3,5,6,7,8] def find_missing_number(arr): n = len(arr) total_sum = sum(range(1,arr[-1]+1)) print(total_sum) arr_sum = sum(arr) print(arr_sum) missing_num = total_sum - arr_sum print(missing_num) find_missing_number([1,2,3,5,6,7,8])
true
8d401a11b4ea284f9bb08c2e2615b9414fd3d3ac
aparna-narasimhan/python_examples
/Misc/regex.py
2,008
4.625
5
#https://www.tutorialspoint.com/python/python_reg_expressions.htm import re line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!" ''' When the above code is executed, it produces following result − searchObj.group() : Cats are smarter than dogs searchObj.group(1) : Cats searchObj.group(2) : smarter ''' #!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'\D', "", phone) print "Phone Num : ", num ''' When the above code is executed, it produces the following result − Phone Num : 2004-959-559 Phone Num : 2004959559 ''' ''' Sr.No. Example & Description 1 [Pp]ython Match "Python" or "python" 2 rub[ye] Match "ruby" or "rube" 3 [aeiou] Match any one lowercase vowel 4 [0-9] Match any digit; same as [0123456789] 5 [a-z] Match any lowercase ASCII letter 6 [A-Z] Match any uppercase ASCII letter 7 [a-zA-Z0-9] Match any of the above 8 [^aeiou] Match anything other than a lowercase vowel 9 [^0-9] Match anything other than a digit Special Character Classes Sr.No. Example & Description 1 . Match any character except newline 2 \d Match a digit: [0-9] 3 \D Match a nondigit: [^0-9] 4 \s Match a whitespace character: [ \t\r\n\f] 5 \S Match nonwhitespace: [^ \t\r\n\f] 6 \w Match a single word character: [A-Za-z0-9_] 7 \W Match a nonword character: [^A-Za-z0-9_] Repetition Cases Sr.No. Example & Description 1 ruby? Match "rub" or "ruby": the y is optional 2 ruby* Match "rub" plus 0 or more ys 3 ruby+ Match "rub" plus 1 or more ys 4 \d{3} Match exactly 3 digits 5 \d{3,} Match 3 or more digits 6 \d{3,5} Match 3, 4, or 5 digits '''
true
ac26b98728ecf7d49aa79f70aa5dd5e3238ef10d
aparna-narasimhan/python_examples
/pramp_solutions/get_different_number.py
1,319
4.125
4
''' Getting a Different Number Given an array arr of unique nonnegative integers, implement a function getDifferentNumber that finds the smallest nonnegative integer that is NOT in the array. Even if your programming language of choice doesn’t have that restriction (like Python), assume that the maximum value an integer can have is MAX_INT = 2^31-1. So, for instance, the operation MAX_INT + 1 would be undefined in our case. Your algorithm should be efficient, both from a time and a space complexity perspectives. Solve first for the case when you’re NOT allowed to modify the input arr. If successful and still have time, see if you can come up with an algorithm with an improved space complexity when modifying arr is allowed. Do so without trading off the time complexity. Analyze the time and space complexities of your algorithm. Example: input: arr = [0, 1, 2, 3] output: 4 ''' #Approach1: It is enough to iterate only upto length of the list instead of up to MAX_INT. Use set instead of the array itself as lookup time of a set is O(1). Set is similar to dict and can be used when we don't need to store values. def get_different_number(arr): temp_set = set(arr) for i in range(len(arr)): if i not in temp_set: return i if i == (2 ** 31) - 1: return i else: return i + 1
true
93354f664979d327f700a7f5ed4a28d92b978b16
premraval-pr/ds-algo-python
/data-structures/queue.py
1,040
4.34375
4
# FIFO Structure: First In First Out class Queue: def __init__(self): self.queue = [] # Insert the data at the end / O(1) def enqueue(self, data): self.queue.append(data) # remove and return the first item in queue / O(n) Linear time complexity def dequeue(self): if self.is_empty(): return -1 data = self.queue[0] del self.queue[0] return data # returns the first element / O(1) def peek(self): return self.queue[0] # check if the queue is empty / O(1) def is_empty(self): return self.queue == [] # returns the size / O(1) def queue_size(self): return len(self.queue) queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print("Dequeue: %d" % queue.dequeue()) print("Size: %d" % queue.queue_size()) print("Peek: %d" % queue.peek()) print("Size: %d" % queue.queue_size()) print("Dequeue: %d" % queue.dequeue()) print("Dequeue: %d" % queue.dequeue()) print("Dequeue: %d" % queue.dequeue())
true
d73c7a9bec4f30251d31d42a17dfa7fde9a48f8e
danieltapp/fcc-python-solutions
/Basic Algorithm Scripting Challenges/caesars-cipher.py
848
4.21875
4
#One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount. #A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on. #Write a function which takes a ROT13 encoded string as input and returns a decoded string. def rot13(str): l = list(str.lower()) for i in range(0, len(l)): if l[i].isalpha(): if ord(l[i]) > 109: l[i] = chr(ord(l[i]) - 13) elif ord(l[i]) <= 109: l[i] = chr(ord(l[i]) + 13) return ''.join(l).upper() print(rot13("SERR PBQR PNZC")) print(rot13('SERR CVMMN!')) print(rot13("SERR YBIR?")) print(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."))
true
2248f6b4e815240d85ee37a6af3dc6c58d44d2d7
danieltapp/fcc-python-solutions
/Basic Algorithm Scripting Challenges/reverse-a-string.py
313
4.4375
4
#Reverse the provided string. #You may need to turn the string into an array before you can reverse it. #Your result must be a string. def reverse_string(str): return ''.join(list(reversed(str))) print(reverse_string('hello')) print(reverse_string('Howdy')) print(reverse_string('Greetings from Earth'))
true
759f39154fc321a20f84850be8482262b21b427e
oluwaseunolusanya/al-n-ds-py
/chapter_4_basic_data_structures/stackDS.py
967
4.375
4
class Stack: #Stack implementation as a list. def __init__(self): self._items = [] #new stack def is_empty(self): return not bool(self._items) def push(self, item): self._items.append(item) def pop(self): return self._items.pop() def peek(self): return self._items[-1] def size(self): return len(self._items) """ s = Stack() print(s.is_empty()) s.push('Olu') print(s.is_empty()) print(s.peek()) print(s.size()) s.push([1 ,2, 5]) print(s.size()) print(s) print(s.pop()) print(s.size()) """ #Function below uses Stack to reverse the characters in a string ''' def rev_string(my_str): my_str_stack = Stack() for i in my_str: my_str_stack.push(i) print(my_str_stack.peek()) reversed_string = "" while not my_str_stack.is_empty(): reversed_string += my_str_stack.pop() return print(reversed_string) rev_string('I want an apple') '''
true
33c05d544f56bec9699add58b0a26673d41e974a
shubee17/Algorithms
/Array_Searching/search_insert_delete_in_unsort_arr.py
1,239
4.21875
4
# Search,Insert and delete in an unsorted array import sys def srh_ins_del(Array,Ele): # Search flag = 0 for element in range(len(Array)): if Array[element] == int(Ele): flag = 1 print "Element Successfully Found at position =>",element + 1 break else: flag = 0 if flag == 0: print "Element Not Found!!! " else: pass #Insert print "\n" flag = 0 position = int(raw_input("Enter the position which you want to be Insert element => ")) Element = int(raw_input("Enter the element => ")) for element in range(len(Array)): if (element + 1) == int(position): flag = 1 Array[element] = int(Element) print "Element Successfully Inserted =>",Array break else: flag = 0 if flag == 0: print "Position Does'nt Exists!!!" else: pass #Delete print "\n" flag = 0 position = int(raw_input("Enter the position which you want to be Delete element => ")) for element in range(len(Array)): if (element + 1) == int(position): flag = 1 del(Array[element]) print "Element Successfully Deleted =>",Array break else: flag = 0 if flag == 0: print "Position Does'nt Exists!!! " else: pass Array = sys.argv[1] Array = map(int, Array) Ele = sys.argv[2] srh_ins_del(Array,Ele)
true
b1ec062d544dfb65fbd8f09e67bb03dce65aeef6
betta-cyber/leetcode
/python/208-implement-trie-prefix-tree.py
784
4.125
4
#!/usr/bin/env python # encoding: utf-8 class Trie(object): def __init__(self): self.root = {} def insert(self, word): p = self.root for c in word: if c not in p: p[c] = {} p = p[c] p['#'] = True def search(self, word): node = self.find(word) return node is not None and '#' in node def startsWith(self, prefix): return self.find(prefix) is not None def find(self, prefix): p = self.root for c in prefix: if c not in p: return None p = p[c] return p # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
true
9f7a5977df4e57f7c7c5518e4e3bc42f517d1856
matthew-lu/School-Projects
/CountingQueue.py
1,823
4.125
4
# This program can be called on to create a queue that stores pairs (x, n) where x is # an element and n is the count of the number of occurences of x. # Included are methods to manipulate the Counting Queue. class CountingQueue(object): def __init__(self): self.queue = [] def __repr__(self): return repr(self.queue) def add(self, x, count=1): if len(self.queue) > 0: xx, cc = self.queue[-1] if xx == x: self.queue[-1] = (xx, cc + count) else: self.queue.append((x, count)) else: self.queue = [(x, count)] def get(self): if len(self.queue) == 0: return None x, c = self.queue[0] if c == 1: self.queue.pop(0) return x else: self.queue[0] = (x, c - 1) return x def isempty(self): return len(self.queue) == 0 def countingqueue_len(self): """Returns the number of elements in the queue.""" l = self.queue count = 0 for x, i in l: for y in range(i): count += 1 return count def countingqueue_iter(self): """Iterates through all the elements of the queue, without removing them.""" l = self.queue for i, x in l: for y in range(x): yield i def subsets(s): """Given a set s, yield all the subsets of s, including s itself and the empty set.""" temp = list(s) if len(s) == 0: return [[]] subset = list(subsets(temp[1:])) answer = list(subset) for x in subset: answer.append(x+[temp[0]]) return answer return s
true
8949fd91df9d848465b03c7024e7516738e72c8e
jtew396/InterviewPrep
/linkedlist2.py
1,651
4.21875
4
# Linked List Data Structure # HackerRank # # # Node class class Node: # Function to initialize the node object def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: # Function to initialize the LinkedList class def __init__(self): self.head = None # Function to append a Node object to the LinkedList object def append(self, data): if self.head == None: self.head = Node(data) return current = self.head while current.next != None: current = current.next current.next = Node(data) # Function to prepend a Node object to the LinkedList object def prepend(self, data): newHead = Node(data) newHead.next = self.head self.head = newHead # Function to delete a Node object from the LinkedList object def deleteWithValue(self, data): if self.head == None: return if self.head.data == data: self.head = self.head.next return current = self.head while current.next != None: if current.next.data == data: current.next = current.next.next return current = current.next def printList(self): temp = self.head while temp: print(temp.data) temp = temp.next if __name__=='__main__': llist = LinkedList() llist.append(1) llist.append(2) llist.append(3) llist.printList() llist.prepend(0) llist.printList() llist.deleteWithValue(0) llist.printList()
true
a624e3d14acd2154c5dc156cfaa092ab1767d6a5
jtew396/InterviewPrep
/search1.py
1,154
4.25
4
# Cracking the Coding Interview - Search # Depth-First Search (DFS) def search(root): if root == None: return print(root) root.visited = True for i in root.adjacent: if i.visited == false: search(i) # Breadth-First Search (BFS) - Remember to use a Queue Data Structure def search(root): queue = Queue() # Declare a Queue object root.marked = True # Set the root node marked parameter equal to True queue.enqueue(root) # Add to the end of the queue while not queue.isEmpty(): # While the Queue is not empty r = queue.dequeue() # Remove from the front of the queue print(r) # Print the returned dequeued node for i in r.adjacent: # for every node in the adjacent nodes if i.marked == False: # if they are marked as False i.marked = True # set them to True queue.enqueue(i) # Add them to the Queue # Bidirectional Search Uses 2 Breadth-First Searches # This is used for to find the shortest path ebetween a source and destination node
true
ffbd1535e7f9c25e817c10e31e0e6812a7645724
knpatil/learning-python
/src/dictionaries.py
686
4.25
4
# dictionary is collection of key-value pairs # students = { "key1":"value1", "key2": "value2", "key3": "value3" } # color:point alien = {} # empty dictionary alien = {"green":100} alien['red'] = 200 alien['black'] = 90 print(alien) # access the value print(alien['black']) # modify the value alien['red'] = 500 print(alien) # remove the value # del alien['green'] # print(alien) # name: favorite programming lanauge print("__" * 40) # loop through all key/value pairs for key,value in alien.items(): print(key, value) print("__" * 40) for key in sorted(alien.keys()): print(key) print("__" * 40) for value in alien.values(): print(value) print("__" * 40)
true
7b3f5e98d0ec4f94764e65e70a68c542f44ea966
knpatil/learning-python
/src/lists2.py
2,077
4.46875
4
cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) # sort a list by alphabetical order # cars.sort() # print(cars) # # cars.sort(reverse=True) # reverse order sort # print(cars) print(sorted(cars)) # temporarily sort a list print(cars) cars.reverse() print(cars) print(len(cars)) # print(cars[4]) # exceptions # comment for car in cars: print(car.title()) # 4 spaces of indentation for value in range(1, 1): # in operator always works with list print(value) for number in [1, 2, 4, 2]: # print(number) numbers = [11, 232, 44, 0, 2, 5] smallest_number = min(numbers) print(smallest_number) biggest_number = max(numbers) print(biggest_number) print("sum of all numbers:", sum(numbers)) # List comprehensions: allows you to generate a list using some code # list of squares for numbers: 1 - 10 # ** exponent print("--------") for x in range(1, 11): print(x**2) print("--------") squares = [x**2 for x in range(1, 11)] print("squares of 1 - 10: ", squares) cubes = [x**3 for x in range(1, 11)] print("cubes of 1 - 10: ", cubes) # slice of list (part of the list) print("Cubes of first 5 numbers: ", cubes[0:5]) # 0, 1, 2, 3, 4 print("Cubes of numbers from 2 - 4: ", cubes[1:4]) # 0, 1, 2, 3, 4 start = 0 end = 6 print(cubes[:end]) # slice 0 --> 5 end index non-inclusive print(cubes[4:]) # slice 0 --> 5 end index non-inclusive print(cubes[:]) # slice of last 3 numbers in the list print(cubes[-3:]) print(cubes[-3:-1]) # for number in cubes[4:8]: # list slice from 4th to 7th item print(number) squares2 = squares print(squares) squares[0] = 9999 print("squares:", squares) print("squares2:", squares2) squares3 = squares[:] # new slice print(squares3) squares[0] = 1111 print(squares3) squares[5] = 42942940 print(squares) # lists in python are mutable(changeable): that means you can change/modify the values # tuple -- immutable <-- you cannot change values x = (2, 4) # using a round bracket, it is a tuple print(x) print(x[0]) # accessing the value for i in x: print(i) x = (3, 9) # types are dynamic
true
a87bf15fb1e4f742f5f31be7a1af84276ffe6fc2
MaxAttax/maxattax.github.io
/resources/Day1/00 - Python Programming/task4.py
808
4.40625
4
# Task 4: Accept comma-separated input from user and put result into a list and into a tuple # The program waits until the user inputs a String into the console # For this task, the user should write some comma-separated integer values into the console and press "Enter" values = input() # Use for Python 3 # After the user pressed "Enter", the rest of the program from here is executed # The split()-operator splits a given String at the indicated separator (here a comma ",") # The split(",") function is used with the value that carries the user input from above (values) l = values.split(",") # A tuple is a special kind of list that can not be modified or extended. # The tuple() function generates a tuple from a given list. t = tuple(l) # Finally the results are printed out. print(l) print(t)
true
e829a743405b49893446c705272db2f7323bb329
Sharanhiremath02/C-98-File-Functions
/counting_words_from_file.py
281
4.375
4
def count_words_from_file(): fileName=input("Enter the File Name:") file=open(fileName,"r") num_words=0 for line in file: words=line.split() num_words=num_words+len(words) print("number of words:",num_words) count_words_from_file()
true
7c821b9a5102495f8f22fc21e29dd9812c77b3bd
chetanDN/Python
/AlgorithmsAndPrograms/02_RecursionAndBacktracking/01_FactorialOfPositiveInteger.py
222
4.125
4
#calculate the factorial of a positive integer def factorial(n): if n == 0: #base condition return 1 else: return n * factorial(n-1) #cursive condition print(factorial(6))
true
9bbcd87d994a200ebe11bc09ff79995dd74eac0a
GBaileyMcEwan/python
/src/hello.py
1,863
4.5625
5
#!/usr/bin/python3 print("Hello World!\n\n\n"); #print a multi-line string print( ''' My Multi Line String ''' ); #concatinate 2 words print("Pass"+"word"); #print 'Ha' 4 times print("Ha" * 4); #get the index of the letter 'd' in the word 'double' print("double".find('d')); #print a lower-case version of the string print("This Sucks".lower()); #print special characters- double escape if you want to print a backslash print("This rocks\tThis rocks\\t"); #If you want to use double quotes here, you would need to escape them print("Single 'quotes' are fine but \"doubles\" are a problem"); #You can use / * + - as well as // (returns whole numbers only and ** which returns exponents and % which mods print(2/2); #variables are like the below my_string = "My sample string"; my_string += " string2"; my_int = 2+2; print(my_string + " testing "); print(my_int); #this is how you print a list/array my_list = [1,2,"three",True]; print(my_list[1]); #print the length of the list print(len(my_list)); #s is how you print from the index position and how many items in the list you want to printt print(my_list[3:len(my_list)]); #You can add items to the list as per below my_list.append(5); print(my_list[0:]); #you can also remove items from the list: my_list.remove("three"); print(my_list); print("My string is " + str(my_int) + " what"); #hashes or dictionaries are set like this ages = {'kevin': 59, 'alex': 60} print(ages); print(ages['kevin']); ages['kayla']=21; print(ages); ages['kayla']=22; print(ages); del ages['kayla']; print(ages); #use this as a safer way to delete an element from a hash ages.pop('alex'); print(ages); #print only the keys or values in the hash print(ages.keys()); print(ages.values()); print(list(ages.values())); #you can also create a hash/dictionary like this weights = dict(kevin=100, bob=200); print(weights);
true
34ad45e897f4b10154ccf0f0585c29e1e51ad2f8
EwarJames/alx-higher_level_programming
/0x0B-python-input_output/3-to_json_string.py
315
4.125
4
#!/usr/bin/python3 """Define a function that returns a json.""" import json def to_json_string(my_obj): """ Function that convert json to a string. Args: my_obj (str): Object to be converted. Return: JSON representation of an object (string) """ return json.dumps(my_obj)
true
431384abd81af78ff79355d261528645cf9c100b
pi408637535/Algorithm
/com/study/algorithm/daily/diameter-of-binary-tree.py
1,370
4.15625
4
''' 树基本是递归。 递归:四要素 本题思路:left+right=diameter https://www.lintcode.com/problem/diameter-of-binary-tree/description ''' #思路: #Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: a root of binary tree @return: return a integer """ def helper(self, root): if not root: return 0 left_depth = self.helper(root.left) right_depth = self.helper(root.right) depth = max(left_depth, right_depth) + 1 return depth def diameterOfBinaryTree(self, root): # write your code here left_depth = self.helper(root.left) right_depth = self.helper(root.right) return left_depth + right_depth if __name__ == '__main__': TreeNode1 = TreeNode(1) TreeNode2 = TreeNode(2) TreeNode3 = TreeNode(3) TreeNode4 = TreeNode(4) TreeNode5 = TreeNode(5) TreeNode1.left = TreeNode2 TreeNode1.right = TreeNode3 TreeNode2.left = TreeNode4 TreeNode2.right = TreeNode5 # TreeNode1 = TreeNode(1) # TreeNode2 = TreeNode(2) # TreeNode3 = TreeNode(3) # # TreeNode2.left = TreeNode3 # TreeNode3.left = TreeNode1 print(Solution().diameterOfBinaryTree(TreeNode1))
true
8661d933bf731b111cda9345752a0307ff4adca8
rodrigomanhaes/model_mommy
/model_mommy/generators.py
1,794
4.34375
4
# -*- coding:utf-8 -*- __doc__ = """ Generators are callables that return a value used to populate a field. If this callable has a `required` attribute (a list, mostly), for each item in the list, if the item is a string, the field attribute with the same name will be fetched from the field and used as argument for the generator. If it is a callable (which will receive `field` as first argument), it should return a list in the format (key, value) where key is the argument name for generator and value is the value for that argument. """ import sys import string import datetime from decimal import Decimal from random import randint, choice, random MAX_LENGTH = 300 def gen_from_list(L): '''Makes sure all values of the field are generated from the list L Usage: from mommy import Mommy class KidMommy(Mommy): attr_mapping = {'some_field':gen_from_list([A, B, C])} ''' return lambda: choice(L) # -- DEFAULT GENERATORS -- def gen_from_choices(C): choice_list = map(lambda x:x[0], C) return gen_from_list(choice_list) def gen_integer(min_int=-sys.maxint, max_int=sys.maxint): return randint(min_int, max_int) gen_float = lambda:random()*gen_integer() def gen_decimal(max_digits, decimal_places): num_as_str = lambda x: ''.join([str(randint(0,9)) for i in range(x)]) return "%s.%s" % ( num_as_str(max_digits-decimal_places), num_as_str(decimal_places) ) gen_decimal.required = ['max_digits', 'decimal_places'] gen_date = datetime.date.today gen_datetime = datetime.datetime.now def gen_string(max_length): return ''.join(choice(string.printable) for i in range(max_length)) gen_string.required = ['max_length'] gen_text = lambda: gen_string(MAX_LENGTH) gen_boolean = lambda: choice((True, False))
true
6c036ab3ae9e679019d589fbd8de8be45486773f
gbrough/python-projects
/palindrome-checker.py
562
4.375
4
# Ask user for input string # Reverse the string # compare if string is equal # challenge - use functions word = None def wordInput(): word = input("Please type a word you would like to see if it's a palindrome\n").lower() return word def reverseWord(): reversedWord = word[::-1] return reversedWord def palindromeCheck(): if word == reverseWord: print("Yes, you have entered a palindrome") else: print("Sorry, this word is not a palindrome") def main(): print("\nPalindrome Checker") wordInput reverseWord palindromeCheck main()
true
5ebe1f88e466c99ba52f3dd43a17e692b30c96b2
chena/aoc-2017
/day12.py
2,625
4.21875
4
""" part 1: Each program has one or more programs with which it can communicate, and they are bidirectional; if 8 says it can communicate with 11, then 11 will say it can communicate with 8. You need to figure out how many programs are in the group that contains program ID 0. For example, suppose you go door-to-door like a travelling salesman and record the following list: 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 In this example, the following programs are in the group that contains program ID 0: - Program 0 by definition. - Program 2, directly connected to program 0. - Program 3 via program 2. - Program 4 via program 2. - Program 5 via programs 6, then 4, then 2. - Program 6 via programs 4, then 2. Therefore, a total of 6 programs are in this group; all but program 1, which has a pipe that connects it to itself. How many programs are in the group that contains program ID 0? """ def __check_connections__(program_id, connections, group): for c in connections[program_id]: if c in group: continue group.add(c) __check_connections__(c, connections, group) def __get_connetions__(): with open('input/programs.txt') as f: content = f.readlines() connections = {} programs = [p.strip() for p in content] arrow = '<->' for p in programs: parts = p.split(arrow) program = int(parts[0].strip()) connections[program] = [int(l) for l in parts[1].strip().split(', ')] return connections def digital_plumber_zero_group(): connections = __get_connetions__() # traverse through each program and check its connections # keep track of the programs with a set zero_group = {0} __check_connections__(0, connections, zero_group) return len(zero_group) # print(digital_plumber_zero_group()) """ part 2: A group is a collection of programs that can all communicate via pipes either directly or indirectly. The programs you identified just a moment ago are all part of the same group. Now, they would like you to determine the total number of groups. In the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely of program 1. How many groups are there in total? """ def digital_plumber_group_count(): connections = __get_connetions__() # traverse through each program mark the group it belongs to groupings = {} for p in connections: if p in groupings: continue group = {p} __check_connections__(p, connections, group) for member in group: groupings[member] = p return len(set(groupings.values())) print(digital_plumber_group_count())
true
6e33fd4e81dcfdce22916bd20d4230e472490dae
chena/aoc-2017
/day05.py
1,882
4.53125
5
""" part 1: The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered. (0) 3 0 1 -3 - before we have taken any steps. (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1. 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2. 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind. 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2. 2 5 0 1 -2 - jump 4 steps forward, escaping the maze. In this example, the exit is reached in 5 steps. part 2: After each jump, if the offset was three or more, instead decrease it by 1. Otherwise, increase it by 1 as before. Using this rule with the above example, the process now takes 10 steps, and the offset values after finding the exit are left as 2 3 2 3 -1. How many steps does it now take to reach the exit? """ def __parse_maze_input__(filename): with open(filename) as f: content = f.readlines() return [int(n) for n in content] def maze_of_twisty(maze): steps = 0 index = 0 while (index < len(maze)): move_forward = maze[index] if (move_forward >= 3): maze[index] -= 1 else: maze[index] += 1 index += move_forward steps += 1 return steps print(maze_of_twisty([0, 3, 0, 1, -3])) # print(maze_of_twisty(__parse_maze_input__('input/maze.txt')))
true
164dda3ecb9d27c153dbc9d143ba05437c47f656
luisprooc/data-structures-python
/src/bst.py
1,878
4.1875
4
from binary_tree import Node class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): current = self.root while current: if new_val >= current.value: if not current.right: current.right = Node(new_val) return current = current.right else: if not current.left: current.left = Node(new_val) return current = current.left def search(self, find_val): # If current node is equal to # find_value, return True if self.root.value == find_val: return True else: # If the find_value is bigger to current node and the current # node not is a leaf, scroll right if find_val >= self.root.value and self.root.right: self.root = self.root.right return self.search(find_val) else: # If current node not is a leaf, scroll left if self.root.left: self.root = self.root.right return self.search(find_val) # This means that you reached a leaf and not # find the expected value return False def preorder_print(self, start, traversal): if start: traversal += (str(start.value) + "-") traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print (tree.search(4)) # Should be False print (tree.search(6))
true
757cfb65fc22c1f8f9326a25018defb7aafbad56
2FLing/CSCI-26
/codewar/camel_case.py
531
4.25
4
# Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). # Examples # to_camel_case("the-stealth-warrior") # returns "theStealthWarrior" # to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior" def to_camel_case(s): return s[0]+s.translate(str.maketrans("","","-_"))[1:] print(to_camel_case("I_love-You"))
true
5a5581ad8604d9d61d579ab1661be5c7d70cdcb6
rodrigocamarena/Homeworks
/sess3&4ex4.py
2,915
4.5
4
print("Welcome to the universal pocket calculator.") print("1. Type <+> if you want to compute a sum." "\n2. Type <-> if you want to compute a rest." "\n3. Type <*> if you want to compute a multiplication." "\n4. Type </> if you want to compute a division." "\n5. Type <quit> if you want to exit.") while True: prompt = 'Introduce your answer: ' answer = input(prompt) if answer == "+": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num + num2 print("The result of: ",num,"+",num2," is: ",result) break elif answer == "-": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num - num2 print("The result of: ",num,"-",num2," is: ",result) break elif answer == "*": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num * num2 print("The result of: ",num,"*",num2," is: ",result) break elif answer == "/": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num / num2 print("The result of: ", num, "/", num2, " is: ", result) break elif answer == "quit": print("Was a pleasure working with you. See you soon!") break else: print("opps, invalid answer. Try again please!")
true
7536d2a8c16cc9bda41d4a4d3894c0a8a0911446
artemis-beta/phys-units
/phys_units/examples/example_2.py
1,160
4.34375
4
############################################################################## ## Playing with Measurements ## ## ## ## In this example the various included units are explored in a fun and ## ## silly way to illustrate how units_database behaves. ## ## ## ############################################################################## #--------------------- Fetch all the units we need --------------------------# from units_database import mile, m, furlong, yd, pc, rod my_distance = 5*mile # By default units_database will use SI units the function 'as_base' treats # the unit as a base unit. print('Today I ran {}.'.format(my_distance.as_base())) print('This is equivalent to {}'.format(my_distance)) print('or (if we want to be silly), this is also {}'.format(my_distance.as_unit(pc))) print('In Imperial units this is also {}'.format(my_distance.as_unit(yd))) print('or (to be unusual) {}'.format(my_distance.as_unit(furlong)))
true
3c419f360e36ed45af7d7935aa2f824bb2dc472a
Cleancode404/ABSP
/Chapter8/input_validation.py
317
4.1875
4
import pyinputplus as pyip while True: print("Enter your age:") age = input() try: age = int(age) except: print("Please use numeric digits.") continue if age < 0: print("Please enter a positive number.") continue break print('Your age is', age)
true
bf005c98b3c7beabc0e2000cfd0cfd404010a9a9
AlexRoosWork/PythonScripts
/delete_txts.py
767
4.15625
4
#!/usr/bin/env python3 # given a directory, go through it and its nested dirs to delete all .txt files import os def main(): print(f"Delete all text files in the given directory\n") path = input("Input the basedir:\n") to_be_deleted = [] for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith(".txt"): string = dirpath + os.sep + filename to_be_deleted.append(string) num_of_files = len(to_be_deleted) if input(f"sure you want to delete {num_of_files} .txt files? (y/n)") == "y": for file in to_be_deleted: os.remove(file) print("Done.") else: print("Abortion.") if __name__ == "__main__": main()
true
8ae3f309e572b41a3ff5205692f0ae4c90f11962
Trenchevski/internship
/python/ex6.py
867
4.21875
4
# Defining x with string value x = "There are %d types of people." % 10 # Binary variable gets string value with same name binary = "binary" # Putting string value to "don't" do_not = "don't" # Defining value of y variable using formatters y = "Those who know %s and those who %s." % (binary, do_not) # Printing value of x print x # Printing value of y print y # Printing value of x using formatters print "I said: %r." % x # Printing value of y using formatters print "I also said: '%s'." % y # Boolean with value False hilarious = False # Variable joke_evaluation gets string value joke_evaluation = "Isn't that joke so funny?! %r" # Printing mod of two previous variables print joke_evaluation % hilarious # Putting string value to w and e variables w = "This is the left side of..." e = "a string with a right side." # Printing them one after another print w + e
true
6cd204d47bb1937a024c1afa0c25527316453468
Soares/natesoares.com
/overviewer/utilities/string.py
633
4.5
4
def truncate(string, length, suffix='...'): """ Truncates a string down to at most @length characters. >>> truncate('hello', 12) 'hello' If the string is longer than @length, it will cut the string and append @suffix to the end, such that the length of the resulting string is @length. >>> truncate('goodbye', 4) 'g...' >>> truncate('goodbye', 6) 'goo...' @suffix defaults to '...'. >>> truncate('hello', 3, '..') 'h..' >>> truncate('hello', 3, '') 'hel' """ if len(string) <= length: return string return string[:length-len(suffix)] + suffix
true
066bcfb00c4f01528d79d8a810a65d2b64e8a8a2
bchaplin1/homework
/week02/03_python_homework_chipotle.py
2,812
4.125
4
''' Python Homework with Chipotle data https://github.com/TheUpshot/chipotle ''' ''' BASIC LEVEL PART 1: Read in the data with csv.reader() and store it in a list of lists called 'data'. Hint: This is a TSV file, and csv.reader() needs to be told how to handle it. https://docs.python.org/2/library/csv.html ''' import csv cd 'c:\ml\dat7\data' with open ('chipotle.tsv','rU') as f: data = [row for row in csv.reader(f,delimiter='\t')] ''' BASIC LEVEL PART 2: Separate the header and data into two different lists. ''' header = data[0] data = data[1:] ''' INTERMEDIATE LEVEL PART 3: Calculate the average price of an order. Hint: Examine the data to see if the 'quantity' column is relevant to this calculation. Hint: Think carefully about the simplest way to do this! ''' sum([float(d[4].replace('$','')) for d in data])/len(set([d[0] for d in data])) ''' INTERMEDIATE LEVEL PART 4: Create a list (or set) of all unique sodas and soft drinks that they sell. Note: Just look for 'Canned Soda' and 'Canned Soft Drink', and ignore other drinks like 'Izze'. ''' drinks = set() for d in data: if d[2] == 'Canned Soda' or d[2] == 'Canned Soft Drink': drinks.add(d[3]) print drinks ''' ADVANCED LEVEL PART 5: Calculate the average number of toppings per burrito. Note: Let's ignore the 'quantity' column to simplify this task. Hint: Think carefully about the easiest way to count the number of toppings! ''' topCt = 0 burritoCt = 0 for d in data: if d[2] == 'Burrito' : topCt += len(d[3].split('[')[-1].split(',')) burritoCt+=1 avgCt = topCt / float(burritoCt) print 'average number of toppings per burrito is ' + str(avgCt) ''' ADVANCED LEVEL PART 6: Create a dictionary in which the keys represent chip orders and the values represent the total number of orders. Expected output: {'Chips and Roasted Chili-Corn Salsa': 18, ... } Note: Please take the 'quantity' column into account! Optional: Learn how to use 'defaultdict' to simplify your code. ''' from collections import defaultdict chips = [d for d in data if d[2].startswith('Chips')] d = defaultdict(int) for order in chips: d[order[2]]+=int(order[1]) print d.items() ''' BONUS: Think of a question about this data that interests you, and then answer it! ''' ''' is there a correlation between meat selection and toppings, like fat content? let's put them in a dictionary and find out ''' chicken = [d for d in data if d[2].startswith('Chicken')] steak = [d for d in data if d[2].startswith('Steak')] orderSum = 0 print 'chicken' + str(sum([float(d[4].replace('$','')) for d in chicken])/len(set([d[0] for d in chicken]))) print 'steak' + str(sum([float(d[4].replace('$','')) for d in steak])/len(set([d[0] for d in steak])))
true
90af163267b8d485c28169c9aeb149df021e3509
hemenez/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
423
4.3125
4
#!/usr/bin/python3 def add_integer(a, b): """Module will add two integers """ total = 0 if type(a) is not int and type(a) is not float: raise TypeError('a must be an integer') if type(b) is not int and type(b) is not float: raise TypeError('b must be an integer') if type(a) is float: a = int(a) if type(b) is float: b = int(b) total = a + b return total
true
ba2c8e1e768b24f7ad7a4c00ee6ed4116d31a21a
kjigoe/Earlier-works
/Early Python/Fibonacci trick.py
866
4.15625
4
dic = {0:0, 1:1} def main(): n = int(input("Input a number")) ## PSSST! If you use 45 for 'n' you get a real phone number! counter = Counter() x = fib(n,counter) print("Fibonacci'd with memoization I'd get",x) print("I had to count",counter,"times!") y = recursivefib(n, counter) print("And with recusion I still get",y) print("But the count changes to",counter) def fib(n,counter): if n in dic: return dic[n] else: counter.increment() if n < 2: dic[n] = n else: dic[n] = fib(n-2,counter) + fib(n-1,counter) return dic[n] def recursivefib(n, counter): if n < 2: return n else: counter.increment() return (recursivefib(n-2,counter) + recursivefib(n-1,counter)) class Counter(object): def __init__(self): self._number = 0 def increment(self): self._number += 1 def __str__(self): return str(self._number) main()
true
e996c9bff605c46d30331d13e44a49c04a2e29be
Kaylotura/-codeguild
/practice/greeting.py
432
4.15625
4
"""Asks for user's name and age, and greets them and tells them how old they'll be next year""" # 1. Setup # N/A # 2. Input name = input ("Hello, my name is Greetbot, what's your name? ") age = input(name + ' is a lovely name! How old are you, ' + name + '? ') # 3. Transform olderage = str(int(age) + 1) # 4. Output print ("You're " + age + "-years old? Wow, I guess that means you're going to be " + olderage + " next year!")
true
922c0d74cf538e3a28a04581b9f57f7cfb7377e4
BstRdi/wof
/wof.py
1,573
4.25
4
from random import choice """A class that can be used to represent a wheel of fortune.""" fields = ('FAIL!', 'FAIL!', 100, 'FAIL!', 'FAIL!', 500, 'FAIL!', 250, 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 1000, 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!') score = [] class WheelOfFortune: """A simple attempt to represent a wheel of fortune.""" def __init__(self, fields, spins=10): """Initialize attributes to describe a wheel of fortune.""" self.fields = fields self.spins = spins def spin_wheel(self): """Spin the wheel of fortune""" for spin in range(1, self.spins): spin = choice(fields) print(spin) if isinstance(spin, int) == True: score.append(spin) sum_score = sum(score) print(f'{player_name} you got {sum_score} points!') # Spin for player one player_name = input('Player One - Enter your name: ') player_one = WheelOfFortune(fields) player_one.spin_wheel() player_one_score = score[:] player_one_name = player_name del score[:] # Spin for player two player_name = input('Player Two - Enter your name: ') player_two = WheelOfFortune(fields) player_two.spin_wheel() player_two_score = score[:] player_two_name = player_name # Selection of the winner if player_one_score > player_two_score: print(f'{player_one_name} wins!') elif player_two_score > player_one_score: print(f'{player_two_name} wins!') elif player_one_score == player_two_score: print('Draw!')
true
b63879f6a16ae903c1109d3566089e47d0212200
idahopotato1/learn-python
/01-Basics/005-Dictionaries/dictionaries.py
1,260
4.375
4
# Dictionaries # A dictionary is an associative array (also known as hashes). # Any key of the dictionary is associated (or mapped) to a value. # The values of a dictionary can be any Python data type. # So dictionaries are unordered key-value-pairs. # Constructing a Dictionary my_dist = {'key1': 'value1', 'key2': 100, 'key3': 99.99} # Accessing Objects from a dictionary print(my_dist['key2']) # 100 print(my_dist['key1'].upper()) # VALUE1 print(my_dist['key2'] - 2) # 98 print(my_dist['key2']) # 100 my_dist['key2'] = my_dist['key2'] - 2 print(my_dist['key2']) # 98 print(my_dist) # {'key1': 'value1', 'key2': 98, 'key3': 99.99} my_colors = {} my_colors['color1'] = 'red' my_colors['color2'] = 'green' print(my_colors) # {'color1': 'red', 'color2': 'green'} # Nesting dictionary my_dist2 = {'key1': {'subKey': 'value'}, 'key2': 100, 'key3': 99.99} print(my_dist2['key1']['subKey'].upper()) # VALUE # Basic Dictionary Methods my_dist3 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} print(my_dist3.keys()) # dict_keys(['key1', 'key2', 'key3']) print(my_dist3.values()) # dict_values(['value1', 'value2', 'value3']) print(my_dist3.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
true
b5dbb2bc21aca13d23b3d3f87569877ce9951eec
idahopotato1/learn-python
/04-Methods-Functions/001-methods.py
736
4.34375
4
# Methods # The other kind of instance attribute reference is a method. # A method is a function that “belongs to” an object. # (In Python, the term method is not unique to class instances: # other object types can have methods as well. # For example, list objects have methods called append, insert, remove, sort, and so on. print('=============================================') my_list = [1, 2, 3] my_list.append(4) print(my_list) # [1, 2, 3, 4] print('=============================================') print(my_list.count(3)) # 1 print('=============================================') print(help(my_list.append)) # append(...) method of builtins.list instance print('=============================================')
true
4afb88e53ccddb16c631b2af181bb0e607a2b37b
Evakung-github/Others
/381. Insert Delete GetRandom O(1).py
2,170
4.15625
4
''' A hashmap and an array are created. Hashmap tracks the position of value in the array, and we can also use array to track the appearance in the hashmap. The main trick is to swap the last element and the element need to be removed, and then we can delete the last element at O(1) cost. Afterwards, we need to update the position of the original last element in the hashmap to its current position. Therefore, that's why we need to record its space in the value of the hashmap. ref: https://www.youtube.com/watch?v=mRTgft9sBhA ''' import random class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.array = [] self.dict = {} def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. """ if val not in self.dict: self.dict[val] = [len(self.array)] self.array.append([val,0]) return True else: self.dict[val].append(len(self.array)) self.array.append([val,len(self.dict[val])-1]) def remove(self, val: int) -> bool: """ Removes a value from the collection. Returns true if the collection contained the specified element. """ if val in self.dict: if not self.dict[val]: return False else: n = self.dict[val][-1] self.dict[self.array[-1][0]][self.array[-1][1]] = n n = self.dict[val].pop() self.array[n], self.array[-1] = self.array[-1],self.array[n] self.array.pop() return True def getRandom(self) -> int: """ Get a random element from the collection. """ n = random.randint(0,len(self.array)-1) return self.array[n][0] # Your RandomizedCollection object will be instantiated and called as such: # obj = RandomizedCollection() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
true
c57eab0302c15814a5f51c2cbc0fa104910eef08
hihihien/nrw-intro-to-python
/lecture-06/solutions/exponent.py
261
4.28125
4
base = float(input('What is your base?')) exp = float(input('What is your exponent?')) num = exp result = 1 while num > 0: result = result * base num = num - 1 print(f'{base} raised to the power of {exp} is: {result}. ({base} ** {exp} = {base**exp})')
true
ef2e1747c49dca4e17fe558704d05d50b2a11506
kengbailey/interview-prep
/selectionsort.py
1,507
4.28125
4
# Selection Sort Implementation in Python ''' How does it work? for i = 1:n, k = i for j = i+1:n, if a[j] < a[k], k = j → invariant: a[k] smallest of a[i..n] swap a[i,k] → invariant: a[1..i] in final position end What is selection sort? The selection sort algorithm is a combination of searching and sorting. It sorts an array by repeatedly finding the minimum/maximum element from unsorted part and putting it at the end. In selection sort, the inner loop finds the next smallest (or largest) value and the outer loop places that value into its proper location. Selection sort should never be used. it does not adapt to the data in any way. What is performance of selection sort in Big'O? Worst-case performance О(n2) Best-case performance О(n2) Average performance О(n2) Worst-case space Complexity О(n) total, O(1) auxiliary ''' def selection_sort(unsorted_arr): for x in range(len(unsorted_arr)): # store current position n = x # search for the position of the next smallest value # in the unsorted part for y in range(x+1, len(unsorted_arr)): if unsorted_arr[y] < unsorted_arr[n]: n = y # swap next smallest value into postition swap(x,n,unsorted_arr) print(unsorted_arr) def swap(a, b, array): temp2 = array[a] array[a] = array[b] array[b] = temp2 arr = [10,9,7,8,6,5,4,2,3,1] print("Unsorted: ", arr) selection_sort(arr) print("Sorted: ", arr)
true
6c612b3a3904a9710b3f47c0174edf1e0f15545b
spots1000/Python_Scripts
/Zip File Searcher.py
2,412
4.15625
4
from zipfile import ZipFile import sys import os #Variables textPath = "in.txt" outPath = "out.txt" ## Announcements print("Welcome to the Zip Finder Program!") print("This program will take a supplied zip file and locate within said file any single item matching the strings placed in an accompanying text file.") input("To use this program please place the desired skus or other identifies in a folder called \"" + textPath + "\" and then press Enter to continue.\n") ## Ensure before opening text file that we have a valid file to read. if not (os.path.isfile(textPath)): print("A valid text file was not found, program will now exit.") input("Press any key to exit...") sys.exit() ## Attempt to open our text file and read in the data targetList = [] textFile = open(textPath, encoding="utf8") for line in textFile: strippedLine = line.strip("\n") strippedLine = strippedLine.strip("\t") targetList.append(strippedLine) print("Text File successfully read in with " + str(len(targetList)) + " items.") textFile.close() ## Get the filename fileName = input("Please enter the name of the zip file without any extensions. >>>") fileName = fileName + ".zip" ## Make sure the file exists try: zip = ZipFile(fileName, 'r') except: print("Zip File Was Not Opened Successfully") print("Program will exit") sys.exit() print("Zip file was read successfully, processing will now comence") ## Read the zip file fileData = zip.infolist() errorList = [] ## Loop through the data for the relevant for target in targetList: print("Attemtping to locate " + target) found = "false" for dat in fileData: if (target in dat.filename): print("Located target file") path = zip.extract(dat) found = "true" break; if(found == "false"): print("Target was not found.") errorList.append(target) ## output to the output file outFile = open(outPath, "a") for err in errorList: outFile.write(err + "\n") outFile.close() i = len(targetList) - len(errorList) ##Final output print("All processing completed. " + str(i) + " total folders successfully processed while " + str(len(errorList)) + " folders were not able to be found.") input("Press any key to exit...") sys.exit()
true
77ee96c305f1d7d21ddae8c1029639a50627382b
SamuelHealion/cp1404practicals
/prac_05/practice_and_extension/electricity_bill.py
1,317
4.1875
4
""" CP1404 Practice Week 5 Calculate the electricity bill based on provided cents per kWh, daily use and number of billing days Changed to use dictionaries for the tariffs """ TARIFFS = {11: 0.244618, 31: 0.136928, 45: 0.385294, 91: 0.374825, 33: 0.299485} print("Electricity bill estimator 2.0") print("Which tariff are you on?") for tariff, cost in TARIFFS.items(): print("Tariff {} at {} per kWh".format(tariff, cost)) valid_tariff = False while not valid_tariff: try: which_tariff = int(input(">>> ")) if which_tariff in TARIFFS.keys(): valid_tariff = True else: print("Not a valid tariff") except ValueError: print("Please enter a number") daily_use = float(input("Enter daily use in kWh: ")) number_of_days = float(input("Enter number of billing days: ")) estimated_bill = TARIFFS[which_tariff] * daily_use * number_of_days print("Estimated bill: ${:.2f}".format(estimated_bill)) """ Original version print("Electricity bill estimator") cents_per_kwh = float(input("Enter cents per kWh: ")) daily_use = float(input("Enter daily use in kWh: ")) number_of_days = float(input("Enter number of billing days: ")) estimated_bill = (cents_per_kwh / 100) * daily_use * number_of_days print("Estimated bill: ${:.2f}".format(estimated_bill)) """
true
823282e7460b9d11b4d4127fa68a87352a5543ce
SamuelHealion/cp1404practicals
/prac_02/practice_and_extension/word_generator.py
2,154
4.25
4
""" CP1404/CP5632 - Practical Random word generator - based on format of words Another way to get just consonants would be to use string.ascii_lowercase (all letters) and remove the vowels. """ import random VOWELS = "aeiou" CONSONANTS = "bcdfghjklmnpqrstvwxyz" def first_version(): """Requires c and v only""" print("Please enter the word format: C for Consonants, V for Vowels") word_format = str(input("> ").lower()) word = "" for kind in word_format: if kind == "c": word += random.choice(CONSONANTS) elif kind == "v": word += random.choice(VOWELS) else: print("Invalid input") break print(word) def second_version(): """Uses wild cards but also accepts regular inputs # for vowels, % for consonants and * for either""" print("Random word generator that includes your characters but uses:") print("Enter # for Vowels, % for Consonants or * for either") word_format = str(input("> ")) word = "" for kind in word_format: if kind == "%": word += random.choice(CONSONANTS) elif kind == "#": word += random.choice(VOWELS) elif kind == "*": word += random.choice(CONSONANTS + VOWELS) else: word += kind print(word) def third_version(): """Automatically generates the word_format for a random length between 1 and 20""" word_length = random.randint(0, 20) word_format = '' for i in range(word_length): word_format += random.choice('%' + '#') word = "" for kind in word_format: if kind == "%": word += random.choice(CONSONANTS) elif kind == "#": word += random.choice(VOWELS) print(word) user_input = '' while user_input != 'Q': print("Press Q to quit") print("What version would you like to run? 1, 2 or 3") user_input = str(input(">>> ")).upper() if user_input == '1': first_version() elif user_input == '2': second_version() elif user_input == '3': third_version() else: print("Invalid option")
true
d2539727c20ffae59e81cccadb78648b10797a5d
SamuelHealion/cp1404practicals
/prac_06/guitar.py
730
4.3125
4
""" CP1404 Practical 6 - Classes Define the class Guitar """ VINTAGE_AGE = 50 CURRENT_YEAR = 2021 class Guitar: """Represent a Guitar object.""" def __init__(self, name='', year=0, cost=0): """Initialise a Guitar instance.""" self.name = name self.year = year self.cost = cost def __str__(self): """Return a string representation of a Guitar object.""" return "{} ({}) : ${:,.2f}".format(self.name, self.year, self.cost) def get_age(self): """Return the age of the guitar.""" return CURRENT_YEAR - self.year def is_vintage(self): """Return whether a Guitar is 50 years old or older.""" return self.get_age() >= VINTAGE_AGE
true
6339d40839889e191b3ef8dae558cf3266b08ba8
jamieboyd/neurophoto2018
/code/simple_loop.py
407
4.46875
4
#! /usr/bin/python #-*-coding: utf-8 -*- """ a simple for loop with conditionals % is the modulus operator, giving the remainder of the integer division of the left operand by the right operand. If a number divides by two with no remainder it is even. """ for i in range (0,10,1): if i % 2 == 1: print (str (i) + ' is an odd number.') else: print (str (i) + ' is an even number.')
true
86dec63990bd3ae55a023380af8ce0f38fcdf3e2
CQcodes/MyFirstPythonProgram
/Main.py
341
4.25
4
import Fibonacci import Check # Driver Code print("Program to print Fibonacci series upto 'n'th term.") input = input("Enter value for 'n' : ") if(Check.IsNumber(input)): print("Printing fibonacci series upto '" + input + "' terms.") Fibonacci.Print(int(input)) else: print("Entered value is not a valid integer. Please Retry.")
true
f193bf10635f1b1cc9f4f7aa0ae7a209e5f041db
Yashs744/Python-Programming-Workshop
/if_else Ex-3.py
328
4.34375
4
# Nested if-else name = input('What is your name? ') # There we can provide any name that we want to check with if name.endswith('Sharma'): if name.startswith('Mr.'): print ('Hello,', name) elif name.startswith('Mrs.'): print ('Hello,', name) else: print ('Hello,', name) else: print ('Hello, Stranger')
true
012cc0af4adbfa714a4f311b729d89a9ba446d35
Tagirijus/ledger-expenses
/general/date_helper.py
1,213
4.1875
4
import datetime from dateutil.relativedelta import relativedelta def calculateMonths(period_from, period_to): """Calculate the months from two given dates..""" if period_from is False or period_to is False: return 12 delta = relativedelta(period_to, period_from) return abs((delta.years * 12) + delta.months) def interpreteDate(date): """Interprete given date and return datetime or bool.""" if date is False: return False try: return datetime.datetime.strptime(date, '%Y-%m') except Exception as e: return False def normalizePeriods(months, period_from, period_to): """ Normlize the periods so that teh programm can work with them. Basically it tries to generate the other period with self.months months in difference, if only one period date is given. """ if period_from is False and period_to is False: return (False, False) elif period_from is False and period_to is not False: period_from = period_to - relativedelta(months=months) elif period_from is not False and period_to is False: period_to = period_from + relativedelta(months=months) return (period_from, period_to)
true
b5a66fd0978895aaabb5cb93de5a7cfabd57ad8e
yosef8234/test
/python_simple_ex/ex28.py
477
4.3125
4
# Write a function find_longest_word() that takes a list of words and # returns the length of the longest one. # Use only higher order functions. def find_longest_word(words): ''' words: a list of words returns: the length of the longest one ''' return max(list(map(len, words))) # test print(find_longest_word(["i", "am", "pythoning"])) print(find_longest_word(["hello", "world"])) print(find_longest_word(["ground", "control", "to", "major", "tom"]))
true
b787971db2b58732d63ea00aaac8ef233068b822
yosef8234/test
/python_simple_ex/ex15.py
443
4.25
4
# Write a function find_longest_word() that takes a list of words and # returns the length of the longest one. def find_longest_word(words): longest = "" for word in words: if len(word) >= len(longest): longest = word return longest # test print(find_longest_word(["i", "am", "pythoning"])) print(find_longest_word(["hello", "world"])) print(find_longest_word(["ground", "control", "to", "major", "tom"]))
true
9b22d6e5f777384cd3b88f9d44b7f2711346fc74
yosef8234/test
/pfadsai/07-searching-and-sorting/notes/sequential-search.py
1,522
4.375
4
# Sequential Search # Check out the video lecture for a full breakdown, in this Notebook all we do is implement Sequential Search for an Unordered List and an Ordered List. def seq_search(arr,ele): """ General Sequential Search. Works on Unordered lists. """ # Start at position 0 pos = 0 # Target becomes true if ele is in the list found = False # go until end of list while pos < len(arr) and not found: # If match if arr[pos] == ele: found = True # Else move one down else: pos = pos+1 return found arr = [1,9,2,8,3,4,7,5,6] print seq_search(arr,1) #True print seq_search(arr,10) #False # Ordered List # If we know the list is ordered than, we only have to check until we have found the element or an element greater than it. def ordered_seq_search(arr,ele): """ Sequential search for an Ordered list """ # Start at position 0 pos = 0 # Target becomes true if ele is in the list found = False # Stop marker stopped = False # go until end of list while pos < len(arr) and not found and not stopped: # If match if arr[pos] == ele: found = True else: # Check if element is greater if arr[pos] > ele: stopped = True # Otherwise move on else: pos = pos+1 return found arr.sort() ordered_seq_search(arr,3) #True ordered_seq_search(arr,1.5) #False
true
720f5fa949f49b1fa20d7c0ae08ae397fc6fc225
yosef8234/test
/pfadsai/03-stacks-queues-and-deques/notes/implementation-of-stack.py
1,537
4.21875
4
# Implementation of Stack # Stack Attributes and Methods # Before we implement our own Stack class, let's review the properties and methods of a Stack. # The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. The stack operations are given below. # Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack. # push(item) adds a new item to the top of the stack. It needs the item and returns nothing. # pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified. # peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified. # isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value. # size() returns the number of items on the stack. It needs no parameters and returns an integer. class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) s = Stack() print(s.isEmpty()) s.push(1) s.push('two') s.peek() s.push(True) s.size() s.isEmpty() s.pop() s.size()
true
5d1b9a089f9f4c0e6b8674dafffa486f4698cdb4
yosef8234/test
/toptal/python-interview-questions/4.py
1,150
4.5
4
# Q: # What will be the output of the code below in Python 2? Explain your answer. # Also, how would the answer differ in Python 3 (assuming, of course, that the above print statements were converted to Python 3 syntax)? def div1(x,y): print "%s/%s = %s" % (x, y, x/y) def div2(x,y): print "%s//%s = %s" % (x, y, x//y) div1(5,2) div1(5.,2) div2(5,2) div2(5.,2.) # A: # In Python 2, the output of the above code will be: 5/2 = 2 5.0/2 = 2.5 5//2 = 2 5.0//2.0 = 2.0 # By default, Python 2 automatically performs integer arithmetic if both operands are integers. As a result, 5/2 yields 2, while 5./2 yields 2.5. # Note that you can override this behavior in Python 2 by adding the following import: from __future__ import division # Also note that the “double-slash” (//) operator will always perform integer division, regardless of the operand types. That’s why 5.0//2.0 yields 2.0 even in Python 2. # Python 3, however, does not have this behavior; i.e., it does not perform integer arithmetic if both operands are integers. Therefore, in Python 3, the output will be as follows: 5/2 = 2.5 5.0/2 = 2.5 5//2 = 2 5.0//2.0 = 2.0
true
3c39888213a9dcc78c1c0a641b9ab70c87680c0a
yosef8234/test
/pfadsai/04-linked-lists/questions/linked-list-reversal.py
2,228
4.46875
4
# Problem # Write a function to reverse a Linked List in place. The function will take in the head of the list as input and return the new head of the list. # You are given the example Linked List Node class: class Node(object): def __init__(self,value): self.value = value self.nextnode = None # Solution # Since we want to do this in place we want to make the funciton operate in O(1) space, meaning we don't want to create a new list, so we will simply use the current nodes! Time wise, we can perform the reversal in O(n) time. # We can reverse the list by changing the next pointer of each node. Each node's next pointer should point to the previous node. # In one pass from head to tail of our input list, we will point each node's next pointer to the previous element. # Make sure to copy current.next_node into next_node before setting current.next_node to previous. Let's see this solution coded out: def reverse(head): # Set up current,previous, and next nodes current = head previous = None nextnode = None # until we have gone through to the end of the list while current: # Make sure to copy the current nodes next node to a variable next_node # Before overwriting as the previous node for reversal nextnode = current.nextnode # Reverse the pointer ot the next_node current.nextnode = previous # Go one forward in the list previous = current current = nextnode return previous # You should be able to easily test your own solution to make sure it works. Given the short list a,b,c,d with values 1,2,3,4. Check the effect of your reverse function and maek sure the results match the logic here below: # Create a list of 4 nodes a = Node(1) b = Node(2) c = Node(3) d = Node(4) # Set up order a,b,c,d with values 1,2,3,4 a.nextnode = b b.nextnode = c c.nextnode = d print(a.nextnode.value) print(b.nextnode.value) print(c.nextnode.value) reverse(a) print(d.nextnode.value) print(c.nextnode.value) print(b.nextnode.value) # Great, now we can see that each of the values points to its previous value (although now that the linked list is reversed we can see the ordering has also reversed)
true
9041e5cb16518965f170e82bdac4929e93ab0273
yosef8234/test
/hackerrank/30-days-of-code/day-24.py
2,826
4.375
4
# # -*- coding: utf-8 -*- # Objective # Check out the Tutorial tab for learning materials and an instructional video! # Task # A Node class is provided for you in the editor. A Node object has an integer data field, datadata, and a Node instance pointer, nextnext, pointing to another node (i.e.: the next node in a list). # A removeDuplicates function is declared in your editor, which takes a pointer to the headhead node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list. # Note: The headhead pointer may be null, indicating that the list is empty. Be sure to reset your nextnext pointer when performing deletions to avoid breaking the list. # Input Format # You do not need to read any input from stdin. The following input is handled by the locked stub code and passed to the removeDuplicates function: # The first line contains an integer, NN, the number of nodes to be inserted. # The NN subsequent lines each contain an integer describing the datadata value of a node being inserted at the list's tail. # Constraints # The data elements of the linked list argument will always be in non-decreasing order. # Output Format # Your removeDuplicates function should return the head of the updated linked list. The locked stub code in your editor will print the returned list to stdout. # Sample Input # 6 # 1 # 2 # 2 # 3 # 3 # 4 # Sample Output # 1 2 3 4 # Explanation # N=6N=6, and our non-decreasing list is {1,2,2,3,3,4}{1,2,2,3,3,4}. The values 22 and 33 both occur twice in the list, so we remove the two duplicate nodes. We then return our updated (ascending) list, which is {1,2,3,4}{1,2,3,4}. class Node: def __init__(self,data): self.data = data self.next = None class Solution: def insert(self,head,data): p = Node(data) if head==None: head=p elif head.next==None: head.next=p else: start=head while(start.next!=None): start=start.next start.next=p return head def display(self,head): current = head while current: print(current.data,end=' ') current = current.next def removeDuplicates(self,head): node = head while node: if node.next: if node.data == node.next.data: node.next = node.next.next else: node = node.next else: node = node.next return head mylist= Solution() T=int(input()) head=None for i in range(T): data=int(input()) head=mylist.insert(head,data) head=mylist.removeDuplicates(head) mylist.display(head)
true
756868b809716f135bb1a27a9c35791e116a902a
yosef8234/test
/pfadsai/04-linked-lists/questions/implement-a-linked-list.py
952
4.46875
4
# Implement a Linked List - SOLUTION # Problem Statement # Implement a Linked List by using a Node class object. Show how you would implement a Singly Linked List and a Doubly Linked List! # Solution # Since this is asking the same thing as the implementation lectures, please refer to those video lectures and notes for a full explanation. The code from those lectures is displayed below: class LinkedListNode(object): def __init__(self,value): self.value = value self.nextnode = None a = LinkedListNode(1) b = LinkedListNode(2) c = LinkedListNode(3) a.nextnode = b b.nextnode = c class DoublyLinkedListNode(object): def __init__(self,value): self.value = value self.next_node = None self.prev_node = None a = DoublyLinkedListNode(1) b = DoublyLinkedListNode(2) c = DoublyLinkedListNode(3) # Setting b after a b.prev_node = a a.next_node = b # Setting c after a b.next_node = c c.prev_node = b
true
6eb333b658f76812126d0fefdb33a39e66f608bf
yosef8234/test
/pfadsai/10-mock-interviews/ride-share-company/on-site-question3.py
2,427
4.3125
4
# On-Site Question 3 - SOLUTION # Problem # Given a binary tree, check whether it’s a binary search tree or not. # Requirements # Use paper/pencil, do not code this in an IDE until you've done it manually # Do not use built-in Python libraries to do this, but do mention them if you know about them # Solution # The first solution that comes to mind is, at every node check whether its value is larger than or equal to its left child and smaller than or equal to its right child (assuming equals can appear at either left or right). However, this approach is erroneous because it doesn’t check whether a node violates any condition with its grandparent or any of its ancestors. # So, we should keep track of the minimum and maximum values a node can take. And at each node we will check whether its value is between the min and max values it’s allowed to take. The root can take any value between negative infinity and positive infinity. At any node, its left child should be smaller than or equal than its own value, and similarly the right child should be larger than or equal to. So during recursion, we send the current value as the new max to our left child and send the min as it is without changing. And to the right child, we send the current value as the new min and send the max without changing. class Node: def __init__(self, val=None): self.left, self.right, self.val = None, None, val INFINITY = float("infinity") NEG_INFINITY = float("-infinity") def isBST(tree, minVal=NEG_INFINITY, maxVal=INFINITY): if tree is None: return True if not minVal <= tree.val <= maxVal: return False return isBST(tree.left, minVal, tree.val) and isBST(tree.right, tree.val, maxVal) # There’s an equally good alternative solution. If a tree is a binary search tree, then traversing the tree inorder should lead to sorted order of the values in the tree. So, we can perform an inorder traversal and check whether the node values are sorted or not. def isBST2(tree, lastNode=[NEG_INFINITY]): if tree is None: return True if not isBST2(tree.left, lastNode): return False if tree.val < lastNode[0]: return False lastNode[0]=tree.val return isBST2(tree.right, lastNode) # This is a common interview problem, its relatively simple, but not trivial and shows that someone has a knowledge of binary search trees and tree traversals.
true
0d349d0708bdb56ce5da09f585eaf41d8f9952c3
yosef8234/test
/python_essential_q/q8.py
2,234
4.6875
5
# Question 8 What does this stuff mean: *args, **kwargs? And why would we use it? # Answer # Use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we dont know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise. # Here is a little illustration: def f(*args,**kwargs): print(args, kwargs) l = [1,2,3] t = (4,5,6) d = {'a':7,'b':8,'c':9} f() f(1,2,3) # (1, 2, 3) {} f(1,2,3,"groovy") # (1, 2, 3, 'groovy') {} f(a=1,b=2,c=3) # () {'a': 1, 'c': 3, 'b': 2} f(a=1,b=2,c=3,zzz="hi") # () {'a': 1, 'c': 3, 'b': 2, 'zzz': 'hi'} f(1,2,3,a=1,b=2,c=3) # (1, 2, 3) {'a': 1, 'c': 3, 'b': 2} f(*l,**d) # (1, 2, 3) {'a': 7, 'c': 9, 'b': 8} f(*t,**d) # (4, 5, 6) {'a': 7, 'c': 9, 'b': 8} f(1,2,*t) # (1, 2, 4, 5, 6) {} f(q="winning",**d) # () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} f(1,2,*t,q="winning",**d) # (1, 2, 4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} def f2(arg1,arg2,*args,**kwargs): print(arg1,arg2, args, kwargs) f2(1,2,3) # 1 2 (3,) {} f2(1,2,3,"groovy") # 1 2 (3, 'groovy') {} f2(arg1=1,arg2=2,c=3) # 1 2 () {'c': 3} f2(arg1=1,arg2=2,c=3,zzz="hi") # 1 2 () {'c': 3, 'zzz': 'hi'} f2(1,2,3,a=1,b=2,c=3) # 1 2 (3,) {'a': 1, 'c': 3, 'b': 2} f2(*l,**d) # 1 2 (3,) {'a': 7, 'c': 9, 'b': 8} f2(*t,**d) # 4 5 (6,) {'a': 7, 'c': 9, 'b': 8} f2(1,2,*t) # 1 2 (4, 5, 6) {} f2(1,1,q="winning",**d) # 1 1 () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} f2(1,2,*t,q="winning",**d) # 1 2 (4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} # Why do we care? # Sometimes we will need to pass an unknown number of arguments or keyword arguments into a function. Sometimes we will want to store arguments or keyword arguments for later use. Sometimes it's just a time saver.
true
ec8296cf056afef1f3ad97123c852b66f25d75cb
yosef8234/test
/pfadsai/04-linked-lists/notes/singly-linked-list-implementation.py
1,136
4.46875
4
# Singly Linked List Implementation # In this lecture we will implement a basic Singly Linked List. # Remember, in a singly linked list, we have an ordered list of items as individual Nodes that have pointers to other Nodes. class Node(object): def __init__(self,value): self.value = value self.nextnode = None # Now we can build out Linked List with the collection of nodes: a = Node(1) b = Node(2) c = Node(3) a.nextnode = b b.nextnode = c # In a Linked List the first node is called the head and the last node is called the tail. Let's discuss the pros and cons of Linked Lists: # Pros # Linked Lists have constant-time insertions and deletions in any position, in comparison, arrays require O(n) time to do the same thing. # Linked lists can continue to expand without having to specify their size ahead of time (remember our lectures on Array sizing form the Array Sequence section of the course!) # Cons # To access an element in a linked list, you need to take O(k) time to go from the head of the list to the kth element. In contrast, arrays have constant time operations to access elements in an array.
true
09da1340b227103c7eb1bc9800c714907939bfde
yosef8234/test
/python_ctci/q1.4_permutation_of_palindrom.py
1,097
4.21875
4
# Write a function to check if a string is a permutation of a palindrome. # Permutation it is "abc" == "cba" # Palindrome it is "Madam, I'm Adam' # A palindrome is word or phrase that is the same backwards as it is forwards. (Not limited to dictionary words) # A permutation is a rearrangement of letters. import string def isPermutationOfPalindrome(str): # {'a': False, 'c': False, 'b': False, 'e': False, 'd': False, 'g': False, 'f': False, 'i': False, 'h': False, 'k': False, 'j': False, 'm': False, 'l': False, 'o': False, 'n': False, 'q': False, 'p': False, 's': False, 'r': False, 'u': False, 't': False, 'w': False, 'v': False, 'y': False, 'x': False, 'z': False} d = dict.fromkeys(string.ascii_lowercase, False) count = 0 for char in str: if(ord(char) > 96 and ord(char) < 123): d[char] = not d[char] for key in d: if d[key] is True: count += 1 if count > 1: return False return True print(isPermutationOfPalindrome("abcecba")) # True print(isPermutationOfPalindrome("aa bb cc eee f")) # False
true
c117f5f321a25493ee9c3811a51e6c28d6487392
imjching/playground
/python/practice_python/11_check_primality_functions.py
730
4.21875
4
# http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html """ Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to [Exercise 4](/exercise/2014/02/26/04-divisors.html to help you. Take this opportunity to practice using functions, described below. """ number = int(raw_input("Please enter a number: ")) def is_prime(number): if number < 2: return False for i in range(2, (number / 2) + 1): if number % i == 0: return False return True if is_prime(number): print "This is a prime number!" else: print "This is not a prime number"
true
8f13963a5059a9cbb14790645f86ff0415398108
imjching/playground
/python/practice_python/14_list_remove_duplicates.py
764
4.1875
4
# http://www.practicepython.org/exercise/2014/05/15/14-list-remove-duplicates.html """ Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and write the solution for that in a different function. """ from sets import Set def unique_elements_loop(_list): new_list = [] for i in _list: if i not in new_list: new_list.append(i) return new_list def unique_elements_sets(_list): return list(Set(_list)) print unique_elements_loop([1, 2, 3, 3, 3, 3]) print unique_elements_sets([1, 2, 3, 3, 3, 3])
true
35c0ab9c2e6bfb4eea6f3750b208495ce1407d03
imjching/playground
/python/practice_python/18_cows_and_bulls.py
1,813
4.21875
4
# http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html """ Create a program that will play the 'cows and bulls' game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a 'cow'. For every digit the user guessed correctly in the wrong place is a 'bull'. Every time the user makes a guess, tell them how many 'cows' and 'bulls' they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout the game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull ... Until the user guesses the number. """ from random import randint print "Welcome to the Cows and Bulls Game!" number = "".join(["1234567890"[randint(0, 9)] for i in range(4)]) print number def check(input_, number): cows = 0 bulls = 0 for i in range(len(number)): if input_[i] == number[i]: cows += 1 elif input_[i] in number: # something doesn't seem right bulls += 1 if cows == 4: return "0" else: res = str(cows) + " cow, " if cows <= 1 else str(cows) + " cows, " res += str(bulls) + " bull" if bulls <= 1 else str(bulls) + " bulls" return res trials = 0 while True: trials += 1 input_ = raw_input("Enter a number: ") if len(input_) != 4: print "Please enter a 4 digit number." else: result = check(input_, number) if result == "0": print "You have guessed the number with a total of " + str(trials) + " guesses!" break else: print result
true
53937a32b059e4e9613be47b492f586eff09a06d
bkhuong/LeetCode-Python
/make_itinerary.py
810
4.125
4
class Solution: ''' Given a list of tickets, find itinerary in order using the given list. ''' def find_route(tickets:list) -> str: routes = {} start = [] # create map for ticket in tickets: routes[ticket[0]] = {'to':ticket[1]} try: routes[ticket[1]].update({'from':ticket[0]}) except: routes[ticket[1]] = {'from':ticket[0]} # find starting point for k,v in routes.items(): if 'from' not in v.keys(): departure = k break # walk dictionary for route: while 'to' in routes[departure].keys(): print(f'{departure} -> {routes[departure]["to"]}') departure = routes[departure]['to']
true
70cc3581b224daa3beadfc0150d31b52c30f6284
Gachiman/Python-Course
/python-scripts/hackerrank/Medium/Find Angle MBC.py
603
4.21875
4
import math def input_length_side(val): while True: try: length = int(float(input("Enter the length of side {0} (0 < {0} <= 100): ".format(val)))) if 0 < length <= 100: return length else: raise ValueError except ValueError: print("Please reinsert") def main(): side_ab = input_length_side("AB") side_bc = input_length_side("BC") tg_mbc = side_ab / side_bc angle_mbc = math.degrees(math.atan(tg_mbc)) print(round(angle_mbc), '°', sep='') if __name__ == '__main__': main()
true
a1b6391a773b23a0f5fe8e0b0a4d36bc7e03b9b0
hobsond/Computer-Architecture
/white.py
1,788
4.625
5
# Given the following array of values, print out all the elements in reverse order, with each element on a new line. # For example, given the list # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # Your output should be # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process. originalList = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] reverseList = originalList[::-1] for i in reverseList: print(i) # Given a hashmap where the keys are integers, print out all of the values of the hashmap in reverse order, ordered by the keys. # For example, given the following hashmap: # { # 14: "vs code", # 3: "window", # 9: "alloc", # 26: "views", # 4: "bottle", # 15: "inbox", # 79: "widescreen", # 16: "coffee", # 19: "tissue", # } # The expected output is: # widescreen # views # tissue # coffee # inbox # vs code # alloc # bottle # window # since "widescreen" has the largest integer key, "views" has the second largest, etc. # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process. # hash map key = { 14: "vs code", 3: "window", 9: "alloc", 26: "views", 4: "bottle", 15: "inbox", 79: "widescreen", 16: "coffee", 19: "tissue", } # loop through key get the key.items() # which im gonna sort by the first value # then loop through and print newList = sorted([i for i in key.items()],reverse=True) # newList.sort(key = lambda e:e[0]) # newList.reverse() for i in newList: print(i[1])
true
2718e25886a29226c5050afe0d83c6459bd6747b
Twest19/prg105
/Ch 10 HW/10-1_person_data.py
1,659
4.71875
5
""" Design a class that holds the following personal data: name, address, age, and phone number. Write appropriate accessor and mutator methods (get and set). Write a program that creates three instances of the class. One instance should hold your information and the other two should hold your friends' or family members' information. Just add information, don't get it from the user. Print the data from each object, make sure to format the output for clarity and ease of reading. """ class Data: # This class takes the data for a person and returns that data def __init__(self, name, address, age, phone='n/a'): self.name = name self.address = address self.age = age self.phone = phone def set_name(self, name): self.name = name def get_name(self): return self.name def set_address(self, address): self.address = address def get_address(self): return self.address def set_age(self, age): self.age = int(age) def get_age(self): return self.age def set_phone(self, phone): self.phone = phone def get_phone(self): return self.phone def __str__(self): return f"Name: {self.name}\nAddress: {self.address}\nAge: {self.age}\nPhone: {self.phone}\n" def main(): my_data = Data('Tim', '119 W South Ave', 21, '815-354-7216') friend_data = Data('Saul', '9800 Montgomery Blvd', 49, '505-503-4455') family_data = Data('Tom', '191 E North Ave', 42) print(my_data) print(friend_data) print(family_data) main()
true
b33b65d4b831bcd41fac9f4cd424a65dc4589d39
Twest19/prg105
/3-3_ticket.py
2,964
4.3125
4
""" You are writing a program to sell tickets to the school play. If the person buying the tickets is a student, their price is $5.00 per ticket. If the person buying the tickets is a veteran, their price is $7.00 per ticket. If the person buying the ticket is a sponsor of the play, the price is $2.00 per ticket. """ # Must initialize price and discount to later assign them a new value price = 0 discount = 0 print(f"{'=' * 6} Play Ticket Types w/ Prices {'=' * 6}" "\n(1) Student - $6.00" "\n(2) Veteran - $7.00" "\n(3) Show Sponsor - $2.00" "\n(4) Retiree - $6.00" "\n(5) General Public - $10.00") print(f"{'=' * 36}") # Ask the buyer which ticket group they fall into # Choose a number 1-5 or it will display an error and prompt them until they provide a proper response while True: prompt = input("\nPlease choose a number for the corresponding ticket type that you fall into: ") if prompt in ('1', '2', '3', '4', '5'): ticket_type = int(prompt) # Assign the ticket to a price for the number chosen by the buyer if ticket_type == 1: price = 6.00 print("\nYou have selected Student.") elif ticket_type == 2: price = 7.00 print("\nYou have selected Veteran.") elif ticket_type == 3: price = 2.00 print("\nYou have selected Show Sponsor.") elif ticket_type == 4: price = 6.00 print("\nYou have selected Retiree.") elif ticket_type == 5: price = 10.00 print("\nYou have selected General Public.") break else: print("\nError please try again") # Let the buyer know that they can receive a discount when they buy more tickets print("\nIf you buy 4 - 8 tickets you get a 10% discount.") print("If you buy 9 - 15 tickets you get a 15% discount.") print("If you buy more than 15 tickets you get a 20% discount.") # Ask buyer how many tickets they would like to purchase ticket_quantity = int(input("\nHow many tickets would you like to buy? ")) # Get the total price before any discounts are applied if there are any ticket_total = price * ticket_quantity # Determine if the buyer has met the requirements for a discount if ticket_quantity > 15: print("\nYou get a 20% discount!") discount = ticket_total * .20 elif ticket_quantity >= 9: print("\nYou get a 15% discount!") discount = ticket_total * .15 elif ticket_quantity >= 4: print("\nYou get a 10% discount") discount = ticket_total * .10 else: print("\nSorry, you do not get a discount.") # Calculate the price by applying the discount discount_applied = ticket_total - discount # Calculate average price paid avg = discount_applied / ticket_quantity # Display the total before and after discount with how much they saved print(f"\nTotal before discount: ${ticket_total:.2f}") print(f"You saved: ${discount:.2f} ") print(f"Your price per ticket is: ${avg:.2f}") print(f"Total after discount: ${discount_applied:.2f}")
true
20a0d53d34ba73884e14d026030289475bb6275e
Twest19/prg105
/chapter_practice/ch_9_exercises.py
2,681
4.4375
4
""" Complete all of the TODO directions The number next to the TODO represents the chapter and section in your textbook that explain the required code Your file should compile error free Submit your completed file """ import pickle # TODO 9.1 Dictionaries print("=" * 10, "Section 9.1 dictionaries", "=" * 10) # 1) Finish creating the following dictionary by adding three more people and birthdays birthdays = {'Meri': 'May 16', 'Kathy': 'July 14'} birthdays['Tim'] = 'Jan 19' birthdays['Jane'] = 'Jun 30' birthdays['Harold'] = 'Oct 19' # 2) Print Meri's Birthday print(birthdays['Meri']) # 3) Create an empty dictionary named registration registration = {} # You will use the following dictionary for many of the remaining exercises" miles_ridden = {'June 1': 25, 'June 2': 20, 'June 3': 38, 'June 4': 12, 'June 5': 30, 'June 7': 25} # 1) Print the keys and the values of miles_ridden using a for loop for k, v in miles_ridden.items(): print(k, v) # 2) Get the value for June 3 and print it, if not found display 'Entry not found', replace the "" value = miles_ridden['June 3'] print(value) # 3) Get the value for June 6 and print it, if not found display 'Entry not found' replace the "" if 'June 6' in miles_ridden: value2 = miles_ridden['June 6'] else: value2 = 'Entry not found' print(value2) # 4) Use the values method to print the miles_ridden dictionary print(miles_ridden.values()) # 5) Use the keys method to print all of the keys in miles_ridden print(miles_ridden.keys()) # 6) Use the pop method to remove June 4 then print the contents of the dictionary miles_ridden.pop('June 4') print(miles_ridden) # 7) Use the items method to print the contents of the miles_ridden dictionary print(miles_ridden.items()) # TODO 9.2 Sets print("=" * 10, "Section 9.2 sets", "=" * 10) # 1) Create an empty set named my_set my_set = set() # 2) Create a set named days that contains the days of the week days = {'Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'} # 3) Get the number of elements from the days set and print it print(len(days)) # 4) Remove Saturday and Sunday from the days set days.remove('Sun') days.remove('Sat') print(days) # 5) Determine if 'Mon' is in the days set if 'Mon' in days: print('Mon') # TODO 9.3 Serializing Objects (Pickling) print("=" * 10, "Section 9.3 serializing objects using the pickle library", "=" * 10) # 1) Import the pickle library at the top of this file # 2) Create the output file log and open it for binary writing output = open('log.dat', 'wb') # 3) Pickle the miles_ridden dictionary and output it to the log file pickle.dump(miles_ridden, output) # 4) Close the log file output.close()
true
666efab8a625d46543dab413aadd15936594a5dd
Twest19/prg105
/4-1_sales.py
862
4.5625
5
""" You need to create a program that will have the user enter in the total sales amount for the day at a coffee shop. The program should ask the user for the total amount of sales and include the day in the request. At the end of data entry, tell the user the total sales for the week, and the average sales per day. You must create a list of the days of the week for the user to step through, see the example output. """ days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] weekly_total = 0 print("Sales for the week:") for day in days: sales = float(input(f"What was the total amount of sales on {day}? ")) weekly_total += sales print(f"\nThe total amount of sales for the week was: ${weekly_total:,.2f}") print(F"The average amount of sales per day was: ${weekly_total / 7:,.2f}")
true
a3ace412c840aac7ff86999020c0d765a5062a5d
Twest19/prg105
/5-3_assessment.py
2,467
4.21875
4
""" You are going to write a program that finds the area of a shape for the user. """ # set PI as a constant to be used as a global value PI = 3.14 # create a main function then from the main function call other functions to get the correct calculations def main(): while True: menu() choice = int(input("Enter the number of your selection: ")) num = validate(choice) if num == 1: base = int(input("Enter the base of the rectangle in cm: ")) height = int(input("Enter the height of the rectangle in cm: ")) area = rectangle(base, height) print(f"The area of the rectangle is {area:.2f} square cm.") elif num == 2: base = int(input("Enter the base of the triangle in cm: ")) height = int(input("Enter the height of the triangle in cm: ")) area = triangle(base, height) print(f"The area of the triangle is {area:.2f} square cm.") elif num == 3: side = int(input("Enter the length of one side of the square in cm: ")) area = square(side) print(f"The area of the square is {area:.2f} square cm.") elif num == 4: radius = int(input("Enter the radius of the circle: ")) area = circle(radius) print(f"The area of the circle is {area:.2f} square cm.") # menu function displays the options available to the user def menu(): print("\nThis program will find the area of any of the shapes below.") print("1. Rectangle\n" "2. Triangle\n" "3. Square\n" "4. Circle\n" "5. Quit\n") # The validate function confirms the users input if the users provides a correct response def validate(x): while True: if 1 <= x < 5: return x elif x == 5: print("\nGoodbye!") exit() else: print("\nError, please try again.\n") x = int(input("Enter the number of your selection: ")) continue # Create a function for each of the shapes to calculate the area for the corresponding shape def rectangle(x, y): area = x * y return area def triangle(x, y): area = x * y * 1/2 return area def square(x): area = x**2 return area def circle(r): global PI area = PI * r**2 return area main()
true
52dd577610c57f96e36b41ee06982c873f0d55af
dougiejim/Automate-the-boring-stuff
/commaCode.py
753
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Write a function that takes a list value as an argument and returns #a string with all the items separated by a comma and a space, with #and inserted before the last item. For example, passing the previous #spam list to the function would return 'apples, bananas, tofu, and cats'. #But your function should be able to work with any list value passed to it. """ Created on Sat Jan 20 15:53:15 2018 @author: coledoug """ spam = ['apples', 'bananas', 'tofu', 'cats'] newString = '' def stringReturn(list): newString = '' for i in list: if i != list[-1]: return newString + str(i +', ') else: return newString + str(' and '+ i) stringReturn(spam)
true
732a68dc8a28c98ecc93001de996919759778a2c
sakamoto-michael/Sample-Python
/new/intro_loops.py
727
4.28125
4
# Python Loops and Iterations nums = [1, 2, 3, 4, 5] # Looping through each value in a list for num in nums: print(num) # Finding a value in a list, breaking upon condition for num in nums: if num == 3: print('Found!') break print(num) # Finding a value, the continuing execution for num in nums: if num == 3: print('Found') continue print(num) # Loops within loops for num in nums: for letter in 'abc': print(num, letter) # Iterations - range(starting point, end point) for i in range(1, 11): print(i) # While loop - must include a breaking condition. Can also included manual break within loop upon a different condition x = 0 while x < 10: if x == 5: break print(x) x += 1
true
701ea9976f04c66564962c3bc7f64d89e1314120
vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews
/Python/BinaryTree/NumberOfNonLeafNodes.py
1,524
4.3125
4
# @author # Aakash Verma # Output: # Pre Order Traversal is: 1 2 4 5 3 6 7 # Number Of non-Leaf Nodes: 3 # Creating a structure for the node. # Initializing the node's data upon calling its constructor. class Node: def __init__(self, data): self.data = data self.right = self.left = None # Defining class for the Binary Tree class NumberOfNonLeafNodes: # Assigning root as null initially. So as soon as the object will be created # of this NumberOfNonLeafNodes class, root will be set as null. def __init__(self): self.root = None # Pre Order Traversal def preOrder(self, root): if root is None: return print(root.data, end = " ") self.preOrder(root.left) self.preOrder(root.right) def numNonLeafNodes(self, root): if root is None: return 0 if root.left is None and root.right is None: return 0; return 1 + self.numNonLeafNodes(root.left) + self.numNonLeafNodes(root.right) # main method if __name__ == '__main__': tree = NumberOfNonLeafNodes() tree.root = Node(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) print("Pre Order Traversal is:", end = " ") tree.preOrder(tree.root) print() print("Number Of non-Leaf Nodes:", end = " ") print(tree.numNonLeafNodes(tree.root))
true
8878c006639c546777ff2af254a979033560c15a
vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews
/Python/LinkedList/StartingOfLoop.py
1,519
4.34375
4
# # # # @author # Aakash Verma # # Start of a loop in Linked List # # Output: # 5 # # Below is the structute of a node which is used to create a new node every time. class Node: def __init__(self, data): self.data = data self.next = None # None is nothing but null # Creating a class for implementing the code for Starting Of a loop in a LinkedList class LinkedList: # Whenever I'll create the object of a LinkedList class head will be pointing to null initially def __init__(self): self.head = None # Inserting at the end of a Linked List (append function) def append(self, key): h = self.head if h is None: new_node = Node(key) self.head = new_node else: while h.next != None: h = h.next new_node = Node(key) h.next = new_node # middle of a linked list def startingOfLoop(self): fast = self.head slow = self.head isLoopFound = False if self.head is None: print("The list doesn't exist.") return while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow == fast: isLoopFound = True break if isLoopFound is True: slow = self.head while slow != fast: slow = slow.next fast = fast.next print(slow.data) # Code execution starts here if __name__=='__main__': myList = LinkedList() myList.append(3) myList.append(4) myList.append(5) myList.append(6) myList.append(7) myList.head.next.next.next.next.next = myList.head.next.next myList.startingOfLoop()
true
96ca87b2c6191ffd17b5571581f5dec816529ef2
SgtHouston/python102
/sum the numbers.py
249
4.21875
4
# Make a list of numbers to sum numbers = [1, 2, 3, 4, 5, 6] # set up empty total so we can add to it total = 0 # add current number to total for each number iun the list for number in numbers: total += number # print the total print(total)
true
25ceca21258ebec39c3bb51f308a1e5f136aaca4
urmajesty/learning-python
/ex5.py
581
4.15625
4
name = 'Zed A Shaw' age = 35.0 # not a lie height = 74.0 # inches weight = 180.0 #lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print(f"Let's talk about {name}.") print(f"He's {height} pounds heavy.") print("Actually that's not too heavy.") print(f"He's got {eyes} eyes and {hair} hair.") print(f"His teeth are usually {teeth} depending on the coffee.") total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.") #study drill #2 cm = (height * 2.54) print(f"He also is {cm} cm tall.") kg = (weight * .453592) print(f"And He weighs {kg} kg.")
true
53c52d5fb29d5f8f28c56ead8f8c31dfd6f06d98
antoinemadec/test
/python/codewars/simplifying/simplifying.py
2,602
4.5
4
#!/usr/bin/env python3 ''' You are given a list/array of example formulas such as: [ "a + a = b", "b - d = c ", "a + b = d" ] Use this information to solve a formula in terms of the remaining symbol such as: "c + a + b" = ? in this example: "c + a + b" = "2a" Notes: Variables names are case sensitive There might be whitespaces between the different characters. Or not... There should be support for parenthesis and their coefficient. Example: a + 3 (6b - c). You might encounter several imbricated levels of parenthesis but you'll never get a variable as coefficient for parenthesis, only constant terms. All equations will be linear See the sample tests for clarification of what exactly the input/ouput formatting should be. Without giving away too many hints, the idea is to substitute the examples into the formula and reduce the resulting equation to one unique term. Look carefully at the example tests: you'll have to identify the pattern used to replace variables in the formula/other equations. Only one solution is possible for each test, using this pattern, so if you keep asking yourself "but what if I do that instead of...", that is you missed the thing. ''' import re def simplify(examples,formula): d,letters = {},[] examples = [re.sub('([0-9]+) *([(a-zA-Z])',r'\1*\2',e) for e in examples] for e in examples: m = re.match('(?P<expr>.*) += +(?P<var>\w+)',e) d[m.group('var')] = m.group('expr') letters.extend([c for c in e if c.isalpha()]) c = [c for c in letters if c not in d][0] d[c] = '1' for _ in range(1000): formula = re.sub('([0-9]+) *([(a-zA-Z])',r'\1*\2',formula) for k in d: formula = formula.replace(k,'(' + d[k] + ')') try: r = eval(formula) except: continue return "%d%c" % (r,c) examples=[["a + a = b", "b - d = c", "a + b = d"], ["a + 3g = k", "-70a = g"], ["-j -j -j + j = b"]] formula=["c + a + b", "-k + a", "-j - b" ] answer=["2a", "210a", "1j" ] for i in range(len(answer)): print('examples:' + str(examples[i])) print('formula:' + str(formula[i])) print('expected answer:'+str(answer[i])) print(simplify(examples[i],formula[i])) examples=['y + 6Y - k - 6 K = f', ' F + k + Y - y = K', 'Y = k', 'y = Y', 'y + Y = F'] formula='k - f + y' print('expected answer:14y') print(simplify(examples,formula)) examples=['x = b', 'b = c', 'c = d', 'd = e'] formula='c' print('expected answer:1x') print(simplify(examples,formula))
true
1d5eba8fd2834bb2375016ec7ed9e8cc686f1991
antoinemadec/test
/python/programming_exercises/q5/q5.py
662
4.21875
4
#!/usr/bin/env python3 print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt Question: Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. Answer:""") class String: def __init__(self): self.string = "" def getString(self): self.string = input("Enter string: ") def printString(self): print(self.string.upper()) s = String(); s.getString() s.printString()
true
7f17dd1d0b9acc663a17846d838cbd79998bb79b
antoinemadec/test
/python/programming_exercises/q6/q6.py
840
4.21875
4
#!/usr/bin/env python3 print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Answer:""") C = 50 H = 30 Q = [] for D in input("Enter numbers separated by comma: ").split(','): D = int(D) Q.append(int(((2*C*D)/H) ** 0.5)) print(','.join([str(i) for i in Q]))
true
d057707ccd873e895d2caf5eec45a19e0473da84
antoinemadec/test
/python/codewars/find_the_divisors/find_the_divisors.py
708
4.3125
4
#!/usr/bin/env python3 """ Create a function named divisors/Divisors that takes an integer and returns an array with all of the integer's divisors(except for 1 and the number itself). If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust). Example: divisors(12); #should return [2,3,4,6] divisors(25); #should return [5] divisors(13); #should return "13 is prime" You can assume that you will only get positive integers as inputs. """ def divisors(i): r = [x for x in range(2,i) if (i//x)*x == i] if r: return r else: return "%0d is prime" % i print(divisors(12)) print(divisors(13))
true
81cc9b7d03933d990e1a90129929d1eb78ffb108
antoinemadec/test
/python/cs_dojo/find_mult_in_list/find_mult_in_list.py
526
4.1875
4
#!/bin/env python3 def find_multiple(int_list, multiple): sorted_list = sorted(int_list) n = len(sorted_list) for i in range(0,n): for j in range(i+1,n): x = sorted_list[i] y = sorted_list[j] if x*y == multiple: return (x,y) elif x>multiple: return None return None # execution l = [int(x) for x in input("Enter list (white space separated): ").split(" ")] m = int(input("Enter multiple: ")) print(find_multiple(l,m))
true