blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
44af3cdf5cfa08251a39f70b645735fbe48b71ea
paola-rodrigues/Lista_Python_02
/questão_07.py
457
4.125
4
# Questão 7 primeiro_numero = float(input("Digite o primeiro número: ")) segundo_numero = float(input("Digite o segundo número: ")) if primeiro_numero > segundo_numero: numero = "O maior número é " + str(primeiro_numero) elif segundo_numero > primeiro_numero: numero = "O maior número é " + str(segundo_numero) elif primeiro_numero == segundo_numero: numero = "Números iguais" print(f"{numero}")
false
0b0b389ea15db8ef6e2c30bf3bec7055bbf2d092
emilycheera/coding-challenges
/string-shifts.py
818
4.125
4
"""You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: - direction can be 0 (for left shift) or 1 (for right shift). - amount is the amount by which string s is to be shifted. A left shift by 1 means remove the first character of s and append it to the end. Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. Return the final string after all operations.""" def stringShift(s, shift): chars = [char for char in s] for direction, amount in shift: if direction == 0: for _ in range(amount): chars.append(chars.pop(0)) else: for _ in range(amount): chars.insert(0, chars.pop()) return "".join(chars)
true
ba6c9e29e63b156a437888eef90a82d6ac222387
emilycheera/coding-challenges
/encipher-string.py
1,115
4.34375
4
"""Write a function that encrypts a string with a variable rotary cipher. The function should take in a number and string and shift the string's characters by that number: >>> rot_encode(1, 'abcxyz') 'bcdyza' It should be able to shift characters by any number: >>> rot_encode(3, 'abcxyz') 'defabc' It should preserve capitalization, whitespace, and any special characters: >>> rot_encode(1, 'Wow! This is 100% amazing.') 'Xpx! Uijt jt 100% bnbajoh.' """ def rot_encode(shift, txt): """Encode `txt` by shifting its characters to the right.""" chars = list(txt) for i in range(len(chars)): char_val = ord(chars[i]) if 65 <= char_val <= 90 or 97 <= char_val <= 122: new_char_val = char_val + (shift % 26) if (char_val <= 90 and new_char_val > 90) or ( char_val <= 122 and new_char_val > 122 ): new_char_val -= 26 chars[i] = chr(new_char_val) return "".join(chars) if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print("\n✨ ALL TESTS PASSED!\n")
true
50f1e107ffa96ab32383d27f54863a631ae7abe0
emilycheera/coding-challenges
/frequency_sort.py
433
4.15625
4
from collections import Counter def frequency_sort(s): """Sort string in decreasing order based on the frequency of characters.""" char_counts = Counter(s) counts = sorted(set(char_counts.values()), reverse=True) result = "" for count in counts: for char in char_counts: if char_counts[char] == count: result += (char * count) return result
true
a98ee7c6bf3deb49705292e9a6b82ebe62107c10
BackToTheSchool/assignment_js
/1113/hw32.py
1,172
4.125
4
import random level = int(input("Input the level : ")) if level == 1 : answer = int(random.randrange(1,11)) guess = int(input("What is your guess? ")) while answer != guess : if(answer < guess ): guess = int(input("That's too high\nWhat is your guess? ")) elif(answer > guess): guess = int(input("That's too low\nWhat is your guess? ")) elif level == 2 : answer = int(random.randrange(1, 101)) guess = int(input("What is your guess? ")) while answer != guess: if (answer < guess): guess = int(input("That's too high\nWhat is your guess? ")) elif (answer > guess): guess = int(input("That's too low\nWhat is your guess? ")) elif level == 3 : answer = int(random.randrange(1, 1001)) guess = int(input("What is your guess? ")) while answer != guess: if (answer < guess): guess = int(input("That's too high\nWhat is your guess? ")) elif (answer > guess): guess = int(input("That's too low\nWhat is your guess? ")) if answer == guess: print("You are correct")
false
c4a09d5be778027019d93b95b5d3495393817ab5
lilyhe19/final_project
/archive/final_project_master/sleepcal.py
1,724
4.75
5
def sleep(): ''' This function puts out the recommended number of hours of sleep per night according to the guidelines set by The National Sleep Foundation. The output is formatted as a range of hours, as there is no perfect formula for determining how much sleep one should get, and these numbers are simply recommendations based on the newest sleep research. You can type in your/your child's age, and the function will give you a recommendation based on your input. This function does not give reliable recommendations for children under 1 year old. ''' print("\n This program returns the recommended number of hours of sleep per night \ \n according to the age-based guidelines set by The National Sleep Foundation. \ \n Note: this calculator may not be accurate for infants and very young children (under the age of 1).") master= [{'age':[1,2],'hours':"11-14"},{'age':[3,4,5],'hours':"10-13"},{'age':[6,7,8,9,10,11,12,13],'hours':"9-11"},{'age':[14,15,16,17],'hours':"8-10"}] number = int(input("Please enter an age (between 1-17 years): ")) for x in master: if number in x['age']: print("Your child should sleep " + str(x['hours']) + " hours." ) #if __name__ == "__main__": #print("\n This program returns the recommended number of hours of sleep per night \ #\n according to the age-based guidelines set by The National Sleep Foundation. \ #\n Note: this calculator may not be accurate for infants and very young children (under the age of 1).") #number = int(input("Please enter in an age (between 1-17 years): ")) #final_answer = sleep(number) #print("Your child should sleep " + str(final_answer) + " hours.")
true
cec2b80f83885c94610442607a09f009cd192ac9
lilyhe19/final_project
/archive/caltesting.py
2,343
4.40625
4
def calorie_intake(): #calculates the number calories one should intake #using Harris Benedict BMR equation print("This program will calculate number of calories you should consume per day.") print("Please note this calculator may not be accurate for infants and young children.") #while gender != "male" or gender != "female": #gender= input("Error, please type in gender again") # weight= float(input("How much do you weigh in pounds?>> ")) # height= float(input("How tall are you in inches?>> ")) # age= float(input("How many years old are you?>> ")) # gender = input("Please type in gender: ") # answer = 0 gender = input("Is your birth gender male or female?>> ") while gender != "male" and gender != "female": gender= input("Error, please type in gender again") weight= float(input("How much do you weigh? (pounds) >> ")) height= float(input("How tall are you? (inches) >> ")) age = float(input("How old are you? (years) >> ")) if gender == "male": x_male= 66+6.2*(weight)+12.7*(height)-6.76*(age) answer = x_male else: x_female= 655.1+4.35*(weight)+4.7*(height)-4.7*(age) answer = x_female # while True: #use "is not" to compare strings # #print(gender) # gender = input("Error, please type in gender again") # if gender != "male" or "female": # print(gender) # print(gender=="male") # gender='' # elif gender== "male": # x_male= 66+6.2*(weight)+12.7*(height)-6.76*(age) # answer = x_male # #x_male is number of calories a male should consume # elif gender== "female": # x_female= 655.1+4.35*(weight)+4.7*(height)-4.7*(age) # answer = x_female #while loop not working, can tell that the gender input is correct, still prints error message #x_female is the number of calories a female should consume #return int(answer) #need to fix error checking for male, in the case that gender is inputted incorrectly print ("You should consume " + str(answer) + " calories daily") '''if __name__=="__main__": print("This program will calculate number of calories you should consume per day.") print("Please note this calculator may not be accurate for infants and young children.") gender= input("Are you male or female?>> ") final_answer = calorie_intake(gender, weight, height, age) print ("You should consume " + str(final_answer) + " calories daily")'''
true
5eab521975bd6e77a387022e3cbb871b009727eb
crakama/UdacityIntrotoComputerScience
/product_list.py
297
4.125
4
# Define a procedure, product_list, # takes as input a list of numbers, # and returns a number that is # the result of multiplying all # those numbers together. def product_list(lst): mult = 1 for i in lst: mult = mult * i print mult num = [1, 2, 3, 4] product_list(num)
true
cde6bfc55241b4f55da0b9e567c86d655db8473b
crakama/UdacityIntrotoComputerScience
/sumlist.py
617
4.125
4
# Define a procedure, replace_spy, # that takes as its input a list of # three numbers, and modifies the # value of the third element in the # input list to be one more than its # previous value. spy = [0,0,7] def replace_spy(p): # this takes one parameter as its input, called p p[2] = p[2] + 1 replace_spy(spy) print spy #>>> [0,0,8] # Define a procedure, sum_list, # that takes as its input a # list of numbers, and returns # the sum of all the elements in # the input list. def sum_list(p): result = 0 for e in p: result = result + e return result print sum_list([1, 4, 7])
true
32608d913f6d92d66454ec9a8708591b8cda5978
R-Rayburn/PythonCookbook
/01_data_structures_and_algorithms/06_mapping_dict_keys_to_multiple_values.py
1,824
4.3125
4
# Problem # Need a dictionary that maps keys ot more than one value (multidict) # Solution # To store multiple values with a single key, a container such as a # list or set should be used. d = { 'a': [1, 2, 3], 'b': [4, 5] } e = { 'a': {1, 2, 3}, 'b': {4, 5} } # Lists are useful when wanting to maintain insertion order, # sets are useful to eliminate duplicates. # These dictionaries can be created by using defaultdict in # the collections module. defaultdict automatically # initializes the first value so that the focus can be on # adding items to the dict. from collections import defaultdict d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['b'].append(4) d = defaultdict(set) d['a'].add(1) d['a'].add(2) d['b'].add(4) # defaultdict will automatically create dictionary entities for keys # accessed later on (even if those keys don't currently exist in # the dict). If this behavior isn't wanted, then the setdefault() # method for an ordinary dict can be used. d = {} d.setdefault('a', []).append(1) d.setdefault('a', []).append(2) d.setdefault('b', []).append(4) # Many find setdefault() to be unnatural, and it always creates # a new instance of the initial value on each invocation (the # empty list [] in the example above) # Discussion # Consturcting a multivalued dict is simple in principle, but # initializing the first value can be messy. d = {} pairs = [ ('a', 1), ('a', 2), ('b', 4) ] for key, value in pairs: if key not in d: d[key] = [] d[key].append(value) # Using defaultdict() simplifies the code d = defaultdict(list) for key, value in pairs: d[key].append(value) # This recipe is related to the problem with needing to group # records in data processing problems. 01.15 is an example of # this.
true
9db02f042c652252431f581a969ec93bdb0800a4
trevinwisaksana/Data-Structures
/source/string_search.py
2,826
4.375
4
#!python ''' Find the starting index of the first occurrence of a pattern in a string. ''' def find(string, pattern): return find_iterative(string, pattern) # return find_recursive(string, pattern) def find_iterative(string, pattern): # number of characters in the pattern array length_of_pattern = len(pattern) # index of the current character current_character = 0 # loops through each character for character in string: # character that will be compared with character_compared = pattern[current_character] # check if the current_character has compared all characters if character == character_compared: # increment after every character match current_character += 1 elif character != character_compared: # restart the current_character index count current_character = 0 # if the current_character count has been incremented enough times if current_character is length_of_pattern: return True return False def find_recursive(string, pattern): pass '''-----------------------------''' def find_index(string, pattern): return find_index_iterative(string, pattern) # return find_index_recursive(string, pattern) def find_index_iterative(string, pattern): # number of characters in the pattern array length_of_pattern = len(pattern) # index of the current character current_character = 0 # index count index_count = 0 # starting index pattern_starting_index = None # bool to check if the pattern_starting_index is captured captured = False # loops through each character for character in string: # index count index_count += 1 # character that will be compared with character_compared = pattern[current_character] # check if the current_character has compared all characters if character == character_compared: # increment after every character match current_character += 1 if captured is False: # retrieving the pattern starting index pattern_starting_index = index_count # stores the index captured = True elif character != character_compared: # restart the current_character index count current_character = 0 # if the current_character count has been incremented enough times if current_character is length_of_pattern: pattern_starting_index return None def find_index_recursive(string, pattern): pass '''-----------------------------''' # TODO: Stretch challenge def find_all_indexes(string, pattern): pass if __name__ == '__main__': print(find('Treeevin', 'evin'))
true
47e03bd72b09b6018c323ac4aa4f11a5abe1a4b4
Eamado18/Python-Challenge
/PyBank/main.py
2,274
4.125
4
import os import csv #Your task is to create a Python script that analyzes the records to calculate each of the following: Bank_csv = os.path.join('PyBank',"Resources","budget_data.csv") Date_rows = 0 Net_total = 0 Profit_Losses = [] Profit_Losses_change = [] Months = [] with open(Bank_csv) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) #The total number of months included in the dataset for row in csvreader: Date_rows = Date_rows + 1 #The net total amount of "Profit/Losses" over the entire period Net_total = Net_total + int(row[1]) #Calculate the changes in "Profit/Losses" over the entire period, then find the average of those changes Profit_Losses.append(int(row[1])) for i in range(len(Profit_Losses)-1): Profit_Losses_change.append(Profit_Losses[i+1]-Profit_Losses[i]) Months.append(row[0]) max_increase_value = max(Profit_Losses_change) max_increase_month = Profit_Losses_change.index(max(Profit_Losses_change)) max_decrease_value = min(Profit_Losses_change) max_decrease_month = Profit_Losses_change.index(min(Profit_Losses_change)) print ("Financial Analysis") print ("-----------------------------") print ("Total : ", "$", (Net_total)) print ("Total Months : ", (Date_rows)) print (f"Average Change: {round(sum(Profit_Losses_change)/len(Profit_Losses_change),2)}") print ("Greatest Increase in Profits: ", Months[max_increase_month], f"${(int(max_increase_value))}") print ("Greatest Decrease in Profits: ", Months[max_decrease_month], f"${(int(max_decrease_value))}") output_file = os.path.join("PyBank", "Analysis","Analysis.txt") with open(output_file, "w") as file: file.write("Financial Analysis") file.write('\n' +"-----------------------------") file.write('\n' +"Total : $" + str(Net_total)) file.write('\n' +"Total Months :" + str(Date_rows)) file.write('\n' +f"Average Change: {round(sum(Profit_Losses_change)/len(Profit_Losses_change),2)}") file.write('\n' +"Greatest Decrease in Profits: " + (Months[max_decrease_month] + (f" (${(str(max_decrease_value))})"))) file.write('\n' +"Greatest Increase in Profits: " + (Months[max_increase_month] + (f" (${(str(max_increase_value))})")))
true
3c6ac1d69134a6ceaa8f46388eee5be1af34d07b
ntritran999/password-checking
/user_pword.py
662
4.1875
4
from password_gen import password_generator while True: user_password = input("Enter a password: ") if len(user_password)<6: print("\n") print("Password must contain at least 6 digits!") print("Your password can be like this:", password_generator()) elif len(user_password)>=6 and (user_password.isalpha() or user_password.isnumeric()): print("\n") print("Password must contain both words and numbers!") print("Your password can be like this:", password_generator()) else: print("\n") print("Your Password Is Good Enough") print("Here it is:", user_password) break
true
c96fada55a63dac9a296b1f3059184a533dfe0ba
JinshanJia/leetcode-python
/+Binary Tree Postorder Traversal.py
1,204
4.125
4
__author__ = 'Jia' ''' Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? ''' # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): result = [] l = [] lastNode = None while root is not None or len(l) != 0: self.add(root, l) root = None currentNode = l[-1] if currentNode.right is None or currentNode.right == lastNode: result.append(l.pop().val) lastNode = currentNode else: self.add(currentNode.right, l) return result def add(self, root, l): while root is not None: l.append(root) root = root.left tree = TreeNode(1) tree.right = TreeNode(2) tree.right.left = TreeNode(3) s = Solution() print s.postorderTraversal(tree)
true
3cde5fca7199dec73582f85717f6d4d9fb1dc25b
JinshanJia/leetcode-python
/Binary Tree Preorder Traversal.py
1,045
4.125
4
__author__ = 'Jia' ''' Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? ''' # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): if root is None: return [] result = [] toTraversal = [root] while len(toTraversal) > 0: node = toTraversal.pop() result.append(node.val) if node.right is not None: toTraversal.append(node.right) if node.left is not None: toTraversal.append(node.left) return result tree = TreeNode(1) tree.right = TreeNode(2) tree.right.left = TreeNode(3) s = Solution() print s.preorderTraversal(tree)
true
0024b0991a6f73f8001b08c805ac6c2861cddd84
AlbertMukhammadiev/NumericalAnalysis_Labworks
/IterativeMethod_SLE/iterative.py
2,390
4.21875
4
"""Tool for solving systems of linear equations using iterative methods(Jacobi and Nekrasov methods). Iterative method is a mathematical procedure that uses an initial guess to generate a sequence of improving approximate solutions for a class of problems, in which the n-th approximation is derived from the previous ones. Functions: perform_iteration_Nekrasov(A, b, x0) -> float perform_iteration_Jacobi(A, b, x0) -> float approximate_Nekrasov(A, b, x0, eps) -> float approximate_Jacobi(A, b, x0, eps) -> float """ from numpy import zeros def perform_iteration_Nekrasov(A, b, x0): """Returns the next approximating value using the Nekrasov method. Arguments: A -- square matrix with diagonal predominance b -- vector x0 -- previous approximation """ n = A.shape[0] x = zeros(n) x0 = x0.copy() for k in range(n): product_k = x0 * A[k] product_k[k] = 0 x[k] = (b[k] - sum(product_k)) / A[k, k] x0[k] = x[k] return x def perform_iteration_Jacobi(A, b, x0): """Returns the next approximating value using the Jacobi method. Arguments: A -- square matrix with diagonal predominance b -- vector x0 -- previous approximation """ n = A.shape[0] x = zeros(n) for k in range(n): product_k = x0 * A[k] product_k[k] = 0 x[k] = (b[k] - sum(product_k)) / A[k, k] return x def approximate_Nekrasov(A, b, x0, eps): """Find the solution of SLE with a given accuracy using Nekrasov method. Arguments: A -- square matrix with diagonal predominance b -- vector x0 -- previous approximation eps -- accuracy """ while True: prev = x0 _log['Nekrasov'].append(prev) x0 = perform_iteration_Nekrasov(A, b, prev) if (sum(abs(x0 - prev))) < eps: break return x0 def approximate_Jacobi(A, b, x0, eps): """Find the solution of SLE with a given accuracy using Nekrasov method. Arguments: A -- square matrix with diagonal predominance b -- vector x0 -- previous approximation eps -- accuracy """ while True: prev = x0 _log['Jacobi'].append(prev) x0 = perform_iteration_Jacobi(A, b, prev) if (sum(abs(x0 - prev))) < eps: break return x0 _log = {'Nekrasov': [], 'Jacobi': []}
true
7cbfbe59de11b9f1f5be91bb510cc47f616db807
khalidammarmo/python-cs
/RPS/rps-3.py
1,424
4.28125
4
""" A lot fewer comments in this one now that you now what you're doing! """ import random beats = { "rock":"scissors", "paper":"rock", "scissors":"paper" } choices = list(beats.keys()) wins = 0 losses = 0 ties = 0 # Here come the functions: one for each step in the last version. def print_score(): print("Wins:", wins) print("Losses:", losses) print("Ties:", ties) def compare(c,p): """ c and p are used here to distinguish the arguments to the function from the player_choice and computer_choice variables in main(). """ global wins,losses,ties print("Computer chose " + c) if beats[p] == c: print("You win!") wins += 1 elif p == c: print("Tie!") ties += 1 else: print("You lose!") losses += 1 def main(): """ Take note how much clearer this is. Also, where'd that while loop go? """ print("Choose rock, paper, scissors, or 'quit' to quit.") player_choice = input("Rock, paper, or scissors? ").lower().strip() computer_choice = random.choice(choices) if player_choice == "quit": print("Goodbye!") print("Final score:") print_score() elif player_choice not in choices: print("You must choose r, p, or s!") main() else: compare(computer_choice, player_choice) main() main() # This is the line that starts the show.
true
0a59fb1d8a9f7ddd39f8695a2a5953734f4052f1
khalidammarmo/python-cs
/div/div-2.py
1,088
4.21875
4
""" Time to fix the div() so it gives right answers. """ def get_values(): """ Retrieves two values to divide """ x = input("What is the divisor? ") y = input("What is the dividend? ") try: #Before, the program would have failed on non-integer input. Now we can catch it. int_x = int(x) int_y = int(y) except ValueError: #If the inputs can't be parsed into print("We need two integers to divide!") return get_values() #On an error, we're going to run the function again return (int_x,int_y) def div(terms): """ Takes a 2 tuple TERMS—dividend and divisor—and returns the quotient. This one uses a simple reversal of the mult() function. """ dividend,divisor = terms[0], terms[1] quotient = 0 #We use a a while loop while dividend - divisor >= 0: dividend -= divisor quotient += 1 #Fun bonus! The divident, after all this subtraction, is actually the remainder. return (quotient,dividend) values = get_values() answer = div(values) print(answer)
true
24758ec4cdf28951f641e66ffe26e33ae2e8e7cd
khalidammarmo/python-cs
/inventory/inventory-1.py
572
4.4375
4
""" In this first list program, we'll simply create an inventory and write a function to manipulate it. This function is of a sort known as a "setter." It can also be considered a "wrapper" for the append() method of the list. Why do we even need a wrapper? Sometimes we like to make the output of a setter more user-friendly. """ #Initialize the inventory variable to an empty list. inventory = [] def add_item(item): """ Adds item to inventory. """ inventory.append(item) add_message = "{} added to inventory.".format(item) print(add_message)
true
2121980b7be9d37b65c437a29e8c43cab1681a28
nGreg72/learning
/checkio/secret message.py
1,378
4.25
4
"""Дан кусок текста. Соберите все заглавные буквы в одно слово в том порядке как они встречаются в куске текста. Например: текст = "How are you? Eh, ok. Low or Lower? Ohhh.", если мы соберем все заглавные буквы, то получим сообщение "HELLO". Входные данные: Текст как строка (юникод). Выходные данные: Секретное сообщение как строка или пустая строка. Предусловие: 0 < len(text) ≤ 1000 all(ch in string.printable for ch in text)""" def find_message(text: str) -> str: """Find a secret message""" result = "" for ch in text: if ch.isupper() == True: result += ch return str(result) if __name__ == '__main__': print('Example:') print(find_message("How are you? Eh, ok. Low or Lower? Ohhh.")) #These "asserts" using only for self-checking and not necessary for auto-testing assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello" assert find_message("hello world!") == "", "Nothing" assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals" print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
false
da0fec54696a1c1397ca66185869adceba7c9732
aga-moj-nick/Python-List
/Exercise 008.py
205
4.125
4
# 8. Write a Python program to check a list is empty or not. def sprawdzanie (lista): if len (lista) == 0: return 0 else: return 1 lista = [1, 2, 3] print (sprawdzanie (lista))
false
6c01f2f150422998dd70a88fbf4bb7a5962796d3
rhivent/py_basic
/9inheritance.py
1,244
4.21875
4
''' inheritance, subclasses, superclasses inheritance memperbolehkan kita utk mendefinisikan class dari klas yg utama/parent/class lain. sehingga kita bisa membuat dan memaintain aplikasi. Artinya kita bisa membuat kelas utama kemudian kelas turunannya hanya perlu didefinisikan sebagai anak kelas dari kelas utama. Dan anak kelas dapat memakai fungsi2 atau variabel yg ada di kelas utama. jika ingin kelas anak tidak ingin ada apa2 hanya menginisiasi sebagai anak kelas utama maka harus menggunakan keyword : pass inisiasi kelas anak tidak harus menginisiasi kelas utama, asalkan sudh mengheritance dr kelas utama dalam hal ini kelas anak bisa mejadi turunan dari banyak kelas parent (multiple inheritance) dgn pemisahan tanda , antar kelas ''' class Parent: variabel1 ="this is var 1" variabel2 ="this is var 2" class Parent2: variabel1 ="this is var 1" variabel2 ="this is var 2" # ini cara menggunakan => class anak(kelas_utama): class Child(Parent,Parent2): pass # menginisiasi class degn menampung dlm variabel # parent_ = Parent() # print(parent_.variabel1) # inisiasi anak kelas dengan ditampung variabel child_ child_ = Child() # menggunakan variabel pada kelas utama print(child_.variabel2,child_.variabel1)
false
84faa7c0967a9b5cd3083c21d125c60f47a47121
rhivent/py_basic
/35pattern_number_right.py
216
4.21875
4
''' output: 1 1 2 1 2 3 1 2 3 4 .... ask user to enter the rows ''' n = int(input("enter the number of rows:")) for i in range(1,n+1): for j in range(1,i+1): print(j,end="") print() # for new line
true
c3bdfb9ec37e63b4902afa497fb0eae394f3f32c
Christine340/R_Project_2
/python_project_2/top-down design.py
1,422
4.1875
4
TOP DOWN DESIGN first version def main(): #print out introduction and title printIntro() #calculate freq of each word freq() #display word cloud in window display() #undraw irrelavant things in the window undraw() #avoid overlaps between different words in word cloud avoidOverlap() main() second version def main(): win=GraphWin("Word Frequency",600,600) win.close() main() def printIntro(win): #print intro #print title #create inputbox #create entry button def freq(listofWord with frq,textfile,numofwordEnter): #loop through textfile #loop through stopword file #remove punctuation #remove stop words #if word is not in stopword #append it to newlist #sort word dictionary by frequency def display(textfile,numofwordEnter): #loop through every word in wordlist(after removing irrelavant things) #find the maxcount(the word exist most) #loop through each word #font size varies depend on the freq of word def avoidOverlap(numofwordEnter): #create a list #create grid #generate random points #check if that point is the same as others #append the word to list def undraw(): #create a white rectangle covers everything #draw the rec third version: third version is the final code it is in this folder(file: proj4_jyi)
true
1d2f680fdbf6f2f169d4f51afb46c832dae41e11
cody-berry/sbfac
/vehicle.py
2,255
4.125
4
from random import randint class Vehicle: def __init__(self, x, y): self.pos = PVector(x, y) self.vel = PVector(0, 0) self.acc = PVector(0, 0) self.max_speed = 5 self.max_force = 0.1 # First, we're taking a look at the target and use position PVectors as # position vectors. Then, we look at them as velocity vectors. They help us # determine what our acceeration should be. def seek(self, target): # target is a PVector # desired velocity = the vector that shows the distance between us and the # target minus our current velocity. # Get the distance away from the target; that'll help us. # Set the force to be max speed; we want our velocity to be it. # Limit the force; otherwise these vehicles will always be turning around. # We want our velocity to be max speed, not our acceleration! If our # velocity will add to the acceleration, we will be over our max speed. # For flee, we don't wanna get all the code and then change it; instead # we are going to return the force. return def flee(self, target): # In seek, we are returning the appropriate force. To shorten the code, # we can just return the return value * -1. return def persue(self, target): # We're basically going to seek a little bit ahead of our target. # But we need a number of frames ahead! # Then, we're going to add the target's velocity to the target's position # (not frequentely) to get our seek target. # Now just return the output of seek on the target on our new position # variable. return def evade(self, target): # Evade is the oppisite of persue. To shorten our code, we can just return # the return value * -1. return def show(self, target): # Acceleration vector pushMatrix() popMatrix() # Velocity vector pushMatrix() popMatrix() # Real position pushMatrix() popMatrix()
true
39de1a25d4355b4c04e101eee5405e1127a2f737
jfarrell-bsu/CS111-resources
/archived/cs111-project3-component1-stub.py
2,165
4.28125
4
# Author: # Date: # Description: Jackpot Challenge - Component One - Dice Game # Import required libraries # # This game is player vs house where each take turns rolling a single six-sided # die. The player with the highest roll each round wins a point. The house # receives the point for a tie. The first player to 5 points wins. # # Parameters # name - Name of the current player # # Returns # True - Player Wins # False - Player Loses def playGameOfDice(name): # The game should begin by displaying a welcome message including the # name of the game (Dice) and the players name. # The game should have a variable for tracking the player's score # and a variable for tracking the house's score # The game will continue while the players score is less than 5 # and the houses score is less than 5. # Print the current scores # Prompt the player to Press Enter to roll # Randomly generate integer value for players roll # Randomly generate integer value for houses roll # Compare results, print winner message, including name # and increment the score of the winner # If the player score is greater than the house score, the player Wins so return True. # Otherwise, return false. ###################################################################### # The code below this comment is what runs the program. Please # # take the time to look at how your function is being called and # # what is being done with the return value, but you do not need # # to modify this code to complete the component. # ###################################################################### # Setup a default player playerName = "Bob" # Call the function and store the result playerWins = playGameOfDice(playerName) # Display the winner! if playerWins == True: winnerString = "* " + playerName + " Wins! *" else: winnerString = "* House Wins! *" starBorder = "*" * len(winnerString) print(starBorder) print(winnerString) print(starBorder)
true
defbd3adab6b43011883ef686ad686d495399cb9
RudrakshAgarwal/Python-Notes
/Operatorss.py
972
4.40625
4
''' Airthmetic operator Assignment operator Comparison operator Logical operator Identity operator Membership operator Bitwise operator ''' #Airthmetic Operator print("5 + 6 is",5+6) print("5 - 6 is",5-6) print("5 * 6 is",5*6) print("5 / 6 is",5/6) print("5 ** 6 is",5**6) #Exponential Operator print("5 // 6 is",5//6) print("5 % 6 is",5%6) #It gives remainder #Assignment operator: print("Assignment operator") x=5 print(x) x += 7 print(x) x -= 2 print(x) #Comparison operator: print("Comparison operator") i= 8 print(i==5) print(i!=5 ) print(i>=5) #Logical operator: print("Logical operator") a = True b = False print(a and b) print(a or b) #Identity operator: print("Identity operator") c = True d = False print(c is d) print(c is not d) #Membership operator: print("Membership operator") list = [3,2,18,17,14,16,20] print(17 in list) print((324 not in list)) #Bitwise operator: print("Bitwise operator")
false
18808d05b10afbb936594183340664bc5644a55a
smhtbtb/Maktab
/clock.py
1,037
4.125
4
class Clock: def __init__(self, hour, minute): if 0 > hour > 23: raise Exception("Hours must be between 24 and -1") if 0 > minute > 59: raise Exception("Minutes must be between 60 and -1") self.hour = hour self.minute = minute def __repr__(self): return f"{self.hour:02}:{self.minute:02}" def __eq__(self, other): return (self.hour, self.minute) == (other.hour, other.minute) def __add__(self, minutes): minutes = self.minute + minutes self.minute = minutes % 60 hours = minutes // 60 self.hour = (self.hour + hours) % 24 return f"{self.hour:02}:{self.minute:02}" def __sub__(self, minutes): minutes = self.minute - minutes self.minute = minutes % 60 hours = minutes // 60 self.hour = (self.hour - hours) % 24 return f"{self.hour:02}:{self.minute:02}" c1 = Clock(1, 20) print(c1 == c2) print(c1) print(c2) print(c1 + 60 * 26) print(c1 - 60) c2 = Clock(1, 20)
false
d0fb2f69978918bf9568fb7f8a08ec15b7311e83
easywaldo/python_basic
/named_tuple.py
1,492
4.1875
4
from collections import namedtuple class Duck(): def __init__(self, bill, tail): self.bill = bill self.tail = tail def about(self): print(f'This duck has a {self.bill.description}, bill and a {self.tail.length}') duck = namedtuple("Duck", 'bill tail') parts = {'bill': 'wide orange', 'tail': 'long'} duck2 = Duck(**parts) print(f'{duck2.bill} {duck2.tail}') Point = namedtuple('Point', 'x, y') pt3 = Point(1.0, 5.0) pt4 = Point(2.5, 1.5) print(pt3) print(pt4) # named tuple 4 ways definition Point1 = namedtuple('Point', ['x', 'y']) Point2 = namedtuple('Point', 'x, y') Point3 = namedtuple('Point', 'x y') Point4 = namedtuple('Point', 'x y x class', rename=True) print(Point4) print(Point1, Point2, Point3, Point4) p1 = Point1(x=10, y=35) p2 = Point2(20, 40) p3 = Point3(45, y=20) p4 = Point4(10, 20, 30, 40) print(p1) print(p2) print(p3) print(p4) temp_dict = {'x': 75, 'y': 55} p5 = Point3(**temp_dict) print(p5) print(p5[0] + p5[1]) print(p5.x + p5.y) # namedtuple method temp = [33, 55] p4 = Point1._make(temp) # 새로운 개체 생성 print(p4) print(p1._fields, p2._fields, p3._fields) # 필드네임 확인 print(p1._asdict()) # OrderedDitc 반환 print(p4._asdict()) Classes = namedtuple('Classes', ['rank', 'number']) numbers = [str(n) for n in range(1, 21)] ranks = 'A B C D'.split() print(numbers) print(ranks) students = [Classes(r, n) for r in ranks for n in numbers] print(len(students)) print(students)
false
7568b3ce3b2b864a9e672fff6bd07d492970b651
LennartElbe/PythOnline
/scripts/sheet5/5.1.py
726
4.4375
4
#returns nth fibonacci value """ definition: this module defines the fibonacci number at nth place(NOT index) of fibonacci sequence. author:Lennart Elbe(lenni.elbe@gmail.com) """ def fib(n): # calculate fibonacci numbers up to input number """Author: Lennart Elbe (lenni.elbe@gmail.com) definition:This module calculates the fibonacci number at the nth place. arguments: n, the nth fibonacci number you want to find returns: element at nth index of list of fibonacci numbers example: """ fibList = [0, 1] for x in range(2, n+1): # hits every value to n # calculates last two numbers together and adds them to list fibList.append(fibList[x-2] + fibList[x-1]) return fibList[n] print(fib(3)) print(fib(10))
true
d41393bbed94b4164aff2dbe6402999f9de82e4c
Yashvishnoi/Python
/Recursion.py
427
4.3125
4
# Iterative method to find the factorial def factorial(n): fac= 1 for i in range (n): fac= fac*(i+1) return fac num= int(input("Enter the number ")) print("Factorial using iterative method ",factorial(num)) # Factorial using recursion def factorial_recursion(n): if n==1: return 1 else : return n*factorial_recursion(n-1) print("Factorial using recursion method ",factorial(num))
true
3a7e3bc23c2a26a432e8e351b0c6dd32fa208f5e
Yashvishnoi/Python
/Operators.py
653
4.5
4
# The below operator is Arithmetic operators print("5+6 is :" ,5+6) print("5-6 is :" ,5-6) print("5*6 is :",5*6) print("6/5 is :",6/5) print("6//5 is :",6//5) # it will give the integer value print("6**5 is :",6**5) # Operator is called double expotential operator it will rais ethe power print("6%5 is :",60%57) # it will give the remainder # The below operator is Logical Operator a=True b=False print(a or b) print(a and b) # The below operator is Identity operators a=True b=False print(a is b) print(a is not b) # The below operator is Membership operators list=[41,85,452,2,23,9,85,98,5,4,6,15,81,489] print(32 in list) print(32 not in list)
true
dde66d6c191110ca42b4ac8204ba39203db29f18
ThomasjD/Lunedi
/objects_classes.py
2,286
4.15625
4
#Write code to class Person(object): def __init__(self, name, email, phone, friends, greetings_count, unique_greetings): self.name = name self.email = email self.phone = phone self.friends = friends self.greetings_count = greetings_count self.unique_greetings = unique_greetings def greet(self, other_person): print (f'Hello {other_person.name}, I am {self.name}!') if other_person.name not in self.unique_greetings: self.unique_greetings.append(other_person.name) else: self.greetings_count += 1 def print_contact_info(self): print(f'{self.name}\'s email: {self.email}, {self.name}\'s phone:{self.phone}') def add_friends(self, friends): self.friends.append(friends) def num_friends(self): return len(self.friends) def __repr__(self): return '' % (self.name, self.email, self.phone) sonny = Person('Sonny', 'sonny@hotmail.com', '483-485-4948', friends = [], greetings_count= 0, unique_greetings= []) jordan = Person('Jordan', 'jordan@aol.com', '495-586-3456', friends = [], greetings_count= 0, unique_greetings= []) print(f'{sonny.name} email is {sonny.email} and phone # is {sonny.phone}') print(f'{jordan.name} email is {jordan.email} and phone # is {jordan.phone}') sonny.print_contact_info() #jordan.friends.append('sonny') jordan.add_friends('sonny') #sonny.friends.append('jordan') sonny.add_friends('jordan') sonny.greet(jordan) jordan.greet(sonny) jordan.greet(sonny) print (sonny.friends) print (jordan.friends) #print(len(jordan.friends)) print(jordan.num_friends()) print (f'sonny greetings count is {sonny.greetings_count}') #Make your own class print (f'Jordan has {jordan.greetings_count} unique greetings') print (f'Sonny has {sonny.greetings_count} unique greetings') print (len(jordan.unique_greetings)) print (len(sonny.unique_greetings)) #Create a class Vehicle. A Vehicle object will have 3 attributes: class Vehicle(object): def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print(f'{self.year} {self.make} {self.model}') car = Vehicle('Nissan', 'Leaf', 2015) print (car.make) car.print_info()
false
8a6097e1399a17a015030bbebbfa0d7f92080716
yashasvijhawar/C97_Number-Guessing-game-project
/guessingGame.py
441
4.1875
4
import random number = random.randint(1,9) chance = 0 print("Guess a number(between 1 and 9):") while chance<5: guess = int(input("Enter your Guess")) if guess == number: print("Congratulations,You won!!") break elif guess<number: print("Guess was too low,guess a number higher than that!!") else : print("Guess was too high,guess a number lower than that!!") chance+=1
true
cfc64dbce80d50ea03751bdda8d5d42000faaa2f
YaniVerwerft/Python
/Exercises/2_Selection/Exercise_3.py
481
4.15625
4
print('Please give me 3 numbers.') first = int(input('Number 1: ')) second = int(input('Number 2: ')) third = int(input('Number 3: ')) running_lowest = first if second < running_lowest: running_lowest = second if third < running_lowest: running_lowest = third #if first < second: # running_lowest = first #else: # if second < third: # running_lowest = second # else: # running_lowest = third print('The smallest number is: ' + str(running_lowest))
false
99ddcbaeddb9dd32d862e72826be1b3d9c05d196
dburger4/PythonProgrammingExercises
/Homework 1/primeNumsPrint.py
702
4.25
4
################ # Author: Daniel Burger # Date: 2/23/2019 # This program finds and prints all prime numbers # between and any given number (but in this case, 0 to 100) ################# NUMBER = 100 #chosen number to print all prime numbers from 0 to NUMBER for i in range(100): #special cases for 2, 3, 5, and 7 if ((i == 2) | (i == 3) | (i == 5) | (i == 7)): print(i) if ((i % 2) != 0): #if i is not divisible by 2 if ((i % 3) != 0): #if i is not divisible by 3 if ((i % 5) != 0): #if i is not divisible by 5 if ((i % 7) != 0): #if i is not divisible by 7 if (i != 1): #1 is not a prime number print(i)
true
a7305a48f677fc03327845be47487738581ed3f1
egalli64/pythonesque
/cip/w6/ex_planetary.py
1,270
4.4375
4
""" Code in Place 2023 https://codeinplace.stanford.edu/cip3 My notes: https://github.com/egalli64/pythonesque/cip Section Week 6 (review from 3): Planetary Weights - Earthling's weight on Mercury is 37.6% of their weight on Earth, ... - Write a program that Prompts an Earthling to enter their weight on Earth, and the name of a planet Prints the calculated weight """ FACTORS = {"Mercury": 0.376, "Venus": 0.89, "Mars": 0.378, "Jupiter": 2.36, "Saturn": 1.081, "Uranus": 0.82, "Neptune": 1.14} def main(): # 1. ask the user for a weight - convert it to real number on the spot earth_weight = float(input("Enter a weight on Earth: ")) # 2. ask the user for a planet planet = input("Enter a planet: ") # 3. determine the factor that should be applied factor = FACTORS.get(planet, 1.0) if factor == 1.0: # unknown planet - let the user know something strange is going on print("I don't know anything of planet " + planet + ". I assume it is just like Earth.") # 4. get the weight on the selected planet planetary_weight = earth_weight * factor # 5. output the result print(f"The equivalent weight on {planet}: {planetary_weight}") if __name__ == "__main__": main()
true
5cc7aa94a044dda878dc88bafd7907d043dc58fa
egalli64/pythonesque
/kaggle/LearnPythonChallenge/Day6/word_search.py
1,638
4.40625
4
# Learn Python Challenge: Day 6 Exercises def word_search(doc_list, keyword): """ Takes a list of documents (each document is a string) and a keyword. Returns list of the index values into the original list for all documents containing the keyword. Example: doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"] >>> word_search(doc_list, 'casino') >>> [0] """ results = [] for i, doc in enumerate(doc_list): tokens = doc.split() words = [x.rstrip('.,').lower() for x in tokens] if keyword.lower() in words: results.append(i) return results def multi_word_search(doc_list, keywords): """ Takes list of documents (each document is a string) and a list of keywords. Returns a dictionary where each key is a keyword, and the value is a list of indices (from doc_list) of the documents containing that keyword >>> doc_list = ["The Learn Python Challenge Casino.", "They bought a car and a casino", "Casinoville"] >>> keywords = ['casino', 'they'] >>> multi_word_search(doc_list, keywords) {'casino': [0, 1], 'they': [1]} """ results = {} for keyword in keywords: results[keyword] = word_search(doc_list, keyword) return results if __name__ == '__main__': print(word_search( ['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'], 'casino' )) print(multi_word_search( ['The Learn Python Challenge Casino', 'They bought a car and a casino', 'Casinoville?'], ['casino', 'they'] ))
true
6ea9325312842cc170f75d76a38824c4e8422b7f
egalli64/pythonesque
/cip/w6/ex_heads.py
926
4.15625
4
""" Code in Place 2023 https://codeinplace.stanford.edu/cip3 My notes: https://github.com/egalli64/pythonesque/cip Week 6: #3 Heads Up 1: Read the provided function that loads all of the words from the file cswords.txt into a list. 2: Then, show a randomly chosen word from the list 3: Repeat: wait for the user to hit enter, then show another word. """ import random # Name of the file to read in! FILE_NAME = 'cip\w6\cswords.txt' def get_words_from_file(): """ This function has been implemented for you. It opens a file, and stores all of the lines into a list of strings. It returns a list of all lines in the file. """ with open(FILE_NAME) as f: lines = f.readlines() return lines def play(words): while True: word = random.choice(words) input(word) def main(): words = get_words_from_file() play(words) if __name__ == '__main__': main()
true
311947c383e452bef946ec62712b28025c99fca9
egalli64/pythonesque
/ctds/problem_3.py
1,906
4.125
4
""" Based on Week 2 > Lecture 4 - Stochastic Programming and Statistical Thinking - L4 Problem 3 From edx.org - MITx: 6.00.2x Introduction to Computational Thinking and Data Science Original function signature: stdDevOfLengths(L) More info: http://pythonesque.blogspot.com/2016/03/strings-standard-deviation.html """ import unittest import math def standard_deviation(strings): """ :param strings: a list of strings :returns the standard deviation of the lengths of the strings, or NaN. :rtype float """ if not strings: return float('NaN') lengths = [len(s) for s in strings] mean = math.fsum(lengths) / len(lengths) sq_sum = 0.0 for l in lengths: sq_sum += (l - mean) ** 2 return math.sqrt(sq_sum / len(lengths)) class StdDevTest(unittest.TestCase): def test_none(self): self.assertTrue(math.isnan(standard_deviation(None))) def test_empty(self): strings = [] self.assertTrue(math.isnan(standard_deviation(strings))) def test_1(self): strings = ['a', 'z', 'p'] self.assertEqual(standard_deviation(strings), 0) def test_2(self): strings = ['apples', 'oranges', 'kiwis', 'pineapples'] self.assertAlmostEqual(standard_deviation(strings), 1.8708, delta=0.0001) def test_3(self): strings = ['mftbycwac', 'rhqbqawnfl', 'clgzh', 'ilqy', 'ckizvsgpnhlx', 'kziugguuzvqarw', 'xqewrmvu', 'ktojfqkailswnb'] self.assertEqual(standard_deviation(strings), 3.5355339059327378) def test_4(self): strings = ['zgbljwombl', 'slkpmjqmjaaw', 'nddl', 'irlzne', '', 'poieczhxoqom', 'waqyiipysskxk', 'dloxspi', 'sk'] self.assertEqual(standard_deviation(strings), 4.447221354708778) def test_bad_data(self): with self.assertRaises(TypeError): standard_deviation([1, 2, 3]) if __name__ == '__main__': unittest.main()
true
e50b0f865675871f3f541453a7f9bda7833fd166
egalli64/pythonesque
/pcc3/ch07/e3_while.py
1,370
4.1875
4
""" Python Crash Course, Third Edition https://ehmatthes.github.io/pcc_3e/ My notes: https://github.com/egalli64/pythonesque/pcc3 Chapter 7 - User Input and While Loops - Using a while Loop with Lists and Dictionaries """ # Moving Items from One List to Another unconfirmed_users = ['alice', 'brian', 'candace'] print('Unconfirmed users:', unconfirmed_users) confirmed_users = [] # until there are unconfirmed users while unconfirmed_users: user = unconfirmed_users.pop() print(f"Verifying user: {user.title()}") confirmed_users.append(user) print("The following users have been confirmed:") for user in confirmed_users: print(user.title()) # Removing All Instances of Specific Values from a List pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print('Original pets:', pets) while 'cat' in pets: pets.remove('cat') print('After removing cats:', pets) # Filling a Dictionary with User Input responses = {} while True: name = input("Name? ") response = input("Which mountain would you like to climb someday? ") responses[name] = response repeat = input("Would you like to let another person respond? (y/n) ") if repeat == 'n': break # Polling is complete. Show the results. print("\n--- Poll Results ---") for name, response in responses.items(): print(f"{name} would like to climb {response}.")
true
ecc47d1d505976382757275589827ae94294c65b
egalli64/pythonesque
/pcc3/ch06/e2_looping.py
1,814
4.21875
4
""" Python Crash Course, Third Edition https://ehmatthes.github.io/pcc_3e/ My notes: https://github.com/egalli64/pythonesque/pcc3 Chapter 6 - Dictionaries - Looping Through a Dictionary """ user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi' } # looping on each k/v pair by items() for key, value in user_0.items(): print(f"Key: {key}", f"Value: {value}") favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'rust', 'phil': 'python', } # naming k/v in more readable way for name, language in favorite_languages.items(): print(f"{name.title()}'s favorite language is {language.title()}.") # looping on all keys() for name in favorite_languages.keys(): print(name.title()) # given a list of friends friends = ['phil', 'sarah'] for name in favorite_languages.keys(): print(f"Hi {name.title()}.") # for each dictionary key that is in the friend list ... if name in friends: language = favorite_languages[name].title() print(f"\t{name.title()}, I see you love {language}!") # if k is not a key in the dictionary ... if 'erin' not in favorite_languages.keys(): print("Erin, please take our poll!") # looping on sorted keys() for name in sorted(favorite_languages.keys()): print(f"{name.title()}, thank you for taking the poll.") # looping on values() print("The following languages have been mentioned:") for language in favorite_languages.values(): print(language.title()) # using set() to get rid of duplicates print("The following languages have been mentioned (no duplicates - no order):") for language in set(favorite_languages.values()): print(language.title()) # set definition languages = {'python', 'rust', 'python', 'c'} print("Set representation is close to dictionary one", languages)
true
bc18a8b83dffbba7be00b255f5f7983e8c2d90b6
egalli64/pythonesque
/algs200x/w7/s4_b_paths.py
743
4.25
4
""" Number of Paths in a Grid author: Manny egalli64@gmail.com info: http://thisthread.blogspot.com/ https://www.edx.org/course/algorithmic-design-techniques-uc-san-diegox-algs200x week 7 - final exam - dynamic programming Given a 5x5 grid. You start at the bottom left cell. In one step, you are allowed to go either one cell up or one cell to the right. Your goal is to compute the number of different paths from the bottom left cell to the top right cell. """ def solution(size): table = [[1 for _ in range(size)] for _ in range(size)] for i in range(1, size): for j in range(1, size): table[i][j] = table[i-1][j] + table[i][j-1] return table[-1][-1] if __name__ == '__main__': print(solution(5))
true
23244f24cc35c425a54e2a5f378848c5b10308a8
Artur-Aghajanyan/VSU_ITC
/Anna_Mayilyan/python/26_05/find.py
1,091
4.40625
4
def Convert_To_String(string): item = list(string.split(" ")) return item # Driver code str1 = "Tux TuX is a penguin character and the official brand character of the LINUX kernel. Originally created as an entry logo competition, TUX is the most commonly used icon for Linux , although different Linux distributions depict Tux in various styles. The character is used in many other lInux programs and as a general symbol of Linux ." # print(Convert(str1)) List = Convert_To_String(str1) counter = 0 dic = {} for i in range(len(List)): if List[i].istitle(): List[i] = List[i].upper() #print(List[i]) #for i in range(len(List)): # print(List[i]) for i in range(0,len(List)): if List[i].isupper(): if List[i] in dic: dic[List[i]] += 1 else: dic[List[i]] = 1 #print(dic) def search(dic, val): keysList = [] itemsList = dic.items() for item in itemsList: if item[1] == val: keysList.append(item[0]) return keysList print("Enter number") val = int(input()) print(search(dic, val))
true
279d44c2bd094f1452ae8e23015fbbf5f24d690c
SiegfriedWagner/Game_of_life-KNN
/main.py
1,124
4.21875
4
#lista = list((1,2,3)) # deklaracja listy lista = [1,2,3] # inna delkaracja tej samej listy print(lista) print(lista[0]) #dobranie sie do pierwszego elementu print(lista[-1]) #dobranie sie do ostatniego elementu print(type(lista[0])) # typ elementu print(type("ciag znakow")) print(type(1.2)) print(type(b'b')) # standard ASCII print(type(lista)) print([1, ['druga lista']]) # listy moga przechowywac inne list, a listy moga przechowac zmienne roznych typo print([[1,2,3], [4,5,6]]) macierz = [[0]*10]*10 # tablica 10x10, zwodnicza! jest elementy tablicy (rzędy) to odnośniki do tej samej listy dziesięcioelementowej wypełnionej zerami print(macierz) macierz = [0]*10 # for row in macierz: # row = [0]*10 print(len(macierz)) # zwraca długość iterowalnej zmiennej for index in range(len(macierz)): # nie można iterować po nieiterowalnych print(index) macierz[index] = [0] * 10 macierz[4][4] = 5 for row in macierz: print(row) # range dwuargumentowy for liczba in range(5, 7): print(liczba) if 5 < 7: # warunek print('prawda') # jezeli prawdziwy else: print('fałsz') # jezeli falszywy
false
640b03f2a49ef53502ccc350f708f264ef7fec60
nicklyle/Fin6320-Assignments-
/NumberGuessing.py
1,207
4.15625
4
#guess_word game words = ("Finance", "Economics", "Money", "Austrian", "Hedging") choice = int(input("Enter a number from 1 to 5: ")) print("Take a guess, word has",len(words[choice]),"letters:") print(words[choice]) guess = input("Take a guess: ") tries = 0 letter = "" while guess != words[choice]: print("\nKeep trying!") if tries != 5: letter_question = input("Want to ask for a letter yes/no? ") if letter_question == "yes" or letter_question == "y": letter_guess = input("Enter a letter: ") if letter_guess in words[choice]: print(letter_guess, "is in word") tries += 1 guess = input("Take a guess: ") else: print("Letter not in word") tries += 1 guess = input("->>Take a guess: ") if guess == words[choice]: print("You guessed the word") break else: continue else: continue else: print("You lose, sorry!") break print("See you soon!")
true
6bb592ba11a7c215c8099656d52b54dcb1185205
wooyoyohehe/Python_Tools
/Linked_List_Usage.gyp
2,054
4.46875
4
#Linked List # Generally speaking, how you use the linked_list depends on how you define it. # For example, you can use both val and data to express its contents. class LinkedList: def __init__(self): self.head = None self.tail = None class Node: def __init__(self, data): self.data = data self.next = None # Definition for singly-linked list. # Demo from Leetcode # Demo starts here class ListNode(object): def __init__(self, x): self.val = x self.next = None # l1 and l2 are both nodes # creates a new instance of the class and assigns this object to the local variable l1. # 0 means the data in this node's cargo is 0 l1 = ListNode(0) print l1.val l2 = ListNode(1) l1.next = l2 print l1.next.val # Demo over # Another demo created by myself l3 = LinkedList() n1 = Node(5) print n1.data n2 = Node(10) # By Judging the node is None or not, we can get to know whether this linked_list is over or not. print n1.next == None # If we want to combine two linked_lists, we can do the follwering operation: n1.next = n2 print n1.next == None # In this instance, we define 4 nodes and link them together as a linked_list like this, and try to print all the elements in it: # Define 4 nodes node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) # Link them together: node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 # Tip: sometimes, we can assign one more node to keep the first node, in order to return. node = node1 # print all them out: def print_linklist(node): while node != None: # Or while node: print node.data node = node.next print_linklist(node) # What if we want to remove node4? # Make the first node refer to the third node3.next = node4.next # separate the second node from the rest of the list node4.next = None new_node = Node(2.5) # What if we want to insert a new node between node2 and node3? # Step 1 new_node.next = node3 # Step 2 node2.next = new_node print_linklist(node)
true
34ee70e97201f2c5c7b27a517f5ffe01a6709e9c
lauramayol/laura_python_core
/week_03/labs/08_tuples/08_02_word_frequencies.py
1,071
4.5
4
''' Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. Find text samples from several different languages and see how letter frequency varies between languages. Compare your results with the tables at: http://en.wikipedia.org/wiki/Letter_frequencies. Solution: http://thinkpython2.com/code/most_frequent.py. Source: Chapter on "Tuples" in Think Python 2e: http://greenteapress.com/thinkpython2/html/thinkpython2013.html ''' def most_frequent(message): formatted_message = message.lower() num_list = list() letter_list = list() for letter in formatted_message: if letter not in letter_list: num_list.append(formatted_message.count(letter)) letter_list.append(letter) #print(num_list, letter_list) combined = list(zip(num_list, letter_list)) combined.sort(reverse=True) for num, let in combined: print(num, let) return combined my_message = "Hello my name is Laura and I am practicing Python" most_frequent(my_message)
true
ce6f1c2fe3673f21744615a6dba0c138a73afda1
lauramayol/laura_python_core
/week_02/mini_projects/leap_year_stack_diagram.py
2,139
4.28125
4
''' -------------------------------------------------------- LEAP YEAR + STACK DIAGRAM -------------------------------------------------------- Construct a function according to the following description, then draw a stack diagram of an execution with ‘2000’ as input. -- DESCRIPTION -- We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February. In the Gregorian calendar three criteria must be taken into account to identify leap years: - The year can be evenly divided by 4, is a leap year, unless: - The year can be evenly divided by 100, it is NOT a leap year, unless: - The year is also evenly divisible by 400. Then it is a leap year. This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. -- TASK -- You are given the year, and you have to write a function to check if the year is leap or not. Input Format: Read y, the year that needs to be checked. Constraints: 1900 <= y <= 10**5 Output Format: Your function must return a boolean value (True/False) -- STACK DIAGRAM -- You can use the viz mode here: http://www.pythontutor.com/visualize.html#mode=edit for better visual understanding and support in creating the stack diagram. ''' print("Please enter a year to determine if it is a leap year:") year_input = int(input()) def is_leap_year(y): if y >= 1900 and y <= 10**5: if y % 4 == 0: if y % 100 == 0 and y % 400 > 0: is_leap = False else: is_leap = True else: is_leap = False else: is_leap = None print("Please enter a year from 1900 up to 100,000.") return is_leap print(is_leap_year(year_input)) ''' Stack diagram below -------------------- <module> | year_input -> 2000 | -------------------- | y -> 2000 | is_leap_year| is_leap -> True | |return value -> True| -------------------- '''
true
42b38cbb06c8599736533d6f8fb695ea8010b134
diemccon/my_projects_python
/userguessnumber.py
620
4.28125
4
import random # the game below allows you to guess a number that the computer has randomly generated print("Try to guess a number 1-100 that the computer has randomly generated...") def guess(x): random_number = random.randint(1, x) guess = 0 while guess != random_number: guess = int(input(f"Enter a number between 1 and {x}: ")) if guess < random_number: print("Not quite. Your guess was too low. ") elif guess > random_number: print("Not quite. Your guess was too high.") print(f"Yay! You guessed the number correct. ({random_number}) ") guess(100)
true
5c7220a837c20230c744003e236569a3141ddf15
gourabbhattacharyya/Python-Hobby-Projects
/ListCheck/unpackList.py
1,137
4.375
4
item = ['May 18, 2017', 'Cake', 5.98] #define list of items print('Date : ' + item[0] + ' Name : ' + item[1] + ' Price : ' + str(item[2])) #access the items in the list using their position index Date, Name, Price = ['May 18, 2017', 'Cake', 5.98] #define list of items along with each definite element name while declaring print('Date : ' + Date + ' Name : ' + Name + ' Price : ' + str(Price)) #access using them def getMiddleAgv(gradesList): #This is the advanced method of unpacking the list items first, *middle, last = gradesList #set the elements to definite item names. '*' defines any number of items that comes in that position avg = sum(middle)/len(middle) #access and manipulate the items print('Average grade is : ' + str(avg)) #print the value getMiddleAgv([55, 65, 40]) #call with 1 items for each position getMiddleAgv([55, 65, 75, 85, 40]) #call with 3 items in the middle position getMiddleAgv([55, 65, 75, 85, 95, 105, 115, 125, 135, 145, 155, 40]) #call with more items in the middle position
true
bcd6d2bdd47d3fd94afa474cf90794554d7a69fe
gourabbhattacharyya/Python-Hobby-Projects
/ListCheck/listOperations_minMax.py
761
4.15625
4
import heapq grades = [10,12,15,25,39,9,7,99,1004,500] #initialize list print(heapq.nlargest(3, grades)) #get the top 3 largest values from the list. Syntax : heapq.nlargest(number of items, list to iterate through) print(heapq.nsmallest(5, grades)) stocks = [ #initialize list of dictionaries {'ticker':'apple', 'price':109.29}, {'ticker':'google', 'price':99.59}, {'ticker':'fb', 'price':69}, {'ticker':'amazon', 'price':119.7}, {'ticker':'ebay', 'price':19.39} ] print(heapq.nlargest(2, stocks, key = lambda stocks:stocks['price'])) #get the top 2 largest values.Syntax : heapq.nlargest(number of items, list to iterate through, keyValue)
true
8bb66b398a692e6b4a0efe5d4a10f5cd941e7bda
amlanpatra/programs
/python3/full_year_calendar.py
248
4.4375
4
# Python program to display calendar of # given month of the year import os print(os.getcwd()) import calendar yy = 2020 mm = 1 print(calendar.month(yy,mm)) print ("The calender of year 2020 is : ") print (calendar.calendar(2020, 2, 1, 6))
true
8363dc4ebfc8136d3237f8de98ab4b081e2d84b5
Hema113/python_puzzles
/47order_list.py
580
4.1875
4
def sort_ing(ip_list): for i in range(len(ip_list)): for j in range(i+1, len(ip_list)): if ip_list[i] > ip_list[j]: ip_list[i], ip_list[j] = ip_list[j], ip_list[i] return ip_list if __name__ == "__main__": ip_list = [-5, 10, 50, 5, 2 ,1 ,100, 80 , 60, 35] search = int(input("Enter number u want be Search>>")) print("Before>>",ip_list) result=sort_ing(ip_list) print("Ascending order>>>",result) if search in result: print(search,"is available in list") else: print(search,"Not available")
false
281e69fbd6e2d18ce465b906ac0a80ce579e0567
Hema113/python_puzzles
/next_prime.py
430
4.1875
4
#Print Next prime Number # Import prime_no function from prime.py from prime import prime_no def next_prime(num): if num == 0 or num == 1: num = 1 for i in range(num+1, (num*2)+1): if prime_no(i): # Check given num is prime or not num = i return num # Main if __name__ == "__main__": num = int(input("Enter the number")) print ("The next prime number is", next_prime(num))
true
f0edf6a1789ad1de4f6a751b8bc8870423c89fe1
Hema113/python_puzzles
/dictionaries.py
1,013
4.15625
4
# Program return date of birth based on name useing dictionaries # Function for dictionaries def dictionary(birthday_data,name): temp = [] for data in birthday_data["birthday"]: if ["Name"] == name: temp.append((data["DOB"], data["ID"]) else: break return temp # Main if __name__ == "__main__": birthday_data = { "birthday": [ { "ID": 1, "Name": "Hemachandran", "DOB": "30-06-1995" }, { "ID": 2, "Name": "Hemachandran", "DOB": "30-04-1996" } { "ID": 30, "Name": "Balaji", "DOB": "24-011-1964" } ] } name = input("Enter the name>>>") result = dictionary(birthday_data,name) if result == []: print("Data not found") else: for i in result: print(name,"DOB>>>",i[0],"ID>>>",i[1])
false
0cd48ae3039ad3a4da7540906a200c20a3030129
Hema113/python_puzzles
/41name_age_height.py
1,001
4.25
4
# Program for stroing data in tuples in ascending order # package for sorting the data useing key values from operator import itemgetter database_info = [] while True: user_ip = input("Enter name,age,height>>>:") if user_ip == "stop" or user_ip == "STOP": # If user is input is balank and press the ENTER exit from the loop break else: # Split the user input and stored in tuples database_info.append(tuple((user_ip.split(" ")))) # Sorting the user data using itemgetter key database_info.sort(key = itemgetter(0, 1, 2)) print("Ascending sorted tuple>>>",database_info) """from operator import itemgetter def tup(): database_info = [] while True: user_ip = input("Enter name,age,height") if user_ip == "": break else: database_info.append(tuple((user_ip.split(",")))) return database_info.sort(key = itemgetter(0, 1, 2)) if __name__ =="__main": print("Ascending order tuples>>>>",tup())"""
true
9644a768e621820137806eacfa06c675699264a6
akshaymulik/Python-Examples
/Area_of_Rectangle.py
261
4.3125
4
# Enter Dimensions of Rectangle length = input(" Enter the Length of Rectangle: ") breadth = input(" Enter the Breadth of Rectangle: ") # Area of Rectangle Area = float(length)*float(breadth) #Print the Area print('The Area of Rectangle is {0}'.format(Area))
true
f5afa796159e738522e5c94363e5865effd64729
VijayVictorious/Python-Practice
/for loop/factorial of given numbers.py
216
4.21875
4
""" Write a program factorial of given numbers """ n = int(input("Enter number = ")) factorial = 1 for i in range(n,1,-1) : factorial = factorial * i print ("factorial value is = ",factorial)
true
0b2f71df92a14d8e9e01ea79f3767dca5fd77cc9
VijayVictorious/Python-Practice
/for loop/number divisible by 5 and 3 between start value to end value.py
341
4.34375
4
""" Write a program print the number is divisible by 5 and 3, in between start value to end value note : you need to get input for start and end value from user """ start = int(input("Enter start value = ")) end = int(input("Enter end value = ")) for i in range(start,end+1) : if i % 5 == 0 and i % 3 ==0 : print(i)
true
7490661db2edd5a2e57506f1999bea1e33ac6672
VijayVictorious/Python-Practice
/for loop/odd number up to in reverse order.py
230
4.3125
4
""" Write a program print the odd number up to n in reverse order eg. n=10 ouuput = 9,7,5,3,1 """ n = int(input("Enter number = ")) for i in range(10,0,-1) : if i % 2!=0 : print(i)
false
21f4bea67a39a4c0a7d89b9cf607283f6fa0e5d3
Bombbird2001/algo-ps1
/ex5.py
564
4.21875
4
# Type your code for insertion sort (Exercise 5) here def insertion_sort(noList): for i in range(1, len(numbers)): key = numbers[i] k = i - 1 while k >= 0 and key < numbers[k]: (numbers[i], numbers[k]) = (numbers[k], numbers[i]) i -= 1; k -= 1; print(numbers) while True: try: rawInput = input("Enter a list of numbers, or X to exit:").strip() if rawInput == "X": break else: numbers = list(map(int, rawInput.split(" "))) insertion_sort(numbers) except: print("Please enter a valid list of space-separated integers!")
true
412de97000b539056929e81a3a448219c8c4c0be
sumit162-sys/pythonprojetcs
/src7.py
1,230
4.15625
4
''' Assume you want to build two functions for discounting products on a website. Function number 1 is for student discount which discounts the current price to 10%. Function number 2 is for additional discount for regular buyers which discounts an additional 5% on the current student discounted price. Depending on the situation, we want to be able to apply both the discounts on the products. Design the above two mentioned functions and apply them both simultaneously on the price. ''' def st(p1): cp1 = 0.9*p1 return cp1 def reg(func, arg): x = func(arg) s = 0.95*x return s a= input("Are you a Student or Regular Customer, type S or R accordingly") b = int(input("Enter the product cost")) if a == 'S': print("The discounted price for student is " + str(st(b))) if a == 'R': print("The discounted price for Regular Customer is " + str(reg(st, b))) ''' def student_discount(price): price = price - (price * 10) / 100 return price def additional_discount(newprice): newprice = newprice - (newprice * 5) / 100 return newprice selling_price = 100 #applying both discounts simultaneously print(additional_discount(student_discount(selling_price))) '''
true
42f1fce93c474e8646d9a162d49f6d0e34703a30
JorPoon/Algorithms
/recipe_batches/recipe_batches.py
999
4.125
4
#!/usr/bin/python import math ''' UNDERSTANDING: -Takes in 2 dictionaries = 1 dictionary is amount of ingredients needed, 1 is amount of ingredients available - returns the amount of batch you can make ''' def recipe_batches(dict1, dict2): arr = [] if len(dict1) != len(dict2): return 0 for i in dict1: for j in dict2: # arr.append(dict2[j] % dict1[i]) if (i == j): arr.append(dict2[j] / dict1[i]) max_batch = int(min(arr)) # for j in dict2: # print(dict2[j]) return max_batch if __name__ == '__main__': # Change the entries of these dictionaries to test # your implementation with different inputs recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
true
3770537998a7055cc1395812c495e8c0837ca86d
vanesa/codepractice
/hackerrank/pythonstrings.py
1,570
4.3125
4
""" HACKERRANK CHALLENGES - PYTHON STRINGS """ #### Strings ###### """ Problem Statement You are given a string S. Your task is to swap case, i.e., convert all lower case letters to upper case and vice versa. Example : Www.HackerRank.com → wWW.hACKERrANK.COM Pythonist 2 → pYTHONIST 2 Input Format Single line containing, String S. Constraints 0<len(S)⩽1000 Output Format Print the modified string S. Sample Input HackerRank.com presents "Pythonist 2". Sample Output hACKERrANK.COM PRESENTS "pYTHONIST 2". """ def swap_case('HackerRank.com presents "Pythonist 2".'): phrase = raw_input() swapped = '' for x in phrase: if x == x.upper(): swapped = swapped + x.lower() else: swapped = swapped + x.upper() print swapped ##### String Split and Join ##### """ Problem Statement In Python a string can be split on a delimiter. Example >>> a = "this is a string" >>> a = a.split(" ") # a is converted to a list of strings. >>> print a ['this', 'is', 'a', 'string'] Joining a string is simple >>> a = "-".join(a) >>> print a this-is-a-string Task You are given a string. Split the string on " " (space) delimiter and join using a - hyphen. Input Format The first line contains a string consisting of words separated by space. Output Format Print the formatted string as explained above. Sample Input this is a string Sample Output this-is-a-string """ def split_join(): phrase = raw_input("Type in a phrase: ") phrase = phrase.split() print "-".join(phrase) if __name__ == '__main__': split_join()
true
58f6b7dfb3df11eed7170e591ebeb3b8a382ccd9
ravishastri9/Python-Projects
/11. Password Generator/Password Generator.py
851
4.25
4
"The program gives you a random password by random module." import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z'] numbers = ['0','1','2','3','4','5','6','7','8','9','0'] symbols = ['@','$','%','^','&','*','(',')','+'] print("welcome to the PyPassword Generator!") nr_letters = int(input("How many letters would you like in your password\n")) nr_numbers = int(input("How many numbers would you like in your password\n")) nr_symbols = int(input("How many symbols would you like in your password\n")) password = "" for char in range(1, nr_letters + 1): password += random.choice(letters) for char in range(1, nr_numbers + 1): password += random.choice(numbers) for char in range(1, nr_symbols + 1): password += random.choice(symbols) print(password)
true
80a5e962dd47023644fa6ecd753cc52bdd7936d7
Sultanova08/Part2_Task11b
/task11.2.2.py
773
4.21875
4
s = input("Enter the sentence : ") n = 2 print(s[3], ) # In the first line, print the third character of this string. print(s[0:-1]) # In the second line, print the second to last character of this string. print(s[0:5]) # In the third line, print the first five characters of this string. print( s[-2] ) # In the fourth line, print all but the last two characters of this string. print(s[::2]) # print all the characters of this string with even indices print(s[1::2]) # print all the characters of this string with odd indices print(s[::-1]) # line, print all the characters of the string in reverse order. print( s[: -n - 1 : -1] ) # print every second character of the string in reverse order,starting from the last one print (len(s)) #not finished last
true
133ab56f3d35eb0866c942134f80b1cf6bb22576
Uchicago-Stat-Comp-37810/assignment-2-jayzhang0727
/Exercise4.py
1,419
4.40625
4
#For the questions: the variable car_pool_capacity was not defined. So it will not return any values. #It is unnecessary to use the floating number to describe an integer since our computation only involves product, sum or subtraction. cars = 100 #This gives the total number of cars which is 100. space_in_a_car = 4 #This gives the number of seats within a car. drivers = 30 #This gives the total number of drivers in this system. passengers = 90 #This gives the total number of passengers in this system. cars_not_driven = cars - drivers #This gives the number of cars that are not driven. cars_driven = drivers #This gives the number of cars that are being used which is obvious equal to the number of drivers. carpool_capacity = cars_driven * space_in_a_car #This gives the total capacity of the systems which equal to the number of cars being used * the seats in each car. average_passengers_per_car = passengers / cars_driven #This gives the average number of passengers sitted on each driven car. #The following codes output the summary of the above datas. print ("There are", cars, "cars available.") print ("There are only", drivers, "drivers available.") print ("There will be", cars_not_driven, "empty cars today.") print ("We can transport", carpool_capacity, "people today.") print ("We have", passengers, "to carpool today.") print ("We need to put about", average_passengers_per_car, "in each car.")
true
52c83f91da10a949611acea906bb39b65706f6a8
ArpitBodana/Python
/palindrome.py
320
4.125
4
def palindrome(num): temp=num rev=0 while(num>0): n=num%10 rev=rev*10+n num=num//10 if rev==temp: print(rev,'=',temp) print("it is palindrome") else: print(rev,'!=',temp) print("it is not palindrome") palindrome(12321)
false
1796c9be0199a55827a7d4112839224769c639e0
SofyaTorosyan/python
/calculator.py
718
4.3125
4
# Homework_1 # simple calculator input1 = float(input()) # for floating inputs input2 = input() input3 = float(input()) result = 0 if input2 == "/": if input3 == 0: # for dividing on zero print("result: ", input1, " / ", input3, " = INFINITY " ) else: result = input1 / input3 print("result: ", input1, " / ", input3, " = ", result ) elif input2 == "*": result = input1 * input3 print("result: ", input1, " * ", input3, " = ", result) elif input2 == "+": result = input1 + input3 print("result: ", input1, " + ", input3, " = ", result) elif input2 == "-": result = input1 - input3 print("result: ", input1, " - ", input3, " = ", result)
false
3a23da431245acc72b5d6181c3d6351c43af983b
24apanda/python_useful
/loop_1.py
450
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 13 23:47:18 2016 @author: apanda88 """ max = 3 print(end=" ") for column in (1,max): print(end="%2i" %column) print() print(end="+") for column in (1,max+1): print(end="###") print() for row in range(1,max+1): print(end="%2i" %row) for column in range(1, max + 1): product = row*column; # Compute product print("\n",end="%2i " % product) # Display product print()
true
64c73e0bdd339d3cdcd6d19a52cb8748e3ea2e33
saitejmandalapu/Problem-Solving-and-Programming-in-Python
/max.py
347
4.21875
4
#finding Maximumber #A value a=int(input("Enter the value of a")) #B value b=int(input("Enter the value of b")) #C value c=int(input("Enter the value of c")) #finding through IF condition if a>b and a>c: print("a is maximum:",a) elif b>a and b>c: print("b is Maximum number:",b) else : print("c is maximum:",c)
true
2b7bd3d197ba217dfd859efbd7b3edddaf9d6399
arnoringi/forritun
/Assignment 9 (Files and exceptions)/9_1) Content of file in one line.py
406
4.125
4
def open_file(file_name): file_object = open(file_name, "r") return file_object def read_and_print(file_object): string = '' for line in file_object: line = line.strip().replace(" ", "") string += line print(string) # Main starts here def main(): file_name = input("Enter filename: ") file_object = open_file(file_name) read_and_print(file_object) main()
true
65807da8d1c0b0e41300a39eac0383e4b67589cd
arnoringi/forritun
/Assignment 9 (Files and exceptions)/9_4) Longest word.py
689
4.28125
4
# Your functions here def open_file(filename): try: file_object = open(filename) return file_object except: return None def find_longest(file_object): longest = '' for line in file_object: if len(line) > len(longest): line = line.strip() longest = line else: continue return longest # Main program starts here filename = input("Enter filename: ") file_object = open_file(filename) if file_object: longest_word = find_longest(file_object) print("Longest word is '{:s}' of length {:d}".format(longest_word, len(longest_word))) file_object.close() else: print("File not found")
true
9d1679be38c21021a12f3aba24fa23735e212af5
atulgolhar/python
/generatorMethods.py
1,720
4.1875
4
Generator Methods pg 184 # We may supply generators with values after they have started running, by using a communications channel # between the generator and the "outside world" with the following two end points: # (1) 'send' method --> the outside world has access to a method on the generator called 'send' # which works just like 'next' # except that it 'send' takes a single argument # (the 'message' to send to the generator -- ie 'message' is an arbitrary object). # (2) 'yield' method inside the suspended generator, 'yield' may now be used as as "expression", # rathar that a "statement" # In other words, when the generator is resumed, 'yield' returns a value. # And that value is sent from the outside through 'send'. # If 'next' was used, 'yield' returns "None". # Note that using 'send' (rather than 'next') makes sense only after the generator has been suspended # (that is, after it has hit the first 'yield'). # If you need to give some information to the generator before that, you can simply use the parameters # of the generator function. # TIP If you really want to use 'send' on a newly started generator, you can use it with 'None' as its parameter. # silly example # Note use of parentheses are around 'yield' expression. # While not strictly necessary in some cases, it is probably better to be safe than sorry and thus simply # always enclose 'yield' expressions in () if you are using the return value in some way >>> def repeater(value): while True: new = (yield value) if new is not None: value = new >>> >>> r = repeater(42) >>> next(r) 42 >>> >>> r.send("Hello World How Are You?") 'Hello World How Are You?' >>>
true
ac15ba28978ef0dfcf828c3e1039e6b5c8bc04e4
aveirinha/210CT-Coursework
/week3_ex2_basic.py
858
4.25
4
#Time complexity: O(n) def linearSearch(num_list, target): """This function receives a list of integer and the value it needs to find. It is called recursively until gets to the target value or to the endo of the list. If the value is found it returns true if not it returns false""" if (len(num_list)>= 1): if (num_list[0] == target): #value was found print('Found') return True elif (len(num_list) == 1): #reached the end of the list print('Not Found') return False else: #method calls itself again starting on the second element num_list.pop(0) return(linearSearch(num_list, target)) def main(): l = [3,5,7,1,2,9] t = 9 linearSearch(l, t) if __name__ == "__main__": main()
true
d403fe8f4312db22a56a2532a1f5f6a1401ec4f2
GrubcChan/Historical_ciphers
/main.py
2,124
4.1875
4
# 23.09.2021 # Решётка Кардано # Работу выполнил: Грубов Михаил Дмитриевич from CardanoLattice import CardanoLattice def main(): print('Enter text to encrypt: ', end=' ') message = input() myth = CardanoLattice(message) print('To encrypt Enter:\t\t\t\t\'enc\';\nTo decrypt Enter:\t\t\t\t\'dec\';\nTo print on display, ' 'Enter:\t\t\t\'print\';\nTo replace the message Enter:\t\t\t\'replace\';\nTo start cryptanalysis of the ' 'system, enter:\t\'analysis\'\nFor help information, ' 'Enter:\t\t\t\'help\'\nTo exit Enter:\t\t\t\t\t\'exit\';') check_out = True check_encrypt = False while check_out: print('>>>', end=' ') code = input() if code == 'enc': if not check_encrypt: myth.encrypt() check_encrypt = True else: print('The message is already encrypted!') elif code == 'dec': if check_encrypt: myth.decoder() check_encrypt = False else: print('The message is already decrypted!') elif code == 'print': print(myth.message) elif code == 'replace': print('Enter text to encrypt: ', end=' ') message = input() myth = CardanoLattice(message) elif code == 'exit': check_out = False elif code == 'analysis': if check_encrypt: myth.analysis() check_encrypt = False else: print('The message is already decrypted!') elif code == 'help': print('To encrypt Enter:\t\t\t\t\'enc\';\nTo decrypt Enter:\t\t\t\t\'dec\';\nTo print on display, ' 'Enter:\t\t\t\'print\';\nTo replace the message Enter:\t\t\t\'replace\';\nTo start cryptanalysis of ' 'the system, enter:\t\'analysis\'\nFor help information, ' 'Enter:\t\t\t\'help\'\nTo exit Enter:\t\t\t\t\t\'exit\';') else: print('Enter the correct code!') if __name__ == '__main__': main()
false
5800394f4deb9873860790e4105238630b31eb05
ram89toronto/1kpythonrun
/15.py
377
4.5
4
# Write a python to caluclate the area of circle using math package # import required packages import math # input variables r = float(input(" Enter the radius of Circle :")) # logic area = math.pi * r ** 2 # Display of output print(" The area of circle is {}".format(area)) #Expressing the area till two decimal points print(" The area of circle is {:0.2f}".format(area))
true
86b66682adac7747d05a3db63d9ac4f81782a8b4
ram89toronto/1kpythonrun
/23.py
325
4.4375
4
# Write a program to search for an element in th list of elements using for-else # input variable group1 = [2,3,4,5,6,7,8] search = int(input("Enter a number to search :")) #logic for element in group1: if search == element: print("Element found") break else: print("entered number is not in list")
true
731376b1fd0bc93cc039a8fc0a9978ee87dd2c0d
ram89toronto/1kpythonrun
/18.py
303
4.40625
4
# Write a program to find given number is a postive, negative or zero using if ,elif & else # input variables n = int(input("Enter a number :")) # Logic & display if n==0: print(" Given number is Zero") elif n>0: print(" Given number is positive") else: print(" Given number is negative")
true
da14457c13289cd2efe157d4abd4af34d9b6d76e
reginaalyssa/CS50-Psets
/pset6/vigenere.py
1,653
4.40625
4
import sys import cs50 def main(): """ Encrypts a message using Vigenere's cipher. Usage: vigenere k Input p where k is an alphabetical string that serves as the key. Each character in k corresponds to a number (A and a as 0, B and b as 1, ..., and Z and z as 25) and where p is the string or message to be encrypted. """ # ensure valid arguments if len(sys.argv) != 2 or not sys.argv[1].isalpha(): print("Usage: python vigenere.py k") exit(1) # key must be all alphabetical k = sys.argv[1] # get message to encrypt print("plaintext: ", end="") p = cs50.get_string() # number of characters rotated/shifted in message shift_count = 0 print("ciphertext: ", end="") # traverse through each character in plaintext for c in p: # if character is alphabetical, shift it if c.isalpha(): c = rotate(c, k, shift_count) shift_count += 1 print(c, end="") print("") def rotate(c, k, shift_count): """ Returns character c rotated by k[i] positions where i is within the range [0, len(k) - 1]. """ i = shift_count % len(k) msg_f = get_first_letter(c) key_f = get_first_letter(k[i]) c = ord(c) key = ord(k[i]) return chr(((c - msg_f + key - key_f) % 26) + msg_f) def get_first_letter(c): """ Returns ASCII of the first letter of the alphabet depending on case. Returns ASCII of "a" if lowercase; "A" if uppercase. """ if c.islower(): return ord("a") else: return ord("A") if __name__ == "__main__": main()
true
8671b79d52a1e1a2ec322e6071b4efd07a1214a8
sophiezhng/CS50-Harvard-Problem-Set-Solutions
/pset7/houses/roster.py
871
4.125
4
# TODO import csv import sys from cs50 import SQL # Import the SQL database db = SQL("sqlite:///students.db") # Begin by checking the command-line arguments if len(sys.argv) != 2: print("missing command-line argument") exit(1) house = sys.argv[1] # Select students from correct house table = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ?", house) # Sort the students by last and then first name table.sort(key=lambda x: (x['last'], x['first'])) # Iterate through list of dictionaries for row in range(len(table)): temp_dict = table[row] # Check if students have middle names or not if temp_dict["middle"] == None: print(f"{temp_dict['first']} {temp_dict['last']}, born {temp_dict['birth']}") else: print(f"{temp_dict['first']} {temp_dict['middle']} {temp_dict['last']}, born {temp_dict['birth']}")
true
827fc3982530369752ca8770c971e229c8292b71
DAPLEXANDER/UFFTESTING
/Numbers greater.py
321
4.125
4
num1 = int(input("Enter the number1: ")) num2 = int(input("Enter the number2: ")) num3 = int(input("Enter the number3: ")) if((num1>num2)& (num1>num3)): print(num1,"IS THE GREATES") elif((num1>num2)& (num1>num3)): print(num2, "Is the greates among the three") else: print(num3,"Is the greated among the three") input()
false
85e092dcd20c1c82b4d6101e02ef902c32c398d5
JoseAntonioVazquezGabian/Tarea_03
/pago trabajador.py
1,199
4.1875
4
#encoding-UTF-8 #AUTOR: José Antonio Vázquez Gabián #Este programa calcula el pago de una trabajador por horas normales, horas extras y el total de pago. #En esta funcion calculamos los pagos de un trabajador en jornada normal def calcularpagoNormal(horasN, pago): pagoNormal = horasN * pago return pagoNormal # Calcula el pago por horas extras del trabajador def calcularpagoExtra(HorasE, pago): pagoExtra = HorasE * (pago * 1.5) return pagoExtra # Calcula el pago total def calcularpagototal(pagoN, pagoE): pagoTotal = pagoN+pagoE return pagoTotal # Esta función main llama a las funciones anteriores e imprime el pago normal, el pago extra y el pago total. def main(): horasN = float(input("Teclea las horas normales trabajadas: ")) horasEx = float(input("Teclea las horas extras trabajadas: ")) pago = float(input("Teclea el pago por hora: ")) pagoNormal = calcularpagoNormal(horasN,pago) pagoExtra = calcularpagoExtra(horasEx,pago) pagoTotal = calcularpagototal(pagoNormal,pagoExtra) print("") print("Pago normal: $%.2f" %(pagoNormal)) print("Pago extra: $%.2f" %(pagoExtra)) print("-----------------------") print("Pago total: $%.2f" %(pagoTotal)) main()
false
e949f7daa0f5fc771a624c344daa91595b4b090a
Titash21/Python-Representation-of-LinkedList
/linkedList_reverse.py
2,196
4.3125
4
class Node: def __init__(self,data): self.data=data self.next=None class Linked_List: def __init__(self): self.head=None #Insert the data at the front of the Linked_List def insert_at_front(self,data): new_node=Node(data) if self.head==None: self.head=new_node else: new_node.next=self.head self.head=new_node #Delete the data if present in the linked list def reverse_linkedList(self): if self.head==None: print(None) else: p=self.head r=None while(p.next!=None): q=p p=p.next q.next=r r=q p.next=r self.head=p def reverse_linkedList_recursive(self,head): if self.head: reverse_linkedList_recursive(self.head.next) print(self.head.data) def prints(self): if self.head==None: print("Empty linked list") else: current=self.head while current: print(current.data) current=current.next objects=Linked_List() def main(): print("OPTIONS FOR THIS PROGRAM") print("1. To insert at front") print("2. Reverse a particular list non recursively") print("3. Reverse a particular list recursively") print("4. Print contents of the linked list") choice=int(input("Enter now: ")) if (choice>4): print("Wrong input! Exiting..........") else: driver_function(choice) def driver_function(choice): if(choice==1): value=int(input("enter data to add in front: ")) objects.insert_at_front(value) objects.prints() elif(choice==2): objects.reverse_linkedList() objects.prints() elif(choice==3): objects.reverse_linkedList_recursive() objects.prints() elif(choice==4): objects.prints() loops=int(input("want to enter again? then print 1 or 0: ")) if(loops==1): main() else: objects.prints() main()
true
e3edd7e0918d741d962459890e1a78a11ad4fd4a
anaerobeth/dev-sprint4
/chap10.py
1,942
4.25
4
#This is where the answers to Chapter 10 questions for the BSS Dev RampUp go # Name: Elizabeth Tenorio #Ex. 10.7 print "This program takes two strings and returns True if they are anagrams" # Sort the letters in a given word def sort_string(word): new_word = list(word) new_word.sort() new_word = ''.join(new_word) return new_word # Compare the sorted words to check for anagrams def is_anagram(first, second): sortf = sort_string(first.lower()) sorts = sort_string(second.lower()) if sortf == sorts: return True else: return False print is_anagram('star', 'rats') print is_anagram('dog', 'cat') print is_anagram('Star', 'Rats') # Ex. 10.13 # Write a program that finds all pairs of words that interlock def interlocked(first, second): third = [] f = list(first.lower()) s = list(second.lower()) f = list(reversed(f)) s = list(reversed(s)) for i in range(len(f)): third += f.pop() third += s.pop() thirdword = ''.join(third) print thirdword for line in open('words.txt'): #print line allwords = line.strip().lower() #print allwords if thirdword == allwords: return True break #print interlocked('dogs', 'cats') print interlocked('shoe', 'cold') print 'Done!' def threeway(): wordlist = [] for line in open('words.txt'): word = line.strip() wordlist.append(word) for line in open('words.txt'): word = line.strip() #print word #print word[0::3] if word[0::3] in wordlist: if word[1::3] in wordlist: if word[2::3] in wordlist: print 'Three-way interlock found!' print word print word[0::3] print word[1::3] print word[2::3] print threeway() #Three-way interlock found! #abacuses #ace #bus #as
true
508f042e6bf51ac81d91e449f7cf4944c591acf3
Bhavan24/Temperature_converter_python
/Temp.py
869
4.125
4
print(''' 1.Celsius to Fahrenheit 2.Celsius to Kelvin 3.Fahrenheit to Celsius 4.Fahrenheit to Kelvin 5.Kelvin to Celsius 6.Kelvin to Fahrenheit ''') temp = int(input("Enter your choice: ")) if temp == 1: c = float(input("Enter centigrade: ")) f = (c * 1.8) + 32 print(f, "*F") elif temp == 2: c = float(input("Enter centigrade: ")) k = c + 273.15 print(k, " K") elif temp == 3: f = float(input("Enter fahrenheit: ")) c = (f - 32) / 1.8 print(c, "*C") elif temp == 4: f = float(input("Enter fahrenheit: ")) c = (f - 32) / 1.8 k = c + 273.15 print(k, " K") elif temp == 5: k = float(input("Enter kelvin: ")) c = k - 273.15 print(c, "*C") elif temp == 6: k = float(input("Enter kelvin: ")) c = k - 273.15 f = (c * 1.8) + 32 print(c, "*F") else: print("Invalid option entered")
false
8192c5b6e6165e55a17a2bf10ba1d433d4f35e2a
shayany/Python_Assignment
/week3/circle.py
650
4.34375
4
from math import pi class Circle(object): """ This class get radius in its constructor and can calculate and return the area and perimeter of the circle. """ def __init__(self,radius=10): """ constructor get radius which has a default value of 10 and assign that value to the local variable """ self.radius=radius def area(self): """ area: returns computed area of the circle """ return pi*self.radius*self.radius def perimeter(self): """ perimeter: returns computed perimeter of the circle """ return 2*pi*self.radius
true
f412021480c56f26db0ef9e695bf7a0b8e3b659a
MAlamGit/MyDEVOPSWork
/pythonLearn/pythonLearn.py
958
4.15625
4
# File: pythonLearn.py a = 100 b = 50 i = 1 #x = 8 #x = x + 3 fruitList = ["apple", "banana", "cherry"] fruitList[1] = "blackcurrant" print("Added at second place--> blackcurrant") print(fruitList) print(len(fruitList)) print\ fruitList.append("orange") print("Append--> orange") print(fruitList) print(len(fruitList)) print\ fruitList.insert(1, "mango") print("Insert--> mango") print(fruitList) print(len(fruitList)) print\ fruitList.remove("cherry") print("Remove--> cherry") print(fruitList) print(len(fruitList)) print\ fruitList.pop() print("POP--> last element deleted") print(fruitList) print(len(fruitList)) print\ for x in fruitList: print(x) if "apple" in fruitList: print("Yes, 'apple' is in the fruits list") else: print("Not available") if "mango" in fruitList: print("Yes, 'apple' is in the fruits list") else: print("Not available") if b > a: print ("True") else: print ("False") while i < 6: print(i) i += 1
true
c8fcef0aa659311796b80cfe0bc37156cef8f56a
DebadityaShome/Coders-Paradise
/Python/Level 0/hashtables.py
261
4.5
4
items1 = dict({"key1" : 1, "key2" : 2, "key3" : "three"}) print(items1) print(items1["key2"]) items1["key2"] = "two" print(items1) # Iterating the keys and values in the dictionary for key, value in items1.items(): print("Key: ", key, " value: ", value)
true
e703d0603fbfaae6bb4c6323c3d61346f965c247
ashehta700/PythonTutorial
/lists.py
1,445
4.1875
4
# ####################lists # The most basic data structure in Python is the sequence. # Each element of a sequence is assigned a number - its position or index. # The first index is zero, the second index is one, and so forth. # Python has six built-in types of sequences, # but the most common ones are lists and tuples. # The list is a most versatile datatype available in # Python which can be written as a list of comma-separated values (items) between square brackets. # Important thing about a list is that items in a list need not be of the same type. newlist=[] newlist=['welcome', 455.55, True] print(newlist[0]) myList = ["C", "JavaScript", "Python", "Java", "php"] print (myList) #pop myList.pop(4) print (myList) myList.pop(2) print (myList) #append adds at the end of the list myList.append('hi') print(myList) #insert at certain index myList.insert(3, "Scala") print(myList) #remove certain item myList.remove('hi') print(myList) #extend the list add item to it yourList = ["Ruby", "Rust"] myList.extend(yourList) print(myList) #List operations #1-length print (len([1, 2, 3])) #2- concatenation x=[1, 2, 3] + [4, 5, 6] print(x) #3- Repetition y= ['Python!'] * 4 print(y) #4- membership print (3 in [1, 2, 3]) #true #5- iteration for x in [1, 2, 3]: print (x) #6- min print(min([10, 20, 30])) #7- max print(max([10, 20, 30]))
true
acebf24432067cee58eedd3972e8619e3ca02c85
jpmcb/interview-problems
/udemyPyInterview/recursion/reverse.py
207
4.3125
4
# Using recursion, reverse a given string def reverse(s): if len(s) == 1: return s # Slice the string from 2nd to last index return reverse(s[1:]) + s[0] print(reverse('hello world'))
true
8e6a05750706a43d5f2824912a18098e18195856
jpmcb/interview-problems
/udemyPyInterview/arrays/anagram.py
1,431
4.28125
4
# Given two strings, check to see if they are anagrams. # An anagram is when the two strings can be written using the exact same # letters (so you can just rearrange the letters to get a different phrase or word). # For example: # "public relations" is an anagram of "crap built on lies." # "clint eastwood" is an anagram of "old west action" # Note: Ignore spaces and capitalization. So "d go" is an anagram of "God" and "dog" and "o d g". # This solution manually checks for spaces as the dictonary is built # the strings could also be manually have their white space removed as in anagram_sorted def anagram(x, y): dict = {} for char in x: if char not in dict and char is not ' ': dict[char] = 1 elif char is not ' ': dict[char] += 1 for char in y: if char not in dict and char is not ' ': return False elif char is not ' ': dict[char] -= 1 for key in dict: if dict[key] is not 0: return False return True # not the optimal solution as timsort is O(n log n) # However, this is the optimal memory size solution def anagram_sorted(x, y): x = x.replace(' ', '').lower() y = y.replace(' ', '').lower() return sorted(x) == sorted(y) print(anagram('clint eastwood', 'old west action')) print(anagram('clint eastgood', 'old west action')) print(anagram(' d o g ', ' g o d '))
true
61668f587e776ff39d72d65f1aec7f98ad72488f
Jlow314/Learning_Python_from_Corey
/Less5 - Working with key-value pairs.py
944
4.28125
4
student = {"name": "John", "age": 25, "courses": ["Art", "Math"]} print(student) print(student["name"]) # keys can be anything immutable: integer, lfoat, string. Here str is used # values can be about anything # print(student["phone"]) print(student.get("name")) print(student.get("phone")) print(student.get("phone", "DOES NOT EXIST")) student["phone"] = "555 - 5555" print(student["phone"]) print(student.get("phone", "DOES NOT EXIST")) student["name"] = "Jane" print(student) student.update({"age": 27, "courses": ["Science", "Latin"], "phone": "444-4444"}) print(student) del student["age"] print(student) student.update({"age": 28}) print(student) age = student.pop("age") print(age) print(student) print(len(student)) print(student.keys()) print(student.values()) print(student.items()) for key in student: print(key) for value in student.values(): print(value) for key, value in student.items(): print(key, value)
true
0941123829243f4e7ff87733cf3c75292d7342d3
jalicea/mtec2002_assignments
/class9/labs/winter_scene.py
1,906
4.40625
4
""" winter_scene.py === Using the drawing and animation techniques we learned create an animation of snow falling. 1. Copy the boilerplate code from the template exercise - hello_pygame.py. 2. Incorporate the code from multiple_objects.py to create the snow: a. However, in the setup, rather than use 0 for the initial y value, use a random value b. In the main loop, when iterating over the circles, check if the y value is greater than the window width (see screen_wrap.py) c. If the y value is greater... then bring the circle back up to the top 3. (INTERMEDIATE) Incorporate random lateral motion. Try adding a unique velocity for x and y for each circle by expanding your two element list! You can also use a dictionary if it makes more sense than a list with indexes. """ import pygame FRAME_RATE = 100 WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 WINDOW_TITLE = "My Game" background_color = (001, 001, 001) running = True pygame.init() screen = pygame.display.set_mode([WINDOW_WIDTH, WINDOW_HEIGHT]) pygame.display.set_caption(WINDOW_TITLE) clock = pygame.time.Clock() while running == True: # stop the main loop when window is closed for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill(background_color) # draw everything here! this line draws a circle in the middle of the screen pygame.draw.circle(screen, (200, 200, 200), (WINDOW_WIDTH / 5, WINDOW_HEIGHT / 1), 75) pygame.draw.circle(screen, (200, 200, 200), (WINDOW_WIDTH / 5, WINDOW_HEIGHT / 1.5), 25) pygame.draw.circle(screen, (200, 200, 200), (WINDOW_WIDTH / 5, WINDOW_HEIGHT / 1.25), 50) pygame.draw.circle(screen, (001, 001, 001), (WINDOW_WIDTH / 5.5, WINDOW_HEIGHT / 1.52), 5) pygame.draw.circle(screen, (001, 001, 001), (WINDOW_WIDTH / 4.5, WINDOW_HEIGHT / 1.51), 5) clock.tick(FRAME_RATE) pygame.display.flip() # exit when we're done with the loop pygame.quit()
true
0b8dc31ee5bd2796ccaf5e84f1afbfe9b98c0d3c
jalicea/mtec2002_assignments
/class7/labs/fortune_teller.py
1,313
4.21875
4
""" fortune_teller.py === 1. Create a list of fortunes: 'you will write a program', 'you have a lot of tabs in your future', 'boo!' and store it in a variable called fortunes 2. Use random to print out a random fortune when you run the program 3. Run the program several times Expected Output: $ python fortune_teller.py boo! $ python fortune_teller.py you have a lot of tabs in your future $ python fortune_teller.py you have a lot of tabs in your future """ import random lof = ["You will write many programs in your future", "you will eat a cookie...a forture cookie", "You will never know the magic word", "The sun rises in the east and beats your ass in the west", "You will break it and you will buy it", "Your assumptions are wrong", " If a pigeon poops on you, do not blame the pigeon, blame the poop.", "Ninety-five percent of the things you worry about will never happen. The other five percent will kill you.", "You are sitting on gum.", "The lesser of two evils is still evil.", " Ancient Chinese secret: You're screwed.", "I know I am, but what am I? —Descartes, on the playground", " Be decisive. Maybe. If you want to.", "If a man slaps you in the face, turn the other cheek and shoot him.","2,390,670,980 fortunes=one tree. Please recycle."] index = random.randint(0,11) print lof[index]
true
cb7536f745dfafd67dedd2de9cc0c3cc422361d5
pdcodes/PythonLearnings
/Basics/stringformatting.py
602
4.375
4
# String formatting user_input = input("Enter your name: ") message = "Hello %s!" % user_input message2 = f"Hello, {user_input}." # The f"String {}" approach only works for Python 3.6+" print(message, "\n", message2) # String formatting with multiple variables name = input("Enter your first name: ") surname = input("Enter your last name: ") new_message = "Hello %s %s!!" % (name, surname) print(new_message) # Take the user input and convert to a float # user_input = float(input("Enter temperature: ")) # print(weather_condition(user_input)) # You can also convert a value to an int using int()
true
51fa6f3fccc4c3c71f2f80c065cf6d55c0787276
jakemat29/python_repo
/ex19.py
229
4.1875
4
"""for loop and lists""" count = [1, 2, 3, 4, 5] fruits=["apple", "orange", "grape","papaya"] for i in count: print i for i in fruits: print i elements= [] for i in range(0,6): elements.append(i) for i in elements: print i
false
cf7d0c3e09a089b24c1f3f9696351a432534d992
makakin/learn-python
/core-python-programming/chapter.07/mapping.py
1,385
4.25
4
""" mapping is a disorder type hash() can judge if the value you passed can be a key in dict sorted() can sort a dict """ __author__ = 'weixy6' def dividingLine(): print '-' * 20 dict1 = {} dict2 = {'name': 'zhangsan', 'age': 28} # use factory method to create dict(after python 2.2) fdict = dict((['x', 1], ['y', 2])) # use BIF to create dict which contains the same value, default value is None ddict = {}.fromkeys(('x', 'y'), -1) ddict2 = {}.fromkeys(('x', 'y')) print dict1, dict2, fdict, ddict, ddict2 for key in dict2.keys(): # for key in dict2: # after python 2.2, you can do it this way print dict2.get(key), # or dict2[key] print # add element dict1[1] = 'hello' dict1[2] = 'world' dict1[3] = '!' print dict1 dividingLine() # update element dict1[2] = 'python' print dict1 dividingLine() # delete element or dict del dict1[1] dict1.pop(2) print dict1 dict1.clear() print dict1 del dict1 dividingLine() # factory function dict() print dict(zip(('x', 'y'), (1, 2))) print dict([['x', 'y'], [1, 2]]) print dict([('xy'[i - 1], i) for i in range(1, 3)]) dividingLine() print dict(x=1, y=2, z=[3, 4]) dividingLine() dict3 = dict2.copy() print dict3 # print hash([2, 3]) # TypeError: unhashable type: 'list' print dict3.items() print dict3.keys() print dict3.values() dividingLine() for key in sorted(dict3): print key, dict3[key]
true
38ccafc298cbab2b232e41c6e7496b574974c762
OrdinaryCoder00/CODE-WARS-PROBLEMS-SOLUTIONS
/8Kyu - How old will I be in 2099?.py
534
4.15625
4
def calculate_age(year_of_birth, current_year): #your code here age = current_year - year_of_birth if(year_of_birth>current_year and age == -1): return 'You will be born in {} year.'.format(abs(age)) elif(year_of_birth<current_year and age == 1): return 'You are {} year old.'.format(age) if(age<0): return 'You will be born in {} years.'.format(abs(age)) elif(age>0): return 'You are {} years old.'.format(age) else: return 'You were born this very year!'
false