blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6a6a06d047a95ed76a60ed9f2392016f6d379ccf
motleytech/crackCoding
/arraysAndStrings/urlify.py
1,506
4.34375
4
''' Replace all spaces in a string with '%20' We can do this easily in python with the string method 'replace', for example to urlify the string myurl, its enough to call myurl.replace(' ', '%20') Its that simple. To make the task a little more difficult (to be more in line with what the question expects), we will convert the string into a list of characters. Our task will now be to return ['a', '%', '2', '0', 'b'] when given an input ['a', ' ', 'b'] ''' def urlify(s): ''' replace spaces in s with %20... the C/Java way ''' # convert string into list of characters s = [c for c in s] # count number of spaces ns = sum(1 for c in s if c == ' ') # get length of string ls1 = len(s) - 1 # add 2*ns empty spaces at the end of the list s.extend([' ']*(2*ns)) # get the new length ls2 = len(s) - 1 # move characters from end of string to end of list # while replacing space with %20 while ls1 >= 0: if s[ls1] == ' ': s[ls2] = '0' s[ls2-1] = '2' s[ls2-2] = '%' ls2 -= 3 else: s[ls2] = s[ls1] ls2 -= 1 ls1 -= 1 return ''.join(s) def test_urlify(): ''' Test the urlify method ''' print 'Testing URLify: ', assert urlify(' ') == '%20' assert urlify('a b') == 'a%20b' assert urlify('a b ') == 'a%20b%20' assert urlify('a b ') == 'a%20%20b%20' print 'Passed' if __name__ == '__main__': test_urlify()
true
edf168e27bffaa08a8f44733f3b55a524ff3052f
ZswiftyZ/Nested_Control_Structures
/Nested Control Structures.py
1,064
4.25
4
""" Programmer: Trenton Weller Date: 10.15.19 Program: This program will nest a for loop inside of another for loop """ for i in range(3): print("Outer for loop: " + str(i)) for l in range(2): print(" innner for loop: " +str(l)) """ Programmer: Trenton Weller Date: 10.22.19 Program: Average Test Scores This program asks for the test score for multiple peeople and reports the average test score for each portion """ num_people = int(input("How many people are taking the test?: ")) testperperson = int(input("How many tests are going to be averaged?: ")) for i in range(num_people): name = input("Enter Name: ") sum = 0 for j in range(testperperson): score = int(input("Enter a score: ")) sum = sum + score average = float(sum) / testperperson print(" Average for " + name + ": " + str(round(average, 2))) print("\n****************\n") """ Programmer: Trenton Date: 10.23.19 Program: This program will ask users of an interest to them theen ask for two items related to that interest """
true
fe6259b11728d674f4e31caef1a1d284bc2b225a
Harshhg/python_data_structures
/Arrays/alternating_characters.py
634
4.125
4
''' You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string. Your task is to find the minimum number of required deletions. For example, given the string AABAAB , remove an A at positions 0 and 3 o make ABAB in 2 deletions. Function that takes string as argument and returns minimum number of deletion ''' def alternatingCharacters(s): d=0 prev="None" for x in s: if x==prev: d+=1 else: prev=x return d
true
368a07b7981351a62e8090e04924e62e0a03bafa
Harshhg/python_data_structures
/Graph/py code/implementing_graph.py
1,481
4.28125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Implementing Graph using Adjacency List from IPython.display import Image Image("graph.png") # In[6]: # Initializing a class that will create a Adjacency Node. class AdjNode: def __init__(self,data): self.vertex = data self.next = None # In[15]: # A class to represent the graph class Graph: def __init__(self,vertices): self.V = vertices self.graph = [None] * self.V # Function to add an EDGE to the undirected graph # Adding the node to the source def addEdge(self, src, dest): node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the node to the Destination (since it is undirected graph) node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the Graph def printGraph(self): for i in range(self.V): print("Adjacency list of vertex {}\n head".format(i), end="") temp = self.graph[i] while temp: print(" -> {}".format(temp.vertex), end="") temp = temp.next print(" \n") # In[16]: # Driver Program V = 5 graph = Graph(V) graph.addEdge(0, 1) graph.addEdge(0, 4) graph.addEdge(1, 2) graph.addEdge(1, 3) graph.addEdge(1, 4) graph.addEdge(2, 3) graph.addEdge(3, 4) graph.printGraph() # In[ ]: # stay Tuned :)
true
6d9e626308c9d866e15c071a6b0e74a3f38eeda5
NiklasAlexsander/IN3110
/assignment3/wc.py
2,168
4.40625
4
#!/usr/bin/env python import sys def main(): """Main function to count number of lines, words, and characters, for all the given arguments 'filenames' given. A for-loop goes through the array of arguments given to wc.py when run from from the terminal. Inside the loop each argument will be 'open' for read-only. Our needed variables will be made and a 'with' will be called containing the open files. A for-loop will go through each line of a file. The counting of lines, words, characters, and spaces will be done in this loop. To get the count of the lines we count one '1' on each iteration. We split the lines at spaces ' ' and count the length to find the wordcount. We find the count of the characters by finding the length of the line and subtracting the amout of spaces in the line and subtract to count for the newline at the end of each line. At the end we print the result as a human-readable string to the default output. Note: The 'with' keyword is being used as it will clean the file-opening regardless of the code gets done, or if it fails, gets interrupted, or exceptions are thrown. Args: argv(array): Array containing all arguments given as strings. Expecting filenames or filepaths. Attributes: lineCounter (int): Variable to keep track of the number of lines wordCounter (int): Variable to keep track of the number of words characterCounter (int): Variable to keep track of the number of characters spaces (int): Variable to keep track of the number of spaces """ if __name__ == "__main__": for path in sys.argv[1:]: file = open(path, 'r') lineCounter = wordCounter = characterCounter = spaces = 0 with file as f: for line in f: lineCounter+=1 wordCounter+= len(line.split()) characterCounter+=len(line)-line.count(' ')-line.count('\n') spaces += line.count(' ') print(f"{lineCounter} {wordCounter} {characterCounter} {path}") main()
true
5d86b8b02a006566aefd819c9249151916514c82
TECHNOCRATSROBOTICS/ROBOCON_2018
/Computer Science/Mayankita Sisodia/ll.py
1,564
4.53125
5
# TO INSERT A NEW NODE AT THE BEGINNING OF A LINKED LIST class Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data to the node. self.next = None # Initialize next as null so that next of the new node can be made the head of the linked list class LinkedList: # Function to initialize the Linked List object def __init__(self): self.head = None #Assign head of linked list as null. def push(self, new_data): new_node = Node(new_data) # creating object of class node, which is the new node to be inserted new_node.next = self.head # making the next of new node as head of linked list self.head = new_node # making head of list to point at new node def PrintList( self ): node = self.head # assigning head to a variable node while node != None: #until node is not null print (node.data) # print the data of the node node = node.next #move to the next of the current node l=LinkedList() #object of class LinkedList l.push(5) # push function to insert elements in the beginning l.push(6) l.push(7) l.PrintList()
true
dca26a9e0cc1952bd168baae5621036c8ac19e8d
TECHNOCRATSROBOTICS/ROBOCON_2018
/Computer Science/Mayankita Sisodia/tree.py
1,955
4.28125
4
class Node: def __init__(self, val): #constructor called when an object of class Node is created self.left = None #initialising the left and right child node as null self.right = None self.data = val # data of each object/node def insert(self, data): if self.data: #if current root is not null if data < self.data: # if the new data to be inserted is less than the the root, assign data to the left node if the left node is empty if self.left is None: self.left = Node(data) else: #if the left node is filled, insert data to one of the child nodes of it. self.left.insert(data) elif data > self.data: # if the new data to be inserted is greater than the the root, assign data to the right node if the right node is empty if self.right is None: self.right = Node(data) else: #if the right node is filled, insert data to one of the child nodes of it. self.right.insert(data) else: # if node of given root is null, insert data at the root self.data = data def search(self,key): if self.data==key: # root is key itself print(self.data) elif self.data<key: # key is greater than given root, compare with the right node search(self.right,key) else: # if key is lesser than the given root, compare with the left node. search(self.left,key) r = Node(3) r.insert(2) r.insert(4) r.insert(5) r.search(5)
true
818f452713e6fce3908f59df610f6a9e4dd073b9
mo2274/CS50
/pset7/houses/import.py
1,508
4.375
4
from sys import argv, exit import cs50 import csv # check if the number of arguments is correct if len(argv) != 2: print("wrong argument number") exit(1) # create database db = cs50.SQL("sqlite:///students.db") # open the input file with open(argv[1], "r") as characters: # Create Reader reader_csv = csv.reader(characters) # skip the first line in the file next(reader_csv) # Iterate over csv for row in reader_csv: # get the name of the character name = row[0] # counter for the number of words in the name count = 0 # check if the name is three words or two for c in name: if c == ' ': count += 1 # if the name contain three words if count == 2: # split the name into three words name_list = name.split(' ', 3) first = name_list[0] middle = name_list[1] last = name_list[2] # if the name contain two words if count == 1: # split the name into two words name_list = name.split(' ', 2) first = name_list[0] middle = None last = name_list[1] # get the name of house house = row[1] # get the year of birth birth = int(row[2]) # insert the data into the table db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", first, middle, last, house, birth)
true
d56d83109a66b60b73160c4a45d770d01ef76274
Stuff7/stuff7
/stuff7/utils/collections/collections.py
1,021
4.1875
4
class SafeDict(dict): """ For any missing key it will return {key} Useful for the str.format_map function when working with arbitrary string and you don't know if all the values will be present. """ def __missing__(self, key): return f"{{{key}}}" class PluralDict(dict): """ Parses keys with the form "key(singular, plural)" and also "key(plural)". If the value in the key is 1 it returns singular for everything else it returns plural """ def __missing__(self, key): if "(" in key and key.endswith(")"): key, rest = key.split("(", 1) value = super().__getitem__(key) suffix = rest.rstrip(")").split(",") if len(suffix) == 1: suffix.insert(0, "") return suffix[0].strip() if value == 1 else suffix[1].strip() return f"{{{key}}}" def safeformat(string, **options): """ Formatting and ignoring missing keys in strings. """ try: return string.format_map(SafeDict(options)) except ValueError as e: return f"There was a parsing error: {e}"
true
68b0ed0774592899b32fc7838d54d9d361a05ff8
gevuong/Developer-Projects
/python/number_game.py
1,407
4.21875
4
import random def game(): # generate a random number between 1 and 10 secret_num = random.randint(1, 10) # includes 1 and 10 as possibilities guess_count = 3 while guess_count > 0: resp = input('Guess a number between 1 and 10: ') try: # have player guess a number guess = int(resp) except ValueError: print("{} is not an integer!".format(resp)) else: # compare player guess to secret number if guess == secret_num: print("You guessed it right! My number was {}!".format(secret_num)) play_again = input("Play again? y/n: ") if play_again == 'y': game() else: print('Ok bye!') break elif guess < secret_num: print("My number is higher than {}, guess again".format(guess)) guess_count -= 1 elif guess > secret_num: print("My number is lower than {}, guess again".format(guess)) guess_count -= 1 else: # runs when while loop finishes on its own, and when break or exception does not execute. print("You ran out of guesses. My number was {}!".format(secret_num)) play_again = input("Play again? y/n: ") game() if play_again == 'y' else print('Ok bye!') game()
true
8f8cb15ef494edb05050d9eb8e82047c89dd1ad1
chandrikakurla/inorder-traversal-using-stack-in-python
/bt_inorder traversal using stack.py
1,018
4.28125
4
#class to create nodes of a tree class Node: def __init__(self,data): self.left=None self.data=data self.right=None #function to inorder traversal of a tree def print_Inorder(root): #initialising stack stack=[] currentnode=root while True: #reach leftmost node of current if currentnode is not None: stack.append(currentnode) currentnode=currentnode.left elif(stack): currentnode=stack.pop() print(currentnode.data,end=" ") currentnode=currentnode.right else: #if currentnode is none and stack is empty then traversal is completed break #main programme if __name__=="__main__": root=Node(1) root.left=Node(2) root.right=Node(3) root.left.left=Node(4) root.left.right=Node(5) root.right.left=Node(6) root.right.right=Node(7) print("Inorder traversal of tree is:") print_Inorder(root)
true
1398699207d99c1fd94e7ed1e72fc3ec0cb661de
cvk1988/biosystems-analytics-2020
/assignments/01_strings/vpos.py
1,425
4.375
4
#!/usr/bin/env python3 """ Author : cory Date : 2020-02-03 Purpose: Find the vowel in a string """ import argparse import os import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('vowel', metavar='str', help='A vowel', choices=['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']) parser.add_argument('text', help='Some text', metavar='str', type=str, default='') return parser.parse_args() # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() vowel = args.vowel text = args.text #index =text.index(vowel) #text.index(vowel) if vowel in text: print(f'Found "{vowel}" in "{text}" at index {text.index(vowel)}.') else: print(f'"{vowel}" is not found in "{text}".') #print(f'Found "{vowel}" in "{text}" at index {index}.') if vowel in text else print(f'"{vowel}" not found') #print(index)) # -------------------------------------------------- if __name__ == '__main__': main()
true
d5ff9d18c1fdf3e489080b6925293d5626adae93
sideroff/python-exercises
/01_basic/exercise_024.py
363
4.25
4
def is_vowel(char: str): vowels = ('a', 'e', 'i', 'o', 'u') if len(string_input) > 1: print("More than 1 character received. Choosing the first char as default.") char = string_input[:1] print("Your char is a vowel" if char in vowels else "Your char is not a vowel") string_input = input("Choose a char: ") is_vowel(string_input)
true
58a9abb0dae2450fd180b6e00ae41748647b9176
sideroff/python-exercises
/various/class_properties.py
634
4.15625
4
# using property decorator is a different way to say the same thing # as the property function class Person: def __init__(self, name: str): self.__name = name def setname(self, name): self.__name = name def getname(self): return self.__name name = property(getname, setname) class DifferentPerson: def __init__(self, name): self.__name = name @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value p = DifferentPerson('Steve') # p = Person('Steve') print(p.name) p.name = 'Josh' print(p.name)
true
bd11a5ebbf2cdb102526ec1f39866c801e04ff54
ladamsperez/python_excercises
/Py_Gitbook.py
2,123
4.75
5
# # Integer refers to an integer number.For example: # # my_inte= 3 # # Float refers to a decimal number, such as: # # my_flo= 3.2 # # You can use the commands float()and int() to change from onte type to another: # float(8) # int(9.5) # fifth_letter = "MONTY" [4] # print (fifth_letter) # #This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem(for escaping characters), like this: # yee_yee = 'There\'s a snake in my boot!' # print(yee_yee) #len() The output when using this method will be the number of letters in the string. # parrot="Norwegian Blue" # len(parrot) # print (len(parrot)) # parrot="Norwegian Blue" # print(parrot.lower()) # parrot="Norwegian Blue" # print(parrot.upper()) # Now let's look at str(), which is a little less straightforward. # The str() method turns non-strings into strings. # pi=3.14 # pi=(str(pi)) # print(type(pi)) # #<class 'str'> # You can work with integer, string and float variables. # But don't mix string variables with float and integer ones when making concatenations: # width + "Hello" # # Sometimes you need to combine a string with something that isn't a string. # # In order to do that, you have to convert the non-string into a string using `str()``. # print("The value of pi is around " + str(3.14)) # The value of pi is around 3.14 # When you want to print a variable with a string, # there is a better method than concatenating strings together. # The %operator after a string is used to combine a string with variables. # The %operator will replace a %s in the string with the string variable that comes after it. # string_1= "Erle" # string_2= "drone" # print (" %s is an awesome %s" %(string_1, string_2)) # Erle is an awesome drone name = raw_input("What is your name?") color = raw_input("What is your favorite color?") print ("Ah, so your name is %s and your favorite color is %s." % (name, color)) name = raw_input("What is your name?") color = raw_input("What is your favorite color?") print "Ah, so your name is %s and your favorite color is %s." % (name, color)
true
8c650f2e69061c4d164e8028b41009512e47d715
ladamsperez/python_excercises
/task6_9.py
636
4.125
4
# Write a python function that takes a list of names and returns a new list # with all the names that start with "Z" removed. # test your function on this list: # test_list = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara'] test_list = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara'] def noznames(namelist): newlist = [] for name in namelist: if not name.startswith("Z"): newlist.append(name) print(newlist) noznames(test_list) # nosynames(name) # namelist = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara'] # namelist.strip(name.startswith("Z")) # print(namelist)
true
b3facc57e8f25fe47cbd1b12d94d98403d490c9a
GabrielCernei/codewars
/kyu6/Duplicate_Encoder.py
596
4.15625
4
# https://www.codewars.com/kata/duplicate-encoder/train/python ''' The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. ''' def duplicate_encode(word): result = "" word = list(word.lower()) for c in word: if word.count(c) > 1: result += ")" else: result += "(" return result
true
2811c2f7ad8732f43ab8498fb10ba05d8e6ad1e6
GabrielCernei/codewars
/kyu6/Opposite_Array.py
342
4.15625
4
# https://www.codewars.com/kata/opposite-array/train/python ''' Given an array of numbers, create a function called oppositeArray that returns an array of numbers that are the additive inverse (opposite or negative) of the original. If the original array is empty, return it. ''' def opposite_list(numbers): return [-i for i in numbers]
true
61e909280a67b37ae7f53ace4915e2ef3b51ba67
GabrielCernei/codewars
/kyu6/To_Weird_Case.py
859
4.5625
5
# https://www.codewars.com/kata/weird-string-case/train/python ''' Note: The instructions are not very clear on this one, and I wasted a lot of time just trying to figure out what was expected. The goal is to alternate the case on *EACH WORD* of the string, with the first letter being uppercase. You will not pass all of the tests if you alternate case based on the indexes of the entire string as a whole. eg. "This is a test string" should return "ThIs Is A TeSt StRiNg" ^ ^ ^ ^ ^ ^ ^ ^ ^ ''' def to_weird_case(string): starter = string.split() result = "" for index, char in enumerate(starter): for i, c in enumerate(char): if i == 0 or i % 2 == 0: result = result + (c.upper()) else: result = result + (c.lower()) result = result + " " return result.rstrip()
true
0e26c6bb0da2b0e5546e86aa6b2cb6ba09b27ccf
enajeeb/python3-practice
/PythonClass/answer_files/exercises/sorting.py
711
4.1875
4
# coding: utf-8 ''' TODO: 1. Create a function called sort_by_filename() that takes a path and returns the filename. - Hint: You can use the string's split() function to split the path on the '/' character. 2. Use sorted() to print a sorted copy of the list, using sort_by_filename as the sorting function. ''' paths = ['PythonClass/exercises/variadic.py', 'PythonClass/exercises/comprehensions.py', 'PythonClass/exercises/hello.py', 'PythonClass/exercises/exceptions.py', 'PythonClass/exercises/directory_iterator.py'] def sort_by_filename(path): segments = path.split('/') filename = segments[-1] return filename print sorted(paths, key = sort_by_filename)
true
c09cdf2e94f9060f285d01e110dc2fc48f2db496
enajeeb/python3-practice
/PythonClass/class_files/exercises/lists.py
688
4.34375
4
# coding: utf-8 ''' Lists Lists have an order to their items, and are changeable (mutable). Documentation: https://docs.python.org/2/tutorial/introduction.html#lists ''' # Square brackets create an empty list. animals = [] # The append() function adds an item to the end of the list. animals.append('cat') animals.append('frog') animals.append('bird') # To access an item in the list, indicate the item number in brackets. # Python lists are zero-based, meaning the first item is item #0. first = animals[0] # Negative numbers index from the end of the list, so -1 is the last item in the list. last = animals[-1] # You can change an item in the list. animals[1] = 'swallow'
true
cffa20e72d74c07324bac4fdd490bac5218dae9a
enajeeb/python3-practice
/PythonClass/class_files/exercises/functions.py
552
4.40625
4
# coding: utf-8 ''' Useful functions for the Python classs. ''' ''' TODO: 1. Create a function called words(). 2. The function should take a text argument, and use the string's split() function to return a list of the words found in the text. The syntax for defining a function is: def func_name(argument1, argument2): # code return result ''' def get_words(arg1): '''This is my test function''' words = arg1.split() count = len(words) return words, count # print get_words('Hello monty python')
true
dd18b7dbf8cf814f889a497c4565dcb3b1d12719
drnodev/CSEPC110
/meal_price_calculator.py
1,349
4.15625
4
""" File:meal_price_calculator.py Author: NO Purspose: Compute the price of a meal as follows by asking for the price of child and adult meals, the number of each, and then the sales tax rate. Use these values to determine the total price of the meal. Then, ask for the payment amount and compute the amount of change to give back to the customer. """ child_price = float(input("What is the price of a child's meal? ")) adult_price = float(input("What is the price of an adult's meal? ")) child_number = int(input("How many children are there? ")) adult_number = int(input("How many adults are there? ")) tax_rate = float(input("What is the sales tax rate? ")) subtotal = (child_number * child_price) + (adult_number * adult_price) sales_tax = subtotal * (tax_rate / 100) total = subtotal + sales_tax #print results print(f"\nSubtotal: ${subtotal:.2f}") print(f"Sales Tax: ${sales_tax:.2f}") print(f"Total: ${total:.2f}") payment = float(input("\nWhat is the payment amount? ")) print(f"Change: ${payment-total:.2f}") yes_no = input("\nDid you enjoy your meal? (Yes/No) ") starts = int(input("Give us your opinion, how many stars would you give to this restaurant? ")) print(f"\nThe customer rated the restaurant with {starts} stars") print(f"The customer enjoyed his meal: {yes_no}")
true
844344450154b2caacee4af1a0530e14781b9ace
sayan19967/Python_workspace
/Python Application programming practice/Context Managers.py
2,410
4.59375
5
#A Context Manager allows a programmer to perform required activities, #automatically, while entering or exiting a Context. #For example, opening a file, doing few file operations, #and closing the file is manged using Context Manager as shown below. ##with open('a.txt', 'r') as fp: ## ## content = fp.read() ## ##print(content) ##print(fp.read()) #Consider the following example, which tries to establish a connection to a #database, perform few db operations and finally close the connection. ##import sqlite3 ##try: ## dbConnection = sqlite3.connect('TEST.db') ## cursor = dbConnection.cursor() ## ''' ## Few db operations ## ... ## ''' ##except Exception: ## print('No Connection.') ##finally: ## dbConnection.close() # Using Context Manager ##import sqlite3 ##class DbConnect(object): ## def __init__(self, dbname): ## self.dbname = dbname ## def __enter__(self): ## self.dbConnection = sqlite3.connect(self.dbname) ## return self.dbConnection ## def __exit__(self, exc_type, exc_val, exc_tb): ## self.dbConnection.close() ##with DbConnect('TEST.db') as db: ## cursor = db.cursor() ## ''' ## Few db operations ## ... ## ''' #quiz ##from contextlib import contextmanager ## ##@contextmanager ##def tag(name): ## print("<%s>" % name) ## yield ## print("</%s>" % name) ## ##with tag('h1') : ## print('Hello') # Hackerrank -1 # Complete the function below. ##def writeTo(filename, input_text): ## with open(filename, 'w') as fp: ## fp.write(input_text) # Hackerrank - 2 # Define 'writeTo' function below, such that # it writes input_text string to filename. ##def writeTo(filename, input_text): ## with open(filename, 'w') as fp: ## fp.write(input_text) ## ### Define the function 'archive' below, such that ### it archives 'filename' into the 'zipfile' ##def archive(zfile, filename): ## with zipfile.ZipFile(zfile, 'w') as myzip: ## myzip.write(filename) # Hackerrank - 3 # Complete the function below. def run_process(cmd_args): with subprocess.Popen(cmd_args, stdout=subprocess.PIPE) as p: out1 = p.communicate()[0] return out1
true
81eccca3e13efaf255a41a92b5f7ee203a6aca41
Elzwawi/Core_Concepts
/Objects.py
2,689
4.4375
4
# A class to order custom made jeans # Programming with objects enables attributes and methods to be implemented # automatically. The user only needs to know that methods exist to use them # User can focus on completing tasks rather than operation details # Difference between functions and objects: Objects contain state and behaviour # while a function only defines a behaviour class jeans: # the _init_ method is a python constructor method for creating new objects. # it defines unique parameters for a new object. def __init__(self, waist, length, color): self.waist = waist self.length = length self.color = color self.wearing = False def put_on(self): print('Putting on {}x{} {} jeans'.format(self.waist, self.length, self.color)) self.wearing = True def take_off(self): print('Taking off {}x{} {} jeans'.format(self.waist, self.length, self.color)) self.wearing = False # create and examine a pair of jeans my_jeans = jeans(31, 32, 'blue') # creating a jeans object print(type(my_jeans)) print(dir(my_jeans)) # put on the jeans my_jeans.put_on() print(my_jeans.wearing) my_jeans.take_off() print(my_jeans.wearing) ## Properties of objects ################################################ class shirt: def __init__(self): self.clean = True def make_dirty(self): self.clean = False def make_clean(self): self.clean = True # create one shirt with two names red = shirt() crimson = red # examine the red/crimson shirt print(id(red)) print(id(crimson)) print(red.clean) print(crimson.clean) # spill juice on the red/crimson shirt red.make_dirty() print(red.clean) print(crimson.clean) # check that red and crimson are the same shirt print(red is crimson) # create a second shirt to be named crimson crimson = shirt() # examine both shirts print(id(red)) print(id(crimson)) print(crimson.clean) print(red.clean) # clean the red shirt red.make_clean() print(red.clean) print(crimson.clean) # check that red and crimson are different shirts print(red is crimson) ## Mutable vs. immutable ################################################ # A mutable object can be modified after creation # Immutable objects can not be modified. closet = ['shirt', 'hat', 'pants', 'jacket', 'socks'] # Mutable variable (list) print(closet) print(id(closet)) closet.remove('hat') print(closet) print(id(closet)) words = "You're wearing that " # Immutable variable (string) print(id(words)) # We can only modify it if we assign a new value to the variable words = words + 'beutiful dress' print(words) print(id(words)) # it is now a different id
true
af30645406d953795958b806cf529f1ce97150c2
ZSerhii/Beetroot.Academy
/Homeworks/HW6.py
2,918
4.1875
4
print('Task 1.\n') print('''Make a program that generates a list that has all squared values of integers from 1 to 100, i.e., like this: [1, 4, 9, 16, 25, 36, ..., 10000] ''') print('Result 1:\n') vResultList = [] for i in range(1, 101): vResultList.append(i * i) print('Squared values list of integers from 1 to 100:\n', vResultList, '\n', sep='') print('Task 2.\n') print('''Make a program that prompts the user to input the name of a car, the program should save the input in a list and ask for another, and then another, until the user inputs ‘q’, then the program should stop and the list of cars that was produced should be printed. ''') print('Result 2:\n') vCarList = [] while True: vCarName = input('Input the name of a car or letter "q" to exit: ') if vCarName == 'q': break vCarList.append(vCarName) print('\nYour car list:\n', vCarList, '\n', sep='') print('Task 3.\n') print('''Start of with any list containing at least 10 elements, then print all elements in reverse order. ''') print('Result 3:\n') import random vAnyList = [random.randint(1, 10) for i in range(20)] print('Original list:\n', vAnyList, '\n', sep='') vResultList = vAnyList.copy() vResultList.reverse() print('Reverse version 1:\n', vResultList, '\n', sep='') vResultList = [] for vIndex in range(1, len(vAnyList) + 1): vResultList.append(vAnyList[-vIndex]) print('Reverse version 2:\n', vResultList, '\n', sep='') print('Lesson topics: Fibonacci sequence.\n') print('''If n > 1 then (n-1)+(n-2) If n == 1 then 1 If n == 0 then 0. ''') print('Result Fibonacci sequence:\n') vFibonacciCount = int(input('Input the number of Fibonacci sequence elements: ')) print('') vResult = 0 vPrevious = 0 vCurrent = 0 vResultList = [] for i in range(vFibonacciCount): vResult = vPrevious + vCurrent if i < 2: vCurrent = i vResult = i else: vPrevious = vCurrent vCurrent = vResult vResultList.append(vResult) print('First {} elements of Fibonacci sequence:\n'.format(vFibonacciCount), vResultList, sep='') print('Lesson topics: Pascal\'s triangle sequence.\n') print('''Pascal’s triangle sequence, given positive int k, returns a list of k lists, each representing a floor in the pyramid/triangle. See the following for rules: https://en.wikipedia.org/wiki/Pascal%27s_triangle ''') print('Result Pascal\'s triangle sequence:\n') vPascalsDepth = int(input('Input the depth of Pascal\'s triangle sequence: ')) vPascalsPrev = [] print('') for i in range(vPascalsDepth): vPascalsLine = [] j = 0 while j <= i: if j == 0 or j == i: vPascalsLine.append(1) else: vPascalsLine.append(vPascalsPrev[j - 1] + vPascalsPrev[j]) j += 1 vPascalsPrev = vPascalsLine.copy() print('{}:'.format(i), vPascalsLine) print('\nThat\'s all Folks!')
true
4cc9d559c7a44cd2f500a60548fc6b98294828f0
erictseng89/CS50_2021
/week6/scores.py
769
4.125
4
scores = [72, 73, 33] """ print("Average: " + (sum(scores) / len(scores))) """ # The "len" will return the number of values in a given list. # The above will return the error: # TypeError: can only concatenate str (not "float") to str # This is because python does not like to concatenate a float value to a string. # In order to fix this issue, we can cast the float into a string: print("Average " + str((sum(scores) / len(scores)))) # You can also wrap the functions themselves inside the print("") contents, which can remove the need for the str() cast function as python will presume that I intended for the value be converted into a str. This can cause the print content to be longer and messier to read. print(f"Average {((sum(scores) / len(scores)))}")
true
72548593092cdbc2ddb64d76951d71d4a89b93e3
mzdesa/me100
/hw1/guessNum.py
599
4.21875
4
#write a python program that asks a user to guess an integer between 1 and 15! import random random_num = random.randint(1,15) #generates a random int between 0 and 15 guess = None #generate an empty variable count = 0 while guess != random_num: count+=1 guess = int(input('Take a guess: ')) if guess == random_num: print('Congratulations, you guessed my number in', count, 'trials!') break #exit the loop and end the program if it is correctly guessed elif guess<random_num: print('Your guess is too low.') else: print('Your guess is too high.')
true
e7011a00db9e29abb6e8ad19259dfcacc1423525
abrolon87/Python-Crash-Course
/useInput.py
1,219
4.28125
4
message = input("Tell me something, and I will repeat it back to you: ") print (message) name = input("Please enter your name: ") print(f"\nHello, {name}!") prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? " #prompt += "\nWhat is your age? " this doesn't work name = input(prompt) print(f"\nHello, {name}!") #as numerical input age = input("How old are you? ") #to compare, we have first convert the string to a numerical value:. #age = int(age) #age >= 18 #try it yourself 7-1 rentalCar = input("What kind of car would you like to rent? ") print(f"\nLet me see if I can find you a {rentalCar}.") # 7-2 guests = input("How many people are in your group?") guests = int(guests) if guests >= 8: print("\nYou will have to wait to be seated.") else: print("Your table is ready.") #7-3 number = input("Enter a number. I'll tell you if it is a multiple of 10 or not: ") number = int(number) if number % 10 == 0: print(f"\nThis number is a multiple of 10") else: print(f"\nThis number is NOT a multiple of 10") #while loop current_number = 1 while current_number <= 5: print(current_number) current_number += 1
true
1957711865e1570ed423c327f288ce8a12d2fe50
jacquelinefedyk/team3
/examples_unittest/area_square.py
284
4.21875
4
def area_squa(l): """Calculates the area of a square with given side length l. :Input: Side length of the square l (float, >=0) :Returns: Area of the square A (float).""" if l < 0: raise ValueError("The side length must be >= 0.") A = l**2 return A
true
a957e7f81f52bc56d9af1cd63a284f2e597c6f9d
JohnAsare/functionHomework
/upLow.py
766
4.15625
4
# John Asare # Jun 19 2020 """ Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters. Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?' Expected Output : No. of Upper case characters : 4 No. of Lower case Characters : 33 """ def up_low(s): uppers = '' lowers = '' for letter in s: if letter.isupper(): uppers += letter elif letter.islower(): lowers += letter print(f'No. of Upper case characters : {len(uppers)}') print(f'No. of Lower case characters : {len(lowers)} \n') print('#########################################') s = 'Hello Mr. Rogers, how are you this fine Tuesday?' up_low(s) up_low('Hi, My name is John Asare')
true
f5306409b6be76bdc3ce5789daafcca973fdb971
kelvinng213/PythonDailyChallenge
/Day09Challenge.py
311
4.1875
4
#Given a string, add or subtract numbers and return the answer. #Example: #Input: 1plus2plus3minus4 #Output: 2 #Input: 2minus6plus4plus7 #Output: 7 def evaltoexpression(s): s = s.replace('plus','+') s = s.replace('minus','-') return eval(s) print(evaltoexpression('1plus2plus3minus4'))
true
e082eb4ff18f0f3a19576a5e3e346227ba98ebf8
kelvinng213/PythonDailyChallenge
/Day02Challenge.py
894
4.53125
5
# Create a function that estimates the weight loss of a person using a certain weight loss program # with their gender, current weight and how many weeks they plan to do the program as input. # If the person follows the weight loss program, men can lose 1.5% of their body weight per week while # women can lose 1.2% of their body weight per week. # The possible inputs are: # Gender: 'M' for Male, 'F' for Female # Current weight: integer above 0 # Number of weeks: integer above 0 # Return the estimated weight after the specified number of weeks. def lose_weight(): gender = input("M or F:").upper() weight = int(input("Enter weight:")) num_weeks = int(input("Number of weeks:")) if gender == "M": n = weight - ((0.015 * weight) * num_weeks) print(n) else: n = weight - ((0.012 * weight) * num_weeks) print(n) lose_weight()
true
45f5407c770e494c7d9be2fbcbf1802e56c74e21
rohan-krishna/dsapractice
/arrays/array_rotate.py
533
4.125
4
# for the sake of simplicity, we'll use python list # this is also known as Left Shifting of Arrays def rotateArray(arr, d): # arr = the input array # d = number of rotations shift_elements = arr[0:d] arr[:d] = [] arr.extend(shift_elements) return arr if __name__ == "__main__": print("How many time do you want to shift the array: ") n = int(input()) print("Enter Array (e.g: 1 2 3 == [1,2,3]): ") arr = list(map(int, input().rstrip().split())) res = rotateArray(arr, n) print(res)
true
bba98a339cc3fe159b5db7a6979f37a1e6467eee
shridharkute/sk_learn_practice
/recursion.py
668
4.375
4
#!/usr/bin/python3 ''' This is recursion example. recursion is method to call itself while running. Below is the example which will create addition till we get 1. Eg. If we below funcation as "tri_resolution(6)" the result will be Rcursion example result 1 1 2 3 3 6 4 10 5 15 6 21 But in the background it will execute below code. >>> 6 + 5 + 4 + 3 + 2 + 1 21 >>> 5 + 4 + 3 + 2 + 1 15 >>> 4 + 3 + 2 + 1 10 >>> 3 + 2 + 1 6 >>> 2 + 1 3 >>> 1 1 >>> ''' def tri_resolution(k): if (k>0): result = k+tri_resolution(k-1) print(k, result) else: result = 0 return result print("\n\nRcursion example result") tri_resolution(6)
true
600409d5897e5a6a2a8fa5900a8ca197abf294f7
DAVIDCRUZ0202/cs-module-project-recursive-sorting
/src/searching/searching.py
798
4.34375
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): if len(arr) == 0: return -1 low = start high = end middle = (low+high)//2 if arr[middle] == target: return middle if arr[middle] > target: return binary_search(arr, target, low, middle-1) if arr[middle] < target: return binary_search(arr, target, middle+1, high) return -1 # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively # def agnostic_binary_search(arr, target): # Your code here
true
1e4ecc5c66f4f79c0f912313acd769edb3a92008
harshal-jain/Python_Core
/22-Lists.py
1,980
4.375
4
list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] """ print ("list1[0]: ", list1[0]) #Offsets start at zero print ("list2[1:5]: ", list2[1:5]) #Slicing fetches sections print ("list1[-2]: ", list1[-2]) #Negative: count from the right print ("Value available at index 2 : ", list1[2]) list1[2] = 2001 print ("New value available at index 2 : ", list1[2]) del list1[2] print ("After deleting value at index 2 : ", list1) print(list1+list2) print(list1*3) print(2000 in list1) for x in [1,2,3] : print (x,end = ' ') #Gives the total length of the list. print (len(list1)) #Returns item from the list with max value. all data type should be same to calculate max print (max(list2)) #Returns item from the list with min value. all data type should be same to calculate max print (min(list2)) #The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list. aTuple = (123, 'C++', 'Java', 'Python') list3 = list(aTuple) print ("List elements : ", list3) str = "Hello World" list4 = list(str) print ("List elements : ", list4) """ #Python includes the following list methods − #Appends object obj to list list1.append('C#') print(list1) #Returns count of how many times obj occurs in list a=list1.count('C#') print(a) #Appends the contents of seq to list list1.extend(list2) print(list1) #Returns the lowest index in list that obj appears print(list1.index('C#')) #Inserts object obj into list at offset index list1.insert(2, 'ASP') print(list1) #Removes and returns last object or obj from list obj=list1.pop() print(obj) print(list1) #Removes and returns last object or obj from list obj=list1.pop(3) print(obj) print(list1) #Removes object obj from list list1.remove('C#') print(list1) #Reverses objects of list in place list1.reverse() print(list1) #Sorts objects of list, use compare func if given '''list1.sort() print(list1) list1.sort(reverse=True) print(list1) '''
true
b253f828fc56c2f9e7148e13ae2a910c542f1249
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 05/ProgrammingExercises/03_budget_analysis.py
1,540
4.40625
4
# Write a program that asks the user to enter the amount that they have # budgeted for a month. A loop should then prompt the user to enter each of # their expenses for the month, and keep a running total. When the loop # finishes, the program should display the amount that the user is over # or under budget. def budget(): # Get the budget's limit. m_limit = float(input('Enter amount budgeted for the month: ')) # Initialize accumulator variable. total_expenses = 0.0 # Variable to control the loop. another = 'y' # Get each expense and accumulate them. while another == 'y' or another == 'Y': # Get expense and tack it to the accumulator. expense = float(input('Enter expense: ')) # Validate expense. while expense < 0: print('ERROR: You can\'t enter a negative amount.') expense = float(input('Enter correct expense: ')) total_expenses += expense # Do it again? another = input('Do you have another expense? ' + \ '(Enter y for yes): ') # Determine over/under budget's amount. if m_limit > total_expenses: under = m_limit - total_expenses print('You are $', format(under, ',.2f'), ' under budget!', sep='') elif m_limit < total_expenses: over = total_expenses - m_limit print('You are $', format(over, ',.2f'), ' over budget...', sep='') else: print('Impressively, you are exactly on budget.') # Call budget function. budget()
true
88cfb1d6b2746e689d6a661caa34e5545f044670
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 04/ProgrammingExercises/09_shipping_charges.py
1,098
4.4375
4
# The Fast Freight Shipping Company charges the following rates: # # Weight of Package Rate per Pound # 2 pounds or less $1.10 # Over 2 pounds but not more than 6 pounds $2.20 # Over 6 pounds but not more than 10 pounds $3.70 # Over 10 pounds $3.80 # # Write a program that asks the user to enter the weight of a package and # then displays the shipping charges. def main(): # Prompt weight = float(input('Enter weight of package: ')) # Decide + Calculate if weight <= 2: rate = weight * 1.10 print('Shipping charges: $', format(rate, ',.2f'), sep='') elif weight > 2 and weight <= 6: rate = weight * 2.20 print('Shipping charges: $', format(rate, ',.2f'), sep='') elif weight > 6 and weight <= 10: rate = weight * 3.70 print('Shipping charges: $', format(rate, ',.2f'), sep='') else: rate = weight * 3.80 print('Shipping charges: $', format(rate, ',.2f'), sep='') main()
true
4d24d83ec69531dd864ef55ed900a6d154589fd8
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 03/ProgrammingExercise/04_automobile_costs.py
1,248
4.34375
4
# Write a program that asks the user to enter the monthly costs for the # following expenses incurred from operating his or her automobile: loan # payment, insurance, gas, oil, tires, and maintenance. The program should # then display the total monthly cost of these expenses, and the total # annual cost of these expenses. def main(): # Get input lp = float(input('Enter monthly loan payment cost: ')) ins = float(input('Enter monthly insurance cost: ')) gas = float(input('Enter monthly gas cost: ')) oil = float(input('Enter monthly oil cost: ')) tire = float(input('Enter monthly tire cost: ')) maint = float(input('Enter monthly maintenance cost: ')) # Calculate monthly cost monthly(lp, ins, gas, oil, tire, maint) # Calculate annual cost annually(lp, ins, gas, oil, tire, maint) def monthly(lp, ins, gas, oil, tire, maint): cost_monthly = lp + ins + gas + oil + tire + maint print('The monthly amount of expenses is $', \ format(cost_monthly, ',.2f'), sep='') def annually(lp, ins, gas, oil, tire, maint): cost_annually = (lp + ins + gas + oil + tire + maint) * 12 print('The annual amount of expenses is $', \ format(cost_annually, ',.2f'), sep='') main()
true
36e179b5db4afaf4b7bc2b6a51f0a81735ac2002
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 06/ProgrammingExercises/01_feet_to_inches.py
521
4.40625
4
# One foot equals 12 inches. Write a function named feet_to_inches that # accepts a number of feet as an argument, and returns the number of inches # in that many feet. Use the function in a program that prompts the user # to enter a number of feet and then displays the number of inches in that # many feet. def main(): feet = int(input('Enter a number of feet: ')) inches = feet_to_inches(feet) print('There are', inches, 'inches in', feet, 'feet.') def feet_to_inches(feet): return feet * 12 main()
true
a8bf3cc39005180b6d3b2d18a751c43f3665ec23
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 07/ProgrammingExercises/09_exception_handling.py
348
4.125
4
# Modify the program that you wrote for Exercise 6 so it handles the following # exceptions: # • It should handle any IOError exceptions that are raised when the file is # opened and data is read from it. # • It should handle any ValueError exceptions that are raised when the items # that are read from the file are converted to a number.
true
3d4cba89be0858b757da7c59a4845ab4360d28d3
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 06/ProgrammingExercises/05_kinetic_energy.py
1,110
4.40625
4
# In physics, an object that is in motion is said to have kinetic energy (KE). # The following formula can be used to determine a moving object’s kinetic # energy: # # KE = (1/2) * m * v^2 # # The variables in the formula are as follows: KE is the kinetic energy in # joules, m is the object’s mass in kilograms, and v is the object’s velocity # in meters per second. # Write a function named kinetic_energy that accepts an object’s mass in # kilograms and velocity in meters per second as arguments. The function # should return the amount of kinetic energy that the object has. Write a # program that asks the user to enter values for mass and velocity, and then # calls the kinetic_energy function to get the object’s kinetic energy. def main(): mass = float(input('Enter the object\'s mass in kilograms: ')) velocity = float(input('Enter the object\'s velocity in meters: ')) KE = kinetic_energy(mass, velocity) print('The object\'s kinetic energy is', KE, 'joules.') def kinetic_energy(m, v): return (1/2) * m * v**2 # Call the main function. main()
true
8cccedbab97b4439c53bbec5f443011066947897
kescalante01/learning-python
/Address.py
867
4.28125
4
#Use raw_input() to allow a user to type an address #If that address contains a quadrant (NW, NE, SE, SW), then add it to that quadrant's list. #Allow user to enter 3 addresses; after three, print the length and contents of each list. ne_adds = [] nw_adds = [] se_adds = [] sw_adds = [] address1 = raw_input("Whats your address?") address2 = raw_input("Whats your work address?") address3 = raw_input("Whats your address of your favorite bar?") address1 = address.upper() address2 = address.upper() address3 = address.upper() address_as_a_list1 = address1.split(' ') print address_as_a_list1 address_as_a_list2 = address2.split(' ') print address_as_a_list2 address_as_a_list3 = address3.split(' ') print address_as_a_list3 all_addresses_as_list = address_as_a_list1 + address_as_a_list2 + address_as_a_list3 if NW in all_addresses_as_list: nw_adds.append()
true
6d72e4e2ce4447de1dfee99def28204c089f7faf
riteshsingh1/learn-python
/string_function.py
406
4.34375
4
string="Why This Kolaveri DI" # 1 # len(string) # This function returns length of string print(len(string)) # 2 # In Python Every String is Array string = "Hello There" print(string[6]) # 3 # index() # Returns index of specific character / Word - First Occurance string="Python is better than PHP." print(string.index("PHP")) # 4 # replace string = "PHP is best" print(string.replace("PHP", "Python"))
true
6b8442b9cd22aa2eeb37966d42ca6511f3ba6c17
antoninabondarchuk/algorithms_and_data_structures
/sorting/merge_sort.py
797
4.125
4
def merge_sort(array): if len(array) < 2: return array sorted_array = [] middle = int(len(array) / 2) left = merge_sort(array[:middle]) right = merge_sort(array[middle:]) left_i = 0 right_i = 0 while left_i < len(left) and right_i < len(right): if left[left_i] > right[right_i]: sorted_array.append(right[right_i]) right_i += 1 else: sorted_array.append(left[left_i]) left_i += 1 sorted_array.extend(left[left_i:]) sorted_array.extend(right[right_i:]) return sorted_array if __name__ == '__main__': sorted1 = merge_sort([1, 7, 5, 3, 4, 2, 0]) sorted2 = merge_sort([]) sorted3 = merge_sort('') sorted4 = merge_sort([9, 8, 7, 6, 5, 4, 3, 2, 1]) print(sorted1)
true
12ee12d7d101ed158bae6079f14e8a6360c424f6
elicecheng/Python-Practice-Code
/Exercise1.py
359
4.15625
4
#Exercise 1 #Asks the user to enter their name and age. #Print out a message addressed to them that #tells them the year that they will turn 100 years old. import datetime name = input("What is your name?") age = int(input("How old are you?")) now = datetime.datetime.now() year = (now.year - age) + 100 print(name, "will be 100 years old in year", year)
true
cb04890ea51898c5c225686f982e77da4dc71535
playwithbear/Casino-Games
/Roulette Basic.py
1,488
4.28125
4
# Basic Roulette Mechanics # # Key attributes: # 1. Provide a player with a balance # 2. Take a player bet # 3. 'Spin' Roulette wheel # 4. Return result to player and update balance if necessary with winnings # # NB. This roulette generator only assumes a bet on one of the evens i.e. red of black to test a gambling strategy # Import modules import random # Initialise game balance = 1000 playing = "y" print("Welcome to The Oversimplified Roulette Machine.") print("This game will assume you always bet on evens.") print("Your current balance is: " + str(balance)) # Game loop while playing == "y": # Take bet bet = int(input("\nHow much would you like to bet? ")) balance -= bet # Spin wheel result = random.randrange(36) print("The result is: " + str(result)) # Assess winning if result == 0: # i.e. no winning or losing balance += bet print("\nZero. Player stands.") elif result % 2 == 0: # Result is even balance += (bet*2) print("\nCongratulations, you win " + str(bet*2)) else: # You lose print("\nSorry, you lose.") # Inform player of their current balance print("\nYour current balance is: " + str(balance)) # Invite to play again playing = str.lower(input("\nWould you like to play again? Y/N: ")) input("\nThank you for playing The Oversimplified Roulette Machine. \nPress any key to exit.")
true
c413add161722e8efad1b4319463ede4f5a3aff8
ramsundaravel/PythonBeyondBasics
/999_Misc/004_generators.py
1,140
4.375
4
# Generators - # Regular function returns all the values at a time and goes off # but generator provides one value at a time and waits for next value to get off. function will remain live # it basically yields or stops for next call # basically not returning all values together. returning one value at a time def generator_example(num): for i in range(1,num): print('Loop started for {}'.format(i)) yield i print('Loop end for {}'.format(i)) test = generator_example(10) # print('1*********') # print(next(test),'\n') # print('2*********') # print(next(test),'\n') # print('3*********') # print( next(test),'\n') # print('*********') # alternative way of call for x in test: print(x) print('\n') #****************************************# print('Square example using generators') def square(num): for i in num: yield i * i sq = square([1,2,3,4,5,6]) # sq is a generator object pointing to the function square # now call sq till end of iteration using for loop or through next method method # advantage memory saving and performance for i in sq: print (i) # it yields one value
true
d70c7e14cb9974a1320850eb1e70fa2fb1e14dd7
AhmedElatreby/python_basic
/while_loop.py
2,392
4.4375
4
""" # While Loop A while loop allows code to be repeated an unknown number of times as long as a condition is being met. ======================================================================================================= # For Loop A for loop allows code to be repeated known number of loops/ iterations """ # import random # i = 1 # while i < 6: # print("True") # i += 1 """ craete a programme to ask the user to guess a number between 1 - 10 and count the number of attemeted """ # count = 0 # num = 0 # rand = str(random.randint(1, 10)) # while num != rand: # num = input("Enter a number between 1-10: ") # count += 1 # print(rand) # print(f"Guess count {count}") # print("Correct!") """ create a programe to genarate a random numbers and to stop the programe once number 5 found """ # num1 = 1 # while num1 > 0: # print(num1) # num1 = random.randint(1, 10) # if num1 == 5: # break # print("5 was found") # # Write a while loop that adds all the numbers from 1 to 100 # i = 1 # while i <= 100: # print(i) # i += 1 """ Take the following list: numbers=[10, 99, 98, 85, 45, 59, 65, 66, 76, 12, 35, 13, 100, 80, 95] Using a while loop iterate through the list and for every instance of 100 print out "Found one!" """ # numbers = [10, 99, 100, 98, 85, 45, 59, 65, # 100, 66, 76, 12, 100, 35, 13, 100, 80, 95] # length = len(numbers) # i = 0 # while i < length: # if numbers[i] == 100: # print("Found one!") # i += 1 """ Using the following list of names: names=["Joe", "Sarah"] Using a while loop allow users to add new names to the list indefinitely. Each time a user adds a new name ask the user if they would like to add another name. 1 = yes and 2 = no. The programme should stop if the users selects 2, no. """ # names = ["Joe", "Sarah"] # while True: # names.append(input("Enter name: ")) # print(names) # x = int(input("1-add more, 2-exit: ")) # if x == 2: # break """ Create a dice roll simulator whereby the user is first given an option on screen to either play or exit the simulator. An input() function is used to capture the users choice. """ import random while True: print("1. Roll dice, \n2. Exit game") user = int(input("Choice 1 or 2: ")) if user == 1: number = random.randint(1, 6) print(number) else: break
true
4280063ba51d897bdb1049d6a1a84c6625ed0a39
igor-kurchatov/python-tasks
/Warmup1/pos_neg/pos_neg_run.py
355
4.1875
4
################################# # Task 8 - implementation # Desription: Given 2 int values, return True if one is negative and one is positive. # Except if the parameter "negative" is True, then return True only if both are negative. # Author : Igor Kurchatov 5/12/2016 ################################# from pos_neg import pos_neg_run pos_neg_run()
true
0fe469e04d72b5e225fdc4279f6f4c9542031644
AmeyMankar/PracticePython
/Exercise2.py
462
4.28125
4
# Let us find the sum of several numbers (more than two). It will be useful to do this in a loop. #http://www.codeabbey.com/index/task_view/sum-in-loop user_input = [] sum_of_numbers = 0 choice=1 while choice != 2: user_input.append(int(input("Please enter your number: \t"))) choice = int(input("Do you want to add more numbers: 1) Yes 2) No: \t")) for item in user_input: sum_of_numbers += item print("Total sum of numbers is:\t"+str(sum_of_numbers))
true
edbc80e91c8a9ad244bee62bcfe3809a3dce876a
ethanpierce/DrZhao
/LinkedList/unitTestLinkedList.py
644
4.15625
4
from linkedlist import LinkedList def main(): #Create list of names listOfNames = { "Tom", "Harry","Susan","Ethan","Willy","Shaina"} #Create linkedlist object testinglist = LinkedList() #Test insertion method for name in listOfNames: testinglist.insert(name) #Test size of list print testinglist.size() #Test print list testinglist.printList() #Test Deletion of head node testinglist.delete("Tom") #Test Deletion method: testinglist.delete("Susan") testinglist.printList() #Test search list testinglist.search("Willy") if __name__ == '__main__': main()
true
97fc123c1a6beb45aa2893c0c4a8d21bfc41b174
dvcolin/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
2,387
4.1875
4
class Node: def __init__(self, value=None, next_node=None): # the value at this linked list node self.value = value # reference to the next node in the list self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): # set this node's next_node reference to the passed in node self.next_node = new_next class LinkedList: def __init__(self): # reference to the head of the list self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False # get a reference to the node we're currently at; update this as we traverse the list current = self.head # check to see if we're at a valid node while current: # return True if the current value we're looking at matches our target value if current.get_value() == value: return True # update our current node to the current node's next node current = current.get_next() # if we've gotten here, then the target node isn't in our list return False def reverse_list(self): def reverse_list_inner(node): # If list is empty, return None if not self.head: return None # If a next node exists, add current node value to head and call function on next node elif node.next_node != None: self.add_to_head(node.value) return reverse_list_inner(node.next_node) # When there is no next node, we are at the tail. Add tail to head self.add_to_head(node.value) reverse_list_inner(self.head) # ex = LinkedList() # ex.add_to_head(4) # ex.add_to_head(9) # ex.add_to_head(2) # ex.add_to_head(0) # print(ex.head.value) # print(ex.head.get_next().value) # print(ex.head.get_next().get_next().value) # print(ex.head.get_next().get_next().get_next().value) # ex.reverse_list() # print(ex.head.value) # print(ex.head.get_next().value) # print(ex.head.get_next().get_next().value) # print(ex.head.get_next().get_next().get_next().value)
true
1041fe53fa1dbc0a91f0602f20530a4608656069
tadeograch/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
483
4.3125
4
#!/usr/bin/python3 """ 0. Integers addition A function that adds 2 integers add_integer(a, b) """ def add_integer(a, b=98): """ Function that add two integers """ if not type(a) is int and not type(a) is float: raise TypeError("a must be an integer") if not type(b) is int and not type(b) is float: raise TypeError("b must be an integer") if type(a) is float: a = int(a) if type(b) is float: b = int(b) return a + b
true
0725747b9015941bac5f87ff3c5a9372ab9fd5cc
uoshvis/py-data-structures-and-algorithms
/sorting_and_selection/selection.py
1,527
4.15625
4
# An example of prune-and-search design pattern import random def binary_search(data, target, low, high): """Return True if target is found in indicated portion of a Python list. The search only considers the portion from data[low] to data[high] inclusive. """ if low > high: return False # interval is empty; no match else: mid = (low + high) // 2 if target == data[mid]: # found a matcha return True elif target < data[mid]: # recur on the portion left of the middle return binary_search(data, target, low, mid - 1) else: # recur on the portion right of the middle return binary_search(data, target, mid + 1, high) # randomized quick-select algorithm # runs in O(n) expected time, O(n^2) time in the worst case def quick_select(S, k): """Return the kth smallest element of list S, for k from 1 to len(S).""" if len(S) == 1: return S[0] pivot = random.choice(S) # pick random pivot element from S L = [x for x in S if x < pivot] E = [x for x in S if x == pivot] G = [x for x in S if pivot < x] if k <= len(L): return quick_select(L, k) # kth smallest lies in L elif k <= len(L) + len(E): return pivot # kth smallest equal to pivot else: j = k - len(L) - len(E) # new selection parameter return quick_select(G, j) # kth smallest is jth in G
true
0ae6074efd9a9b393439a72b9f596d4baf09f7c8
v13aer14ls/exercism
/salao_de_beleza.py
1,538
4.21875
4
#!/bin/python2/env #Guilherme Amaral #Mais um exercicio daqueles hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"] prices = [30, 25, 40, 20, 20, 35, 50, 35] last_week = [2, 3, 5, 8, 4, 4, 6, 2, 1] #1. Create a variable total_price, and set it to 0. total_price = 0 #2. Iterate through the prices list and add each price to the variable total_price. for price in prices: total_price += price print(total_price) # 3. create a variable called average_price that is the total_price divided by the number of haircuts. average_price = total_price/len(hairstyles) #4. prtint average price string print("Average Price: " + str(average_price)) #5. Create list comprehension to make a list titled new_prices, with each element subtracted by 5 new_prices = [price - 5 for price in prices] #6. Print new prices print(new_prices) #7. create new variable called total_revenue and set it equal to 0 total_revenue = 0 #8. create a loop that goes from 0 to len(hairstyles)-1 for i in range(len(hairstyles)-1): print(i) #9 Add the product of prices[i] (the price of the haircut at position i) and last_week[i] for i in range(0, len(hairstyles)-1): total_revenue += prices[i] * last_week[i] #print total revenue print(total_revenue) #find average daily revenue average_daily_revenue = total_revenue/7 print(average_daily_revenue) #12. create comprehension list for haircuts less than 30 cuts_under_30 = list(zip(hairstyles,[price for price in new_prices if price < 30])) print(list(cuts_under_30))
true
ff01b081c831b0593ebb3722ee47ca04b2406991
Praneeth313/Python
/Loops.py
1,363
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu May 6 23:02:40 2021 @author: Lenovo Assignment 5: Basic Loop Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". """ ''' Created a list using range function with elemnts as numbers from 1 to 100 ''' Numbers = list(range(1,101)) ''' Created a for loop with nested if statements ''' for i in Numbers: if i%3 == 0: ''' if the number is the divisible by 3 then replace the number with 'Fizz' by subracting the number with 1 and using it as index ''' Numbers[i-1] = "Fizz" if i%5 == 0: ''' if the number is the divisible by 5 then replace the number with 'Buzz' by subracting the number with 1 and using it as index ''' Numbers[i-1] = "Buzz" if i%3 == 0 and i%5 == 0: ''' if the number is the divisible by 3 and 5 then replace the number with 'FizzBuzz' by subracting the number with 1 and using it as index ''' Numbers[i-1] = "FizzBuzz" ''' Use a for loop to go through all the elements of the List and print them ''' for n in Numbers: print(n)
true
9018be0092cebcda903279b87fcdb9e78a8c79fb
akshat12000/Python-Run-And-Learn-Series
/Codes/98) list_comprehension_in_nested_list.py
389
4.53125
5
# List comprehension in nested list # We want the list --> [[1,2,3], [1,2,3], [1,2,3]] # Method 1)--> without list comprehension l=[] for i in range(3): p=[] for j in range(1,4): p.append(j) l.append(p) print(l) # Method 2)--> with list comprehension l1=[[i for i in range(1,4)] for _ in range(3)] # Note: Here we have used '_' in for loop !! print(l1)
true
8f9ef1a6b1b42b511331646021caa6a7e9b298eb
akshat12000/Python-Run-And-Learn-Series
/Codes/104) args_as_argument.py
296
4.28125
4
def multiply(*args): mul=1 print(f"Elements in args are {args}") for i in args: mul*=i return mul l=[1,2,3] t=(1,2,3) print(multiply(l)) # OUTPUT: [1,2,3] print(multiply(*l)) # OUTPUT: 6 , here all the elements of the list will get unpacked print(multiply(*t))
true
4cd283528b382fab7369630629c6f46d0993590c
akshat12000/Python-Run-And-Learn-Series
/Codes/134) generators_intro.py
569
4.65625
5
# generators are iterators # iterators vs iterables l=[1,2,3,4] # iterable l1=map(lambda a:a**2,l) # iterator # We can use loops to iterate through both iterables and iterators!! li=[1,2,3,4,5] # memory --- [1,2,3,4,5], list, it will store as a chunk of memory!! # memory --- (1)->(2)->(3)->(4)->(5), generators, numbers will be generated one at a time and previously generated number will be # deallocated after it's use, hence it is time and memory efficient!! # If we want to use our data more than once then use lists otherwise use generators
true
82703ca80bd6745995fd86e4de8a7ae6e978efc5
akshat12000/Python-Run-And-Learn-Series
/Codes/137) generators_comprehension.py
444
4.21875
4
# Genrators comprehension square=[i**2 for i in range(1,11)] # list comprehension print(square) square1=(i**2 for i in range(1,11)) # generator comprehension print(square1) for i in square1: print(i) for i in square1: print(i) # Notice that it will print only once!! square2=(i**2 for i in range(1,5)) # generator comprehension print(next(square2)) print(next(square2)) print(next(square2)) print(next(square2))
true
5e5bcdee2c5fd58e9532872a8c4403e8cf47d49f
akshat12000/Python-Run-And-Learn-Series
/Codes/22) string_methods2.py
298
4.25
4
string="He is good in sport and he is also good in programming" # 1. replace() method print(string.replace(" ","_")) print(string.replace("is","was",1)) print(string.replace("is","was",2)) # 2. find() method print(string.find("is")) print(string.find("also")) print(string.find("is",5))
true
7613ae3e2b62c471be17440d5ce22679b7d61d0d
akshat12000/Python-Run-And-Learn-Series
/Codes/119) any_all_practice.py
421
4.1875
4
# Write a funtion which contains many values as arguments and return sum of of them only if all of them are either int or float def my_sum(*args): if all([type(i)== int or type(i)== float for i in args]): total=0 for i in args: total+=i return total else: return "WRONG INPUT!" print(my_sum(1,2,3,6.7,9.8,[1,2,3],"Akshat")) print(my_sum(1,2,3,4,6.7,9.8))
true
ea0f61c783a093d998866e3b7843daa2cbd01e4a
akshat12000/Python-Run-And-Learn-Series
/Codes/126) closure_practice.py
399
4.125
4
# Function returning function (closure or first class functions) practice def to_power(x): def calc_power(n): return n**x return calc_power cube=to_power(3) # cube will be the calc_power function with x=3 square=to_power(2) # square will be the calc_power function with x=2 print(cube(int(input("Enter first number: ")))) print(square(int(input("Enter second number: "))))
true
7232967214c29480b14d437eba3a42e5a2b23a5f
akshat12000/Python-Run-And-Learn-Series
/Codes/52) greatest_among_three.py
365
4.125
4
# Write a function which takes three numbers as an argument and returns the greatest among them def great3(a,b,c): if a>b: if a>c: return a return c else: if b>c: return b return c x,y,z=input("Enter any three numbers: ").split() print(f"Greatest number is: {great3(int(x),int(y),int(z))}")
true
ba1551611784af483ea8341a3fdbccc5a5d8b235
akshat12000/Python-Run-And-Learn-Series
/Codes/135) first_generator.py
932
4.5625
5
# Create your first generator with generator function # Method 1) --> generator function # Method 2) --> generator comprehension # Write a function which takes an integer as an argument and prints all the numbers from 1 to n def nums(n): for i in range(1,n+1): print(i) nums(5) def nums1(n): for i in range(1,n+1): yield(i) # or yield i # this statement makes nums1 a generator!! print(nums1(5)) # now nums1 has become a generator!! for i in nums1(5): # you can iterate through nums1(5) as it is an iterator!! print(i) print("printing numbers..") numbers=nums1(5) for i in numbers: print(i) for i in numbers: print(i) # numbers will be printed only once!! print("printing numbers which is converted to list...") numbers1=list(nums1(5)) for i in numbers1: print(i) for i in numbers1: print(i) # numbers2 will printed twice as it is list now
true
fd70a0a0c399b7ea099ad0df2069b1b861f7ac6d
akshat12000/Python-Run-And-Learn-Series
/Codes/58) intro_to_lists.py
702
4.3125
4
# A list is a collection of data numbers=[1,2,3,4,5] # list declaration syntax and it is list of integers print(numbers) words=["word1",'word2',"word3"] # list of strings as you can see we can use both '' and "" print(words) mixed=[1,2,3,4,"Five",'Six',7.0,None] # Here the list contains integers, strings, float and None data types print(mixed) # accessing list elements(Remember the indexing start from 0) print(numbers[2]) print(words[0]) print(mixed[6]) print(numbers[:2]) print(words[:]) print(mixed[4:]) # updating list elements mixed[1]=8 print(mixed) mixed[1:]="two" # whole list will replace from index 1 to end print(mixed) mixed[1:]=["one","two"] print(mixed)
true
f803ca25ed0928e6c2786d99f26a2f69b5c69dd2
indradevg/mypython
/cbt_practice/for1.py
609
4.34375
4
#!/usr/bin/python3.4 i=10 print("i value before : the loop: ", i) for i in range(5): print(i) ''' The for loops work in such a way that leave's behind the i value to the end of the loop and re-assigns the value to i which was initializd as 10 in our case ''' print("i value after the loop: ", i) ''' The below line in the for loop when enclosed in the [ ] will not allow the for loop variable leak However, in Python 3.x, we can use closures to prevent the for-loop variable to cut into the global namespace ''' i = 1 #print([i for i in range(5)]) [print(i) for i in range(5)] print(i, '-> i in global')
true
0c28d1d950dbbdf74ec827583dd7c46c331bc4b0
thanasissot/myPyFuncs
/fibonacci.py
481
4.1875
4
# cached fibonacci cache = dict() def memFib(n): """Stores result in cache dictionary to be used at function definition time, making it faster than first caching then using it again for faster results """ if n in cache: return cache[n] else: if n == 0: return 0 elif n == 1: return 1 else: result = memFib(n - 1) + memFib(n -2) cache[n] = result return result
true
e58f837ab1a161e23b8af68e15cb9095961ab52c
Moglten/Nanodegree-Data-structure-and-Algorithm-Udacity
/Data Structure/queue/reverse_queue.py
329
4.21875
4
def reverse_queue(queue): """ Given a Queue to reverse its elements Args: queue : queue gonna reversed Returns: queue : Reversed Queue """ stack = Stack() while not queue.is_empty(): stack.push(queue.dequeue()) while not stack.is_empty(): queue.enqueue(stack.pop())
true
38b7b5030e6d39b2adaabe73e14b40e637a14e3b
feleck/edX6001x
/lec6_problem2.py
623
4.1875
4
test = ('I', 'am', 'a', 'test', 'tuple') def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' result = () i = 0 while i < len(aTup): if i % 2 == 0: result += (aTup[i:i+1]) i+= 1 #print result return result # Solution from page: def oddTuples2(aTup): ''' Another way to solve the problem. aTup: a tuple returns: tuple, every other element of aTup. ''' # Here is another solution to the problem that uses tuple # slicing by 2 to achieve the same result return aTup[::2]
true
8781f9f96a111b4edb2772afc5bee20e7861a881
deadsquirrel/courseralessons
/test14.1mod.py
1,059
4.15625
4
''' Extracting Data from JSON In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: Sample data: http://python-data.dr-chuck.net/comments_42.json (Sum=2553) Actual data: http://python-data.dr-chuck.net/comments_204876.json (Sum ends with 78) ''' import urllib import json url = raw_input('Enter location: ') print 'Retrieving', url uh = urllib.urlopen(url) print uh data = uh.read() print 'Retrieved',len(data),'characters' print "----------------" print data info = json.loads(data) #print info sum = 0 #print json.dumps(info, indent=4) #print 'mm', info["comments"][0] #["count"] commentators = [] for item in info["comments"]: # print item # print item["count"] sum = sum + item["count"] commentators.append(item["name"]) print commentators print sum
true
97caae6c7fcaed2f8c0442dec8166a3c26b7caf5
pduncan08/Python_Class
/Wk3_Sec4_Ex3a.py
704
4.28125
4
# Lists - Exercise 3 # Python indexing starts at 0. This will come up whenever you # have items in a list format, so always remember to ask for # 1 less than whatt you want! John_Skills=["Python", "Communicateon", "Low Salary Request", 1000] print(John_Skills) Applicants=[["John", "Python"],["Geoff", "Doesn't Know Python"]] print(Applicants) # Create Lists of Lists heights=[["Jenny",61], ["Alexus",70],["Sam",67], ["Grace",64],["vik",68]] ages=[["Aaron",15],["Dhruti",16]] print(heights[2][1]) print(ages[0]) # You can use zip to create a new list names=["Jenny", "Alexus", "Samuel", "Grace"] skills=["Python", "R", "NOTHING","Python"] names_and_skills=zip(names, skills) print(names_and_skills)
true
5394d2d8237802a930e1c43b1fffc5fb1f2a1090
non26/testing_buitIn_module
/superMethod/test1_superMethod.py
603
4.53125
5
""" this super method example here takes the argument of two, first is the subClass and the second is the instance of that subClass so that the the subClass' instance can use the superClass' attributes STRUCTURE: super(subclass, instance) """ class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height self.area = width * height class Square(Rectangle): def __init__(self, length): # super() executes fine now super(Square, self).__init__(length, length) s = Square(5) print(s.area) # 25
true
f31816fec154d08f18eaa849cbd8d8ca3920bb2e
SoyUnaFuente/c3e3
/main.py
571
4.21875
4
score = int(input("Enter your score: ")) # if score in range(1, 51): # print (f"There is no prize for {score}") if 1 <= score <=50: print (f"There is no prize for {score}") elif 51 <= score <=150: medal = "Bronze" print(f"Congratulations, you won the {medal} medal for having {score} points ") elif 151 <= score <=180: medal = "Silver" print(f"Congratulations, you won the {medal} medal for having {score} points ") elif 181 <= score <=200: medal = "Gold" print(f"Congratulations, you won the {medal} medal for having {score} points ")
true
5c133a38fdca5f32432dbe164820ed62e249615c
cosmos-sajal/python_design_patterns
/creational/factory_pattern.py
1,035
4.21875
4
# https://dzone.com/articles/strategy-vs-factory-design-pattern-in-java # https://stackoverflow.com/questions/616796/what-is-the-difference-between-factory-and-strategy-patterns # https://stackoverflow.com/questions/2386125/real-world-examples-of-factory-method-pattern from abc import ABCMeta, abstractmethod class DBTable(metaclass=ABCMeta): @abstractmethod def create_table(self): pass class PostgreSQL(DBTable): def create_table(self): print("creating table in postgreSQL") class MongoDB(DBTable): def create_table(self): print("creating table in MongoDB") class DBFactory(): def __init__(self): """ change this db config in order to change the underlying DB """ self.db_config = 'sql' def get_database(self): if self.db_config == 'sql': return PostgreSQL() else: return MongoDB() print("creating table in database") db_factory = DBFactory() db = db_factory.get_database() db.create_table()
true
92d46625f1bb1bfe6e6a2a359af18f50770d540b
potnik/sea_code_club
/code/python/rock-paper-scissors/rock-paper-scissors-commented.py
2,585
4.5
4
#!/bin/python3 # The previous line looks like a comment, but is known as a shebang # it must be the first line of the file. It tells the computer that # this is a python script and to use python3 found in the /bin folder from random import randint # From the python module called random, import the function randint # randint returns a random integer in range [a, b], including both end points. # initiate some variables an assign them values play = True # this will be used to keep the game going if the user chooses to # These next three are to hold the score for reporting later draw = 0 # number of draw games pw = 0 # number of player wins cw = 0 # number of computer wins # The main part of the program consists of a while loop that runs the game # until the player tells it to quit while play==True: # while the value of the variable play equal True, keep running the game loop prompt = True # set the prompt variable to True while prompt == True: # keep prompting the player until they give the correct response player = input('rock(r), paper(p) or scissors(s)?') if player=='r' or player=='s' or player=='p': prompt=False else: print('Please enter r, p, or s') # Here we use randint to generate an integer. In this case, 1, 2, or 3 # this will map to the computers selection below chosen = randint(1,3) # A comment to remind us what each value means. Commenting you code is a good practice # 1 = rock (r) # 2 = paper (p) # 3 = scissors (s) # an if, elif, else block that assigns a letter to the value of chosen if chosen == 1: computer = 'r' elif chosen == 2: computer = 'p' else: # an else statement doesn't have a condition. computer = 's' print(player, ' vs ', computer) # A block of if statements to determine who wins if player == computer: print('DRAW!') draw = draw + 1 # these statements keep a running count of the score elif player == 'r' and computer == 's': print('Player Wins!') pw = pw + 1 elif player == 'p' and computer == 'r': pw = pw + 1 print('Player Wins') elif player == 's' and computer == 'p': pw = pw + 1 print('Player Wins!') else: print('Computer Wins!') cw = cw + 1 # prompt the user if they want to play again. # if they enter anything other than q, continue again=input('Play again? enter q to quit') if again=='q': play=False # Finally, print out the scoreboard print() print('Score') print('-----') print('Player: ', pw) print('Computer: ', cw) print('Draw: ', draw) print()
true
af908716f27a9ff46e623c883300cdcd7464d994
pranaychandekar/dsa
/src/basic_maths/prime_or_no_prime.py
1,199
4.3125
4
import time class PrimeOrNot: """ This class is a python implementation of the problem discussed in this video by mycodeschool - https://www.youtube.com/watch?v=7VPA-HjjUmU :Authors: pranaychandekar """ @staticmethod def is_prime(number: int): """ This method tells whether a given non-negative number is prime or not. :param number: The number which needs to be verified. :type number: int :return: The result whether the given number is prime or not. :rtype: bool """ result: bool = True if number < 2: result = False else: upper_limit = int(number ** 0.5) + 1 for i in range(2, upper_limit, 1): if number % i == 0: result = False return result return result if __name__ == "__main__": tic = time.time() number = 49 # Enter the number here if PrimeOrNot.is_prime(number): print("\nThe number", number, "is prime.") else: print("\nThe number", number, "is not prime.") toc = time.time() print("\nTotal time taken:", toc - tic, "seconds")
true
db56d84911eac1cae9be782fd2ebb047c625fce2
pranaychandekar/dsa
/src/sorting/bubble_sort.py
1,488
4.46875
4
import time class BubbleSort: """ This class is a python implementation of the problem discussed in this video by mycodeschool - https://www.youtube.com/watch?v=Jdtq5uKz-w4 :Authors: pranaychandekar """ @staticmethod def bubble_sort(unsorted_list: list): """ This method sorts a given list in ascending order using Bubble Sort algorithm. :param unsorted_list: The list which needs to be sorted. :type unsorted_list: list """ unsorted_list_size = len(unsorted_list) for i in range(unsorted_list_size - 1): all_sorted = True for j in range(unsorted_list_size - i - 1): if unsorted_list[j] > unsorted_list[j + 1]: temp = unsorted_list[j] unsorted_list[j] = unsorted_list[j + 1] unsorted_list[j + 1] = temp all_sorted = False if all_sorted: break if __name__ == "__main__": tic = time.time() print("\nYou are currently running Bubble Sort test case.") unsorted_list = [2, 7, 4, 1, 5, 3] print("\nUnsorted List: ") for element in unsorted_list: print(str(element), end=", ") print() BubbleSort.bubble_sort(unsorted_list) print("\nSorted List: ") for element in unsorted_list: print(str(element), end=", ") print() toc = time.time() print("\nTotal time taken:", toc - tic, "seconds.")
true
7e2f82c44c8df1de42f1026dcc52ecef804d9506
pranaychandekar/dsa
/src/basic_maths/prime_factors.py
1,324
4.25
4
import time class PrimeFactors: """ This class is a python implementation of the problem discussed in this video by mycodeschool - https://www.youtube.com/watch?v=6PDtgHhpCHo :Authors: pranaychandekar """ @staticmethod def get_all_prime_factors(number: int): """ This method finds all the prime factors along with their power for a given number. :param number: The non-negative number for which we want to find all the prime factors. :type number: int :return: All the prime factors with their corresponding powers. :rtype: dict """ prime_factors = {} upper_limit = int(number ** 0.5) + 1 for i in range(2, upper_limit, 1): if number % i == 0: count = 0 while number % i == 0: number /= i count += 1 prime_factors[i] = count if number != 1: prime_factors[int(number)] = 1 return prime_factors if __name__ == "__main__": tic = time.time() number = 99 prime_factors = PrimeFactors.get_all_prime_factors(number) print("\nThe prime factors of number", number, "are:", prime_factors) toc = time.time() print("\nTotal time taken", toc - tic, "seconds.")
true
2910d6bc150cfb5cfc60e5b31f9910d546027eda
karthikwebdev/oops-infytq-prep
/2-feb.py
1,943
4.375
4
#strings # str = "karthi" # print(str[0]) # print(str[-1]) # print(str[-2:-5:-1]) # print(str[-2:-5:-1]+str[1:4]) #str[2] = "p" -- we cannot update string it gives error #del str[2] -- this also gives error we cannot delete string #print("i'm \"karthik\"") --escape sequencing # print("C:\\Python\\Geeks\\") # print(r"I'm a \"Geek\"") # print(r"I'm a "Geek"") # print(r"C:\\Python\\Geeks\\")# --to print raw string #string formatting # print("{} hello {} hi".format(1,"hey")) # print("{0} hello {1} hi".format(1,"hey")) # print("{first} hello {second} hi".format(first=1,second="hey")) #logical operator in string # print("hello" and "hi") # if none of them is empty string then returns second string # print("hello" or "hi")# if none of them is empty string then returns first string # print("hi" or "") # if one them are empty but one is a string then returns that string # print("hello" and "") #both should be string returns empty string # print(not "hello") #false # print(not "") #true # def power(a, b): # """Returns arg1 raised to power arg2.""" # return a*b # print(power.__doc__ ) # different ways for reversing string # def rev1(s): # str = "" # for i in s: # str = i + str # return str # #using recursion # def rev2(s): # if len(s) == 0: # return s # else: # return rev2(s[1:])+s[0] # #most easy method # def rev3(s): # str = s[::-1] # return str # #using reversed method # #reversed method returns an iterator # #join used for joining iterables with a string # def rev4(s): # return "".join(reversed(s)) # print(rev1("karthik")) # print(rev2("karthik")) # print(rev3("karthik")) # print(rev4("karthik")) # #palindrome program # def palindrome(s): # if(s == s[::-1]): # print("yes") # else: # print("no") # palindrome("malayalam") str = "hello" str += " world" print(str) print("we " + "can " + "concatinate ")
true
29be4af3d652948430278ffe545f81c011643a1e
ronaka0411/Google-Python-Exercise
/sortedMethod.py
222
4.125
4
# use of sorted method for sorting elements of a list strs = ['axa','byb','cdc','xyz'] def myFn(s): return s[-1] #this will creat proxy values for sorting algorithm print(strs) print(sorted(strs,key=myFn))
true
d53ea1900d1bfc9ab6295430ac272616293cb09d
talebilling/hackerrank
/python/nested_list.py
1,480
4.3125
4
''' Nested Lists Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input: 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Output: Berry Harry ''' def main(): # if __name__ == '__main__': names_and_grades = [] names_and_grades = get_data(names_and_grades) name_list = get_lowest_grades(names_and_grades) printing(name_list) def get_data(names_and_grades): students = int(input()) for item in range(students): student_data = [] name = input() score = float(input()) student_data.append(score) student_data.append(name) names_and_grades.append(student_data) return names_and_grades def get_lowest_grades(names_and_grades): lowest = min(names_and_grades) second_lowest_list = [] for name_grade in names_and_grades: if name_grade[0] != lowest[0]: second_lowest_list.append(name_grade) second_lowest = min(second_lowest_list) name_list = [] for name_grade in second_lowest_list: if name_grade[0] == second_lowest[0]: name_list.append(name_grade[1]) return name_list def printing(name_list): name_list = sorted(name_list) print("\n".join(name_list)) main()
true
cc2355c574130c4b5244b930cb6c5c3160af40e3
KarimBertacche/Intro-Python-I
/src/14_cal.py
2,289
4.65625
5
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py [month] [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. Note: the user should provide argument input (in the initial call to run the file) and not prompted input. Also, the brackets around year are to denote that the argument is optional, as this is a common convention in documentation. This would mean that from the command line you would call `python3 14_cal.py 4 2015` to print out a calendar for April in 2015, but if you omit either the year or both values, it should use today’s date to get the month and year. """ import sys import calendar from datetime import datetime # Get length of command line arguments arg_length = len(sys.argv) # if length is more than 3, block execution and warn user if arg_length > 3: print("Exessive number of arguments passed in, \n expected 2 arguments representing the desired day and year as numeric values") sys.exit() # if inputed arguments are equal to 3 we assume those are numbers and pass them to the # calendar module and get the month and year based on the arguments elif arg_length == 3: print(calendar.month(int(sys.argv[2]), int(sys.argv[1]))) # if inputed arguments are equal to 2, that means no year has been specified, therefore # we show the month specified by the user of the current year elif arg_length == 2: print(calendar.month(datetime.now().year, int(sys.argv[1]))) # if no arguments have been provided, then we showcase the current month and year else: print(calendar.month(datetime.now().year, datetime.now().month))
true
1387e63d50e7170a0733e43c95da207acf0f5925
kagekyaa/HackerRank
/Python/005-for_while_loop_in_range.py
488
4.28125
4
'''https://www.hackerrank.com/challenges/python-loops Read an integer N. For all non-negative integers i<N, print i^2. See the sample for details. Sample Input 5 Sample Output 0 1 4 9 16 ''' if __name__ == '__main__': n = int(raw_input()) for i in range(0, n): print i * i ''' A for loop: for i in range(0, 5): print i And a while loop: i = 0 while i < 5: print i i += 1 Here, the term range(0,5) returns a list of integers from 1 to 5: [0,1,2,3,4]. '''
true
261a252acbfe4691fbee8166a699e3789f467e8b
franciscoguemes/python3_examples
/basic/64_exceptions_04.py
1,328
4.28125
4
#!/usr/bin/python3 # This example shows how to create your own user-defined exception hierarchy. Like any other class in Python, # exceptions can inherit from other exceptions. import math class NumberException(Exception): """Base class for other exceptions""" pass class EvenNumberException(NumberException): """Specific exception which inherits from MyGenericException""" pass class OddNumberException(NumberException): """Specific exception which inherits from MyGenericException""" pass def get_number(message): while True: try: number = int(input(message)) return number except ValueError: print("The supplied value is not a number, Try again...") stay = True while stay: try: num = get_number("Introduce any number (0 to exit):") if num == 0: stay = False elif num % 2 == 0: raise EvenNumberException else: raise OddNumberException except EvenNumberException: print("The number you introduced", num, "is Even!") except OddNumberException: print("The number you introduced", num, "is Odd!") # As example you can try to re-write this same application capturing the exception NumberException and using the # isinstance operator...
true
73cccc2cd1bbcea2da0015abc9ea0157be449844
franciscoguemes/python3_examples
/projects/calculator/calculator.py
1,434
4.3125
4
#!/usr/bin/python3 # This example is the typical calculator application # This is the calculator to build: # ####### # 7 8 9 / # 4 5 6 * # 1 2 3 - # 0 . + = # Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s import tkinter window = tkinter.Tk() #window.geometry("312x324") window.resizable(0,0) window.title("Calculator") tkinter.Label(window, text="0", anchor="e", bg="orange").grid(row=0, columnspan=4, sticky="nswe") #The 'sticky' option forces the element to fill all extra space inside the grid tkinter.Button(window, text="7").grid(row=1, column=0) tkinter.Button(window, text="8").grid(row=1, column=1) tkinter.Button(window, text="9").grid(row=1, column=2) tkinter.Button(window, text="/").grid(row=1, column=3) tkinter.Button(window, text="4").grid(row=2, column=0) tkinter.Button(window, text="5").grid(row=2, column=1) tkinter.Button(window, text="6").grid(row=2, column=2) tkinter.Button(window, text="x").grid(row=2, column=3) tkinter.Button(window, text="1").grid(row=3, column=0) tkinter.Button(window, text="2").grid(row=3, column=1) tkinter.Button(window, text="3").grid(row=3, column=2) tkinter.Button(window, text="-").grid(row=3, column=3) tkinter.Button(window, text="0").grid(row=4, column=0) tkinter.Button(window, text=".").grid(row=4, column=1) tkinter.Button(window, text="+").grid(row=4, column=2) tkinter.Button(window, text="=").grid(row=4, column=3) window.mainloop()
true
7244b8b9da478b14c71c81b2ff299da0e4b18877
franciscoguemes/python3_examples
/basic/06_division.py
697
4.4375
4
#!/usr/bin/python3 # Floor division // --> returns 3 because the operators are 2 integers # and it rounds down the result to the closest integer integer_result = 7//2 print(f"{integer_result}") # Floor division // --> returns 3.0 because the first number is a float # , so it rounds down to the closest integer and return it in float format. float_result = 7.//2 print(f"{float_result}") # Floor division // --> returns -4.0 because the floor division rounds the result down to the nearest integer # in this case rounding down is to -4 because -4 is lower than -3 !!! integer_result = -7.//2 print(f"{integer_result}") # Division / --> returns 3.5 float_result = 7/2 print(f"{float_result}")
true
e83ee865e27bc54b1c58fb9c220ef757d2df4de3
franciscoguemes/python3_examples
/advanced/tkinter/03_click_me.py
557
4.125
4
#!/usr/bin/python3 # This example shows how to handle a basic event in a button. # This basic example uses the command parameter to handle the click event # with a function that do not have any parameters. # Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s import tkinter window = tkinter.Tk() window.title("Handling the click event!") window.geometry('500x500') def say_hi(): tkinter.Label(window, text="Hello! I am here!").pack() tkinter.Button(window, text="Click Me!", command=say_hi).pack() window.mainloop()
true
776a51053306a024ab824003e63255c89cdbb6d4
franciscoguemes/python3_examples
/basic/09_formatting_strings.py
673
4.625
5
#!/usr/bin/python3 # TODO: Continue the example from: https://pyformat.info/ # There are two ways of formatting strings in Python: # With the "str.format()" function # Using the Old Python way through the "%" operator # Formatting strings that contain strings old_str = "%s %s" % ("Hello", "World") new_str = "{} {}".format("Hello", "World") print(old_str) print(new_str) # Formatting strings that contain integers old_str = "%d and %d" % (1, 2) new_str = "{} and {}".format(1, 2) print(old_str) print(new_str) # Formatting strings that contain float old_str = "%f" % (3.141592653589793) new_str = "{:f}".format(3.141592653589793) print(old_str) print(new_str)
true
b315f178386a8072670a9087e791c0f978cd2212
stianbm/tdt4113
/03_crypto/ciphers/cipher.py
1,223
4.28125
4
"""The file contains the parent class for different ciphers""" from abc import abstractmethod class Cipher: """The parent class for the different ciphers holding common attributes and abstract methods""" _alphabet_size = 95 _alphabet_start = 32 _type = '' @abstractmethod def encode(self, text, cipher_key): """Encode a text string using it's cipher and key and return encoded text""" return text @abstractmethod def decode(self, text, cipher_key): """Decode a text string using it's cipher and key and return decoded text""" return text def verify(self, text, cipher_key): """Check if the encoded - then decoded text is the same as original""" print('Type: ', self._type) print('Text: ', text) encoded = self.encode(text, cipher_key) print('Encoded: ', encoded) decoded = self.decode(encoded, cipher_key) print('Decoded: ', decoded) if text == decoded: print('VERIFIED') print() return True print('NOT VERIFIED') print() return False @abstractmethod def possible_keys(self): """Return all possible keys"""
true
9c20ceec0fdccd3bc2bb92815e56b7a99855058a
cindy859/COSC2658
/W2 - 1.py
721
4.15625
4
def prime_checker(number): assert number > 1, 'number needs to be greater than 1' number_of_operations = 0 for i in range(2, number): number_of_operations += 3 #increase of i, number mod i, comparision if (number % i) == 0: return False, number_of_operations # returning multiple values (as a tuple) return True, number_of_operations # returning multiple values (as a tuple) numbers = [373, 149573, 1000033, 6700417] for number in numbers: (is_prime, number_of_operations) = prime_checker(number) if is_prime: print(number, "is prime") else: print(number, "is not prime") print('Number of operations:', number_of_operations) print('')
true
bdc290072854219917fe8a24ef512b26d38e93f9
TecProg-20181/02--matheusherique
/main.py
1,779
4.25
4
from classes.hangman import Hangman from classes.word import Word def main(): guesses = 8 hangman, word = Hangman(guesses), Word(guesses) secret_word, letters_guessed = hangman.secret_word, hangman.letters_guessed print'Welcome to the game, Hangman!' print'I am thinking of a word that is', len(secret_word), ' letters long.' word.join_letters(secret_word) print'-------------' while not hangman.is_word_guessed() and guesses > 0: print'You have ', guesses, 'guesses left.' hangman.stickman(guesses) available = word.get_available_letters() for letter in available: if letter in letters_guessed: available = available.replace(letter, '') print'Available letters', available letter = raw_input("Please guess a letter: ") if letter in letters_guessed: letters_guessed.append(letter) guessed = word.letter_guessed(secret_word, letters_guessed) print'Oops! You have already guessed that letter: ', guessed elif letter in secret_word: letters_guessed.append(letter) guessed = word.letter_guessed(secret_word, letters_guessed) print'Good Guess: ', guessed else: guesses -= 1 letters_guessed.append(letter) guessed = word.letter_guessed(secret_word, letters_guessed) print"Oops! That letter is not in my word: ", guessed print'------------' else: if hangman.is_word_guessed(): hangman.stickman(guesses) print'Congratulations, you won!' else: hangman.stickman(guesses) print'Sorry, you ran out of guesses. The word was ', secret_word, '.' main()
true
327d89760aca774d4cf1019eda5c88cadc469502
arossbrian/my_short_scripts
/multiplier.py
405
4.15625
4
##This is a multiply function #takes two figures as inputs and multiples them together def multiply(num1, num2): multiplier = num1 * num2 return multiplier input_num1 = input("Please enter the first value: ") input_num2 = input("Enter the Second Value: ") ##input_num1 = int(input_num1) ##input_num2 = int(input_num2) Answer = multiply(int(input_num1), int(input_num2)) print(Answer)
true
f8b914676da0c034a908c3e440313e6633264068
arossbrian/my_short_scripts
/shoppingbasketDICTIONARIES.py
492
4.15625
4
print (""" Shopping Basket OPtions --------------------------- 1: Add item 2: Remove item 3: View basket 0: Exit Program """) shopping_basket = {} option = int(input("Enter an Option: ")) while option != 0: if option == 1: item = input("Add an Item :") qnty = int(input("Enter the quantity: ")) for item, qnty in shopping_basket.items(): print(item) #print(shopping_basket) #elif option == 2:
true
36ec1104b30f90707920614405bc83cd5a2f7e40
yeonsu100/PracFolder
/NewPackage01/LambdaExample.py
601
4.5
4
# Python program to test map, filter and lambda # Function to test map def cube(x): return x ** 2 # Driver to test above function # Program for working of map print "MAP EXAMPLES" cubes = map(cube, range(10)) print cubes print "LAMBDA EXAMPLES" # first parentheses contains a lambda form, that is # a squaring function and second parentheses represents # calling lambda print(lambda x: x ** 2)(5) # Make function of two arguments that return their product print(lambda x, y: x * y)(3, 4) print "FILTER EXAMPLE" special_cubes = filter(lambda x: x > 9 and x < 60, cubes) print special_cubes
true
c30cd41b41234884aea693d3d0893f2889bd5f1d
deeptivenugopal/Python_Projects
/edabit/simple_oop_calculator.py
605
4.125
4
''' Simple OOP Calculator Create methods for the Calculator class that can do the following: Add two numbers. Subtract two numbers. Multiply two numbers. Divide two numbers. https://edabit.com/challenge/ta8GBizBNbRGo5iC6 ''' class Calculator: def add(self,a,b): return a + b def subtract(self,a,b): return a - b def multiply(self,a,b): return a * b def divide(self,a,b): return a // b calculator = Calculator() print(calculator.add(10, 5)) print(calculator.subtract(10, 5)) print(calculator.multiply(10, 5)) print(calculator.divide(10, 5))
true
6598f0f714711ea063ef0f160e65847cc9dfa295
fiberBadger/portfolio
/python/collatzSequence.py
564
4.15625
4
def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 else: print(3 * number + 1) return 3 * number + 1 def app(): inputNumber = 0 print('Enter a number for the collatz functon!') try: inputNumber = int(input()) except (ValueError, UnboundLocalError): print('invalid number') if not inputNumber or inputNumber < 0: print('Enter an absolute number!') else: while inputNumber != 1: inputNumber = collatz(inputNumber) app()
true
f416c4993cfc11e8ca6105d48168d42952f55aa3
fiberBadger/portfolio
/python/stringStuff.py
813
4.125
4
message = 'This is a very long message' greeting = 'Hello' print(message); print('This is the same message missing every other word!'); print(message[0:5] + message[8:9] + ' ' + message[15:19]); print('The length of this string is: ' + str(len(message)) + 'chars long'); print('This is the message in all lower case ' + message.lower()); print('This is the message in all upper case ' + message.upper()); print('This message has: ' + str(message.count('s')) + ' S\'es'); print('The word "very" starts at' + str(message.find('very'))); print('The word long is replaced' + message.replace('Long', 'Short')); greeting += ' World' print('This string is contatianted: ' + greeting); print('This is a formated string:' + '{}, {} !'.format('Hello', 'World')); print('This is a "F" string' + f'{greeting}, {message}');
true