blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7cfa1c977434c386eb3738bb15c0510c2a587563
adityaapi444/beginner_game
/chocwrap.py
1,004
4.1875
4
#chocolate wrapper puzzle game # price of one chocolate=2 #you will get 1 chocolate by exchanging 3 wrapper #write a program to count how many chocolates can you eat in 'n' money # n is input value for money #ex. #input: money=20 #output: chocolate=14 wrapper remains: 2 money=int(input("ente your money")) c=w=0 if money>0: #chocolate count by exchange with money c+=money//2 w+=c #wrapper count based on chocolate got print('Chocolates:',c,'Wrapper :',w) while(w>=3): #check at least 3 wrapper remaining d=w//3 #chocolate got by xchng with wrapper c+=d #update chocolate count by ading (d) w=w%3+d #update the wrapper count print('Chocolates:',c,'Wrapper :',w) if(w<3): #break if wrapper less than 3 break
true
681b785e3f09a24c8ab87c58aa759a588ce30e51
esterwalf/python-basics
/rosette or polygon.py
1,005
4.5625
5
>>> import turtle >>> t = turtle.Pen() >>> number = int(turtle.numinput("Number of sides or circles", "How many sides or circles in your shape?", 6)) >>> shape = turtle.textinput("which shape do you want?", "Enter 'p' for polygon or 'r' for rosette:") >>> for x in range(number): if shape == 'r': t.circle(100) t.left(95) else: t.forward (150) t.left(360/number) >>> import turtle >>> t = turtle.Pen() >>> sides = int(turtle.numinput("Number of sides", "How many sides in your spiral?")) >>> for m in range(5,75): #our outer spiral loop for polygons and rosettes, from size 5-75 t.left(360/sides + 5) t.width(m//25+1) t.penup() #don't draw lines on spiral t.forward(m*4) #move to next corner t.pendown() #get ready to draw if (m % 2 == 0): for n in range(sides): t.circle(m/3) t.right(360/sides) else: #or, draw a little polygon at each ODD corner of the spiral for m in range(sides): t.forward(m) t.right(360/sides)
true
989eeaea35c3342c9476735031a4ea1ae496c878
elaguerta/Xiangqi
/ElephantPiece.py
1,777
4.21875
4
from Piece import Piece class ElephantPiece(Piece): """Creates ElephantPieces elephant_positions is a class variable, a dictionary of initial positions keyed by player color Two ElephantPieces are created by a call to Player.__init__().""" elephant_positions = { 'red': ['c1', 'g1'], 'black': ['c10', 'g10'] } # legal_ranks is a class variable, a set of ranks that elephants may occupy keyed by player side # Elephants cannot cross the river. legal_ranks = { 'red': {'1','2','3','4','5'}, 'black': {'10','9','8','7','6'} } def __init__(self, side, board, id_num): """ Initializes an Elephant Piece. The side ('red' or 'black'), the Board, and the id_num of this piece are passed as arguments. """ super().__init__(side, board) self._movement = 'diagonal' # Elephants move diagonal self._path_length = 2 # Elephants move 2 points # assign a position from ElephantPiece self._id = id_num # id_num is passed as argument, by Player, and will be 1 or 2 self._pos = ElephantPiece.elephant_positions[side][id_num - 1] # keep track of positions used based on id number def __repr__(self): """Return an informative label for this Piece: ["r" or "b"] + "El" + [id_num for this specific piece]. This is intended to be unique for every piece in a Game """ return self._side[0] + "El" + str(self._id) def is_legal(self, to_pos): """ call Piece.is_legal() with additional restriction that Elephants stay within their legal ranks, i.e. they don't cross the river.""" return super().is_legal(to_pos) and to_pos[1:] in ElephantPiece.legal_ranks[self._side]
true
fef6a53d7ac9e0a73aaf7f8a6168c6b2761c2e90
rambabu519/AlgorithmsNSolutions
/Valid_paranthesis.py
1,533
4.125
4
''' 20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true ''' class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] dt = {'(':')','{':'}','[':']'} # Taken another local storage to avoid iterating through keys for each character in string dtk = dt.keys() for c in s: #If it is open paranthesis then PUSH to stack if c in dt.keys): stack.append(c) #If it is closed paranthesis then pop from stack and compare with current closed paranthesis elif stack: if dt[stack.pop()] != c: return False # This case is when a single open closed paranthesis is present else: return False # if no characters remaining in string and still stack is not empty then given string is not valid if stack: return False else: return True
true
4c775b35a1f0a0b9ff4484564abcdfadc8273e01
kemar1997/Python_Tutorials
/range_and_while.py
1,213
4.5
4
# creates a for loop that iterates through nine times starting with 0 # the range function is equivalent to creating a list but within the for loop only # Remember: Computers always start counting from 0 # the range function also accepts a range of numbers so the iteration doesn't necessarily, # have to start from exactly 0 # when we have two numbers we have a beginning and an end """ when you use three numbers inside of the range function you have the beginning number then where you want it to end at and lastly the increment value of the range, an example would be range(10, 40, 5) = this is saying that the range starts at 10 and ends at 40 but goes up by 5 for each number so it would give an output of 10, 15, 20, 25, 30, 35 """ # for x in range(10, 40, 5): # print(x) """ A while loop is a special loop that loops as long as the condition is true. So you don't explicitly give a list or a range of numbers. Keeps looping until a condition becomes false. """ x = 2 # keeps outputting the number 5 cause the condition is always true # creating a way to change the variable so that the while knows when to stop is ideal # you never really want an infinite loop while x < 10: print(x) x += 2
true
20781199bff842884181faa97ec7af6d40b239dd
kemar1997/Python_Tutorials
/keyword_arguments.py
991
4.4375
4
# name, action, and item are keywords that hold values either strings or numbers # these keywords can have a default value which can be set in the parentheses below def dumb_sentence(name='Kemar', action='ate', item='tuna.'): print(name, action, item) dumb_sentence() # keyword arguments are taken in the function in the order you first put them in as dumb_sentence('Sally', 'made', 'a banana and strawberry smoothie for breakfast.') # there are gonna be certain times when you just want to pass in the second argument # or maybe pass in the third one and so on. whenever you want to pass in a limited # amount of arguments or pass them in a different order this example shows you how # First off you need to utilize the keywords of the arguments and equal it to something # in the parentheses below, so for instance.. i changed the item argument and set it equal # to "awesome" so when I run it, it returns the sentence "Kemar ate awesome". dumb_sentence(item='awesome', action='is')
true
076c7e2aa32dcc8aef746adb9c52fd64a742106d
halamsk/checkio
/checkio_solutions/O'Reilly/cipher_crossword.py
2,329
4.3125
4
#!/usr/bin/env checkio --domain=py run cipher-crossword # Everyone has tried solving a crossword puzzle at some point in their lives. We're going to mix things up by adding a cipher to the classic puzzle. A cipher crossword replaces the clues for each entry with clues for each white cell of the grid. These clues are integers ranging from 1 to 26, inclusive. The objective, as any other crossword, is to determine the proper letter for each cell. In a cipher crossword, the 26 numbers serve as a cipher for those letters: cells that share matching numbers are filled with matching letters, and no two numbers stand for the same letter. All resulting entries must be valid words. # # For this task you should solve the cipher crossword. You are given a crossword template as a list of lists (2D array) with numbers (from 0 to 26), where0is a blank cell and other numbers are encrypted letters. You will be given a list of words for the crossword puzzle. You should fill that template with a given word and return the solved crossword as a list of lists with letters. Blank cells are replaced with whitespaces (0 => " "). # # The words are placed in rows and columns with NO diagonals. The crossword contains six words with 5 letters each. These words are placed in a grid. # # # # Input:The Cipher Crossword as a list of lists with integers. Words as a list of strings. # # Output:The solution to the Crossword as a list of lists with letters. # # Precondition: # |crossword| = 5x5 # ∀ x ∈ crossword : 1 ≤ x ≤ 26 # # # END_DESC def checkio(crossword, words): return None if __name__ == '__main__': assert checkio( [ [21, 6, 25, 25, 17], [14, 0, 6, 0, 2], [1, 11, 16, 1, 17], [11, 0, 16, 0, 5], [26, 3, 14, 20, 6] ], ['hello', 'habit', 'lemma', 'ozone', 'bimbo', 'trace']) == [['h', 'e', 'l', 'l', 'o'], ['a', ' ', 'e', ' ', 'z'], ['b', 'i', 'm', 'b', 'o'], ['i', ' ', 'm', ' ', 'n'], ['t', 'r', 'a', 'c', 'e']]
true
70573b9422a6e9b4122522882bf71f6dc902d9a8
No-Life-King/school_stuff
/CSC 131 - Intro to CS/philip_smith.py
1,280
4.21875
4
def mult_tables_one(num): """ Prints a row of the multiplication table of the number 'num' from num*1 to num*10. """ print(num, end="\t") for x in range(1, 11): print(x*num, end='\t') print('\n') def mult_tables_two(start, end): """ Prints the rows of the multiplication table from the specified starting point to the specified ending point. The columns go from 1 to 10. """ print("\t", end='') for x in range(1, 11): print(x, end='\t') print('\n') for y in range(start, end+1): mult_tables_one(y) def is_prime(x): """ Returns true if 'x' is prime, otherwise false. """ if (x == 2): return True for a in range(2, x//2+2): if (x%a==0): return False return True def prime_split(num): """ Accepts an integer input and returns the integer as the sum of two primes. """ if (num <= 2 or num%2==1): return "Improper Number" for x in range(2, num): if (is_prime(x) and is_prime(num-x)): return str(x) + "+" + str(num-x) #mult_tables_one(8) #mult_tables_two(1, 10) #print(is_prime(34)) #print(prime_split(8490))
true
259f11820d403abfd022a319693f15bf0e17156f
nandhinipandurangan11/CIS40_Chapter3_Assignment
/CIS40_Nandhini_Pandurangan_P3_3.py
1,478
4.1875
4
# CIS40: Chapter 3 Assignment: P3.3: Nandhini Pandurangan # This program uses a function to solve problem 3.3 # P3.3: Write a program that reads an integer and prints how many digits # the number has, by checking whether the number >= 10, >= 100 and so on. # (Assume that all integers are less than 10 billion) >> 10 billion >> 10,000, 000, 000 # if the number is negative, multiply it by -1 first # in this context, 0 has 1 digit import math def output_digits(): flag = True num = 0 # input validation while flag: try: num = abs(int(input("Please enter an integer: "))) flag = False except: print("\n ----- Please enter a valid integer ----- \n") # evaluating the input using by checking it against incrementing powers of 10 for i in range (1, 11): digit_counter = math.pow(10, i) if num < digit_counter: print("The number has {0} digit(s)".format(i)) break # calling the function to solve the problem output_digits() ''' Output: Please enter an integer: 1000000 The number has 7 digit(s) ------------------------------------------------- Please enter an integer: hi ----- Please enter a valid integer ----- Please enter an integer: 2jehr3u ----- Please enter a valid integer ----- Please enter an integer: 0 The number has 1 digit(s) ------------------------------------------------- Please enter an integer: 321333980 The number has 9 digit(s) '''
true
c6f2dd94451ab8a2877335b133e1a4b8b0e5c838
betyonfire/gwcexamples
/python/scramble.py
475
4.21875
4
import random print "Welcome to Word Scramble!\n\n" print "Try unscrambling these letters to make an english word.\n" words = ["apple", "banana", "peach", "apricot"] while True: word = random.choice(words) letters = list(word) random.shuffle(letters) scramble = ''.join(letters) print "Scrambled: %s" % scramble guess = raw_input("What word is this? ") if guess == word: print "\nThat's right!\n" else: print "\nNo, the word was %s\n" % word
true
f5be1bc6340012b3b3052e8f6a45df116a1c2d5c
Zahidsqldba07/CodeSignal-solutions-2
/Arcade/Intro/growingPlant.py
1,072
4.53125
5
def growingPlant(upSpeed, downSpeed, desiredHeight): import itertools for i in itertools.count(): if upSpeed >= desiredHeight: return 1 elif i*upSpeed - (i-1)*downSpeed >= desiredHeight: return i '''Caring for a plant can be hard work, but since you tend to it regularly, you have a plant that grows consistently. Each day, its height increases by a fixed amount represented by the integer upSpeed. But due to lack of sunlight, the plant decreases in height every night, by an amount represented by downSpeed. Since you grew the plant from a seed, it started at height 0 initially. Given an integer desiredHeight, your task is to find how many days it'll take for the plant to reach this height. Example For upSpeed = 100, downSpeed = 10, and desiredHeight = 910, the output should be growingPlant(upSpeed, downSpeed, desiredHeight) = 10. # Day Night 1 100 90 2 190 180 3 280 270 4 370 360 5 460 450 6 550 540 7 640 630 8 730 720 9 820 810 10 910 900 The plant first reaches a height of 910 on day 10.'''
true
a288cdf0c28d593175e59f2e8fdff0a2c26cd98f
OmkarD7/Python-Basics
/22_assignment.py
766
4.28125
4
from functools import reduce #find the sum of squares of all numbers less than 10 numbers = [5, 6, 11, 12] sum = reduce(lambda a,b:a+b, map(lambda a:a*a, filter(lambda n: n <= 10, numbers))) print("sum of squares of all numbers which are less than 10: ",sum) #other way without using lambda def fun1(a, b): return a+b def fun2(c): return c*c def fun3(d): if d<10: return True else: return False sum = reduce(fun1, map(fun2,filter(fun3, numbers))) print("sum of squares of all numbers \ which are less than 10 \ without using lambda function: ", sum) #find the sum of square of all even numbers sum = reduce(lambda n1,n2:n1+n2, map(lambda n:n*n, filter(lambda n: n%2 ==0, numbers))) print("sum of squares of all even numbers: ",sum)
true
709a63ba721c447fad84ff309e45adc0774d29f5
egosk/codewars
/ML - Iris flower - Scikit/Iris flower - ML - basic exercises.py
1,849
4.125
4
# ML exercises from https://www.w3resource.com/machine-learning/scikit-learn/iris/index.php import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy import sparse # 1. Write a Python program to load the iris data from a given csv file into a dataframe and print the shape of the # data, type of the data and first 3 rows. data = pd.read_csv("iris.csv", delimiter='\t') print('Data shape: ', data.shape) print('Data type: ', type(data)) print('First 3 rows:\n', data[:3]) #data.head(3) # 2. Write a Python program using Scikit-learn to print the keys, number of rows-columns, feature names and the # description of the Iris data. print('Keys: ', data.keys()) print('Number rows-columns: ', len(data), '-', len(data.columns)) # 3. Write a Python program to get the number of observations, missing values and nan values. print('Number of observations, missing values, Nan values:') print(data.info()) # data.isnull().values.any() # data.isnull().sum() # 4. Write a Python program to create a 2-D array with ones on the diagonal and zeros elsewhere. Now convert the # NumPy array to a SciPy sparse matrix in CSR format. eye = np.eye(5) print(eye) new_eye = sparse.csr_matrix(eye) print('CSR:\n', new_eye) # 5. Write a Python program to get observations of each species (setosa, versicolor, virginica) from iris data. print('Number of samples per specie:') print(data['Species'].value_counts()) # 6. Write a Python program to view basic statistical details like percentile, mean, std etc. of iris data. print('Statistical details:') print(data.describe()) # 7. Write a Python program to access first four columns from a given Dataframe using the index and column labels. new_df = data[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']] print(new_df) new_df_2 = data.iloc[:, :4] print(new_df_2)
true
da877bb35d8f3728d2bf91305c8b30e46819b30c
egosk/codewars
/print directory contents.py
606
4.15625
4
""" This function takes the name of a directory and prints out the paths files within that directory as well as any files contained in contained directories. This function is similar to os.walk. Please don't use os.walk in your answer. We are interested in your ability to work with nested structures. """ import os def print_directory_contents(sPath): for direc in os.listdir(sPath): path = os.path.join(sPath, direc) if os.path.isdir(path): print_directory_contents(path) else: print(path) print_directory_contents('/Users/emila/Desktop/codewars')
true
088f07aec3fa090ff61b70376bf6e2f169f2241a
Bhumi248/finding_Squareroot_in_python
/squareroot.py
351
4.1875
4
#importing pakage import math print "enter the number u want to squreroot" a=int(input("a:")) #for finding square root there is defuslt function sqrt() which can be accessible by math module print" square_root=",math.sqrt(a) #finding square root without use of math module like:x**.5 print "squareroot using second method" print a**.5
true
ebdd28443a4eb602e246e5284e300344ce5cd9bf
nihagopala/PythonAssignments
/day3/MaxInThreeNos.py
700
4.5
4
#-----------------------------------------------------------# #Define a function max_of_three() that takes three numbers as # arguments and returns the largest of them. #-----------------------------------------------------------# def Max_Three(a,y,z): max_3 = 0 if a > y: if a > z: max_3 = a else: max_3 = z else: if y > z: max_3 = y else: max_3 = z return max_3 num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) num3 = int(input("Enter the third number:")) print("The largest number of three numbers is", Max_Three(num1, num2, num3))
true
6bcc913eed3ed4d99c607fb12c0400017b247a9e
nihagopala/PythonAssignments
/day1/15. SetOfOperations.py
545
4.53125
5
#----------------------------------------------------------# #Program to print the result of different set of operations #----------------------------------------------------------# set1 = {0, 2, 4, 6, 8}; set2 = {1, 2, 3, 4, 5}; # set union print("Union of set1 and set2 is",set1 | set2) # set intersection print("Intersection of set1 and set2 is",set1 & set2) # set difference print("Difference of set1 and set2 is",set1 - set2) # set symmetric difference print("Symmetric difference of set1 and set2 is",set1 ^ set2)
true
8ba142c74997a10c79bf39bcfca62307c8f3eb89
bs4/LearnPythontheHardWay
/ex32drill.py
2,263
4.625
5
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in items for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range (0, 6): print "Adding %d to the list." % i # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Element was: %d" % i # RANGE PRACTICE # range(start, stop[, step]) # below line is just the stop part of above range() # leaves out the stop integer # oh, also starts at zero, that must be default # below line prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print range(10) # below line prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print range(1, 11) # below line prints: [0, 5, 10, 15, 20, 25] # counts up to 30 by fives, 5 is step print range (0, 30, 5) # below line prints:[0, 6, 12, 18, 24] print range (0, 30, 6) # below line prints: [0, 5, 10, 15, 20, 25, 30] # even tho not a step of 5, still counts all steps of 5 up to stop point 31 print range (0, 31, 5) # below line prints: [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] print range (0, -10, -1) # below line prints: TypeError expected integer step, got float #print range (0, 10, .5) # lol, i had to put a # in front of above line or python won't print # after it, haha # STUDY DRILL 2 elementP = [range(0, 6)] for x in elementP: print "This is practice number: %s" % x #...hmm, i think i did this wrong, i think i should be using .append elementG = #...hmm, i don't quite get Study Drill 2, gonna have to come back... # COMMON QUESTION 3 # This took me a sec typing into Python. good practive tho, i created a list # test = [] # then created 2 different variables that were equal to lists of words # then i separately appended (added) each variables list to test # cool
true
5958d7e44c80a44c98a28c64c9451631525f27c5
bs4/LearnPythontheHardWay
/ex06drill.py
2,124
4.125
4
# The below line gives a value for variable x, the value is a string that has a formatter in it x = "There are %d types of people." % 10 # The below line gives a value for the variable "binary", I think doing this is a joke of sorts binary = "binary" # The below line gives a value for the variable "do_not", the value is a contraction of the variable do_not = "don't" # The below line gives variable "y" a value of a string with formatters, there are variables in the string for variable "y" y = "Those who know %s and those who %s." % (binary, do_not) # The below line says to print variable "x" print x # The below line says to print variable "y" print y #The below line inserts variable "x" using %r formatter. %r formatter prints exactly as it is written. ie-(') single quotes are included. #Zed does this to quote the above string, basically "I said "variable x" print "I said: %r." % x # The below line inserts variable y using %s formatter. In this instance, Zed puts (') singles quotes around %s so that the value put into the string looks quoted. # Zed had to use single quote for the below line since he used %s instead of %r. It could read - print "I also said: %r." % y # *Note* using %r in the line above, *POSSIBLY* since there are already (") double quotes, when it pulls "y" using %r, it changes the (") double quotes in "y" to single quotes print "I also said: %r." % y # The below line gives variable "hilarious" a value of "False" hilarious = False # The below line gives variable joke_evaluation a value of a string with a formatter joke_evaluation = "Isn't that joke so funny?! %r" # The below line uses variable "joke_evaluation" as short hand for the string which is it's value...SO instead of writing out the string everytime, you could just use "joke_evaluation", aha! # Notice the % after joke evaluation is just as if you typed -- print "Isn't that joke so fully?! %r" % then added variable "hilarious", aha! print joke_evaluation % hilarious # The below lines are just a play on words or a joke...I think :) w = "This is the left side of..." e = "a string with a right side." print w + e
true
ada0873f48aba1239e05d845c2bb457cda744af4
bs4/LearnPythontheHardWay
/ex18drill.py
1,643
4.5
4
# this one is like your scripts with argv. The below line has a *, it tells python to take all arguments to the function and put them in args as a list def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'." # this one is putting a lot of words in a row, just for function def in_a_row(a, b, c, d, e, f, g, h, i, j, k): print "a: %r, b: %r, c: %r, d: %r, e: %r, f: %r, g: %r, h: %r, i: %r, j: %r, k: %r" % (a, b, c, d, e, f, g, h, i, j, k) # this one is...going to attempt raw_input...lol, don't know if this will work. it did, that took some maneuvering tho LOL! def user_def(var1): print "Now we attempt the old raw_input." girl = raw_input("What is your daughters name?") print "Your girl is %r and your son is %r." % (girl, var1) # this one will attempt to read some text in a file. There it is. When I call/run/use the function "filetext" below it will print whatever is in the .txt file...i think lol def filetext(text1): print "Now we attempt to open and read some text from a file." wife = open(text1).read() print wife print_two("Brandon","Smith") print_two_again("Brandon","Smith") print_one("First!") print_none() in_a_row('apple', "bee", "cat", "dog", "eel", "fan", "git", "hat", "ick", "jack", "kick") user_def("Noah") filetext("ex18_sample.txt")
true
f30c80da1a3ca8b3c3b34359cc1f7ecb6f0004bc
alinabalgradean/algos
/insertion_sort.py
413
4.25
4
def InsertionSort(lst): """Basic Insertion sort. Args: lst [list]: The list to be sorted. Returns: lst [list]: Sorted list. """ for index in range(1, len(lst)): position = index temp_value = array[lst] while position > 0 and lst[position - 1] > temp_value: lst[position] = lst[position - 1] position -= 1 lst[position] = temp_value return lst
true
8dd255cbd492106fcfde67c9221698df5a85045f
andrewlidong/PythonSyntax
/Top18Questions/11_determineValidNum.py
2,176
4.125
4
''' 11. Determine if the number is valid Given an input string, determine if it makes a valid number or not. For simplicity, assume that white spaces are not present in the input. 4.325 is a valid number. 1.1.1 is NOT a valid number. 222 is a valid number. is NOT a valid number. 0.1 is a valid number. 22.22. is NOT a valid number. Solution: To check if a number is valid, we’ll use the state machine below. The initial state is start, and we’ll process each character to identify the next state. If the state ever ends up at unknown or in a decimal, the number is not valid. Time: O(N) Space: O(1) ''' class STATE: START, INTEGER, DECIMAL, UNKNOWN, AFTER_DECIMAL = range(5) def get_next_state(current_state, ch): if (current_state is STATE.START or current_state is STATE.INTEGER): if ch is '.': return STATE.DECIMAL elif ch >= '0' and ch <= '9': return STATE.INTEGER else: return STATE.UNKNOWN if current_state is STATE.DECIMAL: if ch >= '0' and ch <= '9': return STATE.AFTER_DECIMAL else: return STATE.UNKNOWN if current_state is STATE.AFTER_DECIMAL: if ch >= '0' and ch <= '9': return STATE.AFTER_DECIMAL else: return STATE.UNKNOWN return STATE.UNKNOWN def is_number_valid(s): if not s: return True i = 0 if s[i] is '+' or s[i] is '-': i = i + 1 current_state = STATE.START for c in s[i:]: current_state = get_next_state(current_state, c) if current_state is STATE.UNKNOWN: return False i = i + 1 if current_state is STATE.DECIMAL: return False return True print("Is the number valid 4.325? ", is_number_valid("4.325")) print("Is the number valid 1.1.1? ", is_number_valid("1.1.1")) print("Is the number valid 222? ", is_number_valid("222")) print("Is the number valid 22.? ", is_number_valid("22.")) print("Is the number valid 0.1? ", is_number_valid("0.1")) print("Is the number valid 22.22.? ", is_number_valid("22.22.")) print("Is the number valid 1.? ", is_number_valid("1."))
true
fd8ea6ece01e686a8beef54bc5af3b8dfab593bf
andrewlidong/PythonSyntax
/Top18Questions/3_sumOfTwoValues.py
1,277
4.21875
4
''' 3. Sum of two values Given an array of integers and a value, determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists and return false if it does not. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. SOLUTION In this solution, you can use the following algorithm to find a pair that add up to the target (say val). Scan the whole array once and store visited elements in a hash set. During scan, for every element e in the array, we check if val - e is present in the hash set i.e. val - e is already visited. If val - e is found in the hash set, it means there is a pair (e, val - e) in array whose sum is equal to the given val. If we have exhausted all elements in the array and didn’t find any such pair, the function will return false. # Time: O(N) # Space: O(N) ''' def find_sum_of_two(A, val): found_values = set() for a in A: if val - a in found_values: return True found_values.add(a) return False v = [5, 7, 1, 2, 8, 4, 3] test = [3, 20, 1, 2, 7] for i in range(len(test)): output = find_sum_of_two(v, test[i]) print("find_sum_of_two(v, " + str(test[i]) + ") =" + str(output))
true
e93d0ce781eb3ff8e8ed1515c3ccc49fb0c47dd9
drewAdorno/Algos
/Python Algos.py
2,200
4.125
4
import math '''Sara is looking to hire an awesome web developer and has received applications from various sources. Her assistant alphabetized them but noticed some duplicates. Given a sorted array, remove duplicate values. Because array elements are already in order, all duplicate values will be grouped together. As with all these array challenges, do this without using any built-in array methods. Second: solve this without using any nested loops.''' def removeDuplicates(arr): newArr=[arr[0]] for i in range(1,len(arr)): if arr[i]!=newArr[len(newArr)-1]: newArr.append(arr[i]) return newArr # Array: Remove Negatives # Implement removeNegatives() that accepts an array, removes negative values, and returns the same array # (not a copy), preserving non-negatives’ order. As always, do not use built-in array functions. # Second: don’t use nested loops. def removeNegatives(arr): x = 0 while x < len(arr): if arr[x] < 0: arr.pop(x) else: x+=1 return arr #1,-2,3,4,5 #  Array: Second-to-Last # Return the second-to-last element of an array. Given [42,true,4,"Kate",7], return "Kate". If array is too short, # return null. def secondToLast(arr): if(len(arr)>=2): return arr[len(arr)-2] else: return None #  Array: Nth-to-Last # Return the element that is N-from-array’s-end. Given ([5,2,3,6,4,9,7],3), return 4. If the array is too short, # return null. #condition_if_true if condition else condition_if_false def nth_to_last(arr, i): return arr[len(arr) - i] if len(arr) >= i else None #  Array: Second-Largest # Return the second-largest element of an array. Given [42,1,4,Math.PI,7], return 7. If the array is too short, # return null. def secondLargest(arr): arr.sort(reverse=True) return arr[1] if len(arr)>=2 else None #  Array: Nth-Largest # Liam has "N" number of Green Belt stickers for excellent Python projects. Given arr and N, return the Nth largest element, where (N-1) elements are larger. Return null if needed. def nth_largest(arr, n): arr.sort(reverse=True) print(arr) return arr[n - 1] if len(arr)>=n else None
true
3bb64b4540bed752e3f748ce0af80e2657d373e4
carcagi/hpython
/part1/P2_looping.py
1,393
4.25
4
# while loops # Not i++ avaiable i = 0 while i <= 5: # print(i) i += 1 # break and continue i = 0 while i <= 5: i += 1 if i == 2: continue print(i) if i == 4: break # else i = 0 while i <= 5: i += 1 print(i) else: print('Is more than 5') # if you break before else you'll never get there i = 0 while i <= 5: i += 1 if i == 2: continue print(i) if i == 4: break else: print('Is more than 5') """ This is a Docstring, it's ignored, but used for help commands For loops in the traditional form are not encouraged for(i=0; i<5; i++) Instead, Python insists on iterating over items using the for loop """ array = ['h', 'o', 'l', 'b', 'i', 'e'] for element in array: print(element) # run on a string string = "holbie" for char in string: print(char) # range # range generates sequences # range(7) generates 0..6 # range(1, 9) generates 1..8 # range(1, 8, 2) generates 1,3,5,7 for ele in range(3): print(ele) # loop on index of array # len returns len of structure (refer to line 43) for index in range(0, len(array)): print(array[index]) # iterate on dictionaries dict = {'name': 'Pepito perez'} for key, value in dict.items(): print(key + ' is ' + value) # enumerate is used to return a tuple with indexes for index, value in enumerate(array): print(value + ' is in ' + str(index))
true
575617625d8ba29a27eebc80b953330d8e20fb9f
famd92/python
/FizzBuzz.py
565
4.3125
4
###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" #### def fizzbuzz(number): if (number%3 ==0 and number%5 ==0): output = 'Fizz Buzz' elif (number%3 ==0): output = 'Fizz' elif (number%5 ==0): output ='Buzz' else: output = number return output if __name__ == '__main__': for i in range(1,101): print(fizzbuzz(i))
true
b4ed82079b3ad9ae8e9e2628c7570668215044b3
hamdi3/Python-Practice
/Formatting.py
783
4.53125
5
#Formatting in python str="string" print("this will type a %s" %(str)) # in %() whatever you write will be changed to a string print("this will type a %s , %s" %("hello" ,3)) # you can use %s 2 times and more but you use one %() with a comma for diffrient ones print("this will type a float %1.2f" %(13.4454)) # %1.2f means that the float would have min 1 num before the comma and max 2 after #Recommended Methods: print("this will print {p}".format (p = "something")) #by typing {p} then ending the string with a .format(P=) you can put anything as a value of p in it print("string1 : {p} , string2: {p}, string 3:{p}" .format(p="hi")) #you can p several times print("object1: {a}, object2:{b}, object3:{c}" .format(a="string", b= 4 , c = 2.3)) #you can use more than one variable
true
1ecebff7cf8703717fc8bc5d19a795161869c53a
iamSurjya/dailycoding
/Day 12_numpy_advance_indexing.py
421
4.1875
4
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) print('Array') print(x) y = x[[0,1,2], [0,1,0]] print('\nFrom each row, a specific element should be selected') #fetching [1 4 5] print(y) print('\nFrom a 4x3 array the corner elements should be selected using advanced indexing') x = np.array( [[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) y=x[[0,0,3,3],[0,2,0,2]] #print(y) print(x[[0,3],[1,2]])
true
f38d4534d6a5fdb6565f9124eefc8e7cf00e04e5
satyamachani/python-experiments
/guess game.py
896
4.21875
4
import random print("you are going to play guess game with computer") print("rules are as follows") print("computer guess and you too") print("if ur guess equals computer guess") print("you wins") print("maximum guess allowed are 3") print("we are strating game......") print("ready to play with satya's computer") num = 3 print(num,"guesses are left") print("Guess the number between 1 to 10") while True: guess = input() computer = random.randint(1,10) print("you guessed",guess) print("computer guessed",computer) print() if 0<int(guess)<11 and (int(guess) == computer): print("hurray! you wins") break elif num == 1: print("No guesses left\n you loose the game") else: print("sorry guess again") num = num-1 print(num,"guesses left") print("guess the number between 1 to 10")
true
503eb1fb3f378307e6ff0d9a9ccbd191e592d9b3
hugolribeiro/Python3_curso_em_video
/World3/exercise081.py
811
4.21875
4
# Exercise 081: Extracting data from a lista # Make a program that reads several numbers and put them into a list. After that, show: # A) How many numbers were inputted # B) The numbers list, in descending order # C) If the value 5 is in the list numbers_list = [] want_continue = 'Y' while want_continue != 'N': number = int(input('Input here a number: ')) numbers_list.append(number) print(f'The number {number} was add into the list') want_continue = input('Do you want to continue?\n' '[N] to stop the program\n').upper() print(f'You inputted {len(numbers_list)} numbers') print(f'The list in descending order: {sorted(numbers_list, reverse=True)}') if 5 in numbers_list: print('The number 5 is in the list') else: print('The number 5 ins\'t in the list')
true
edaa06ad2bdc494c8011777a3aacf69f5ba2764a
hugolribeiro/Python3_curso_em_video
/World3/exercise096.py
467
4.40625
4
# Objective: Make a program that have a function called Area(). # Receive the dimensions of a rectangular land (width and length) and show its area. # Programmer: Hugo Leça Ribeiro def area(width, length): amount_area = width * length print(f'The area of this land is equal than: {amount_area}m²') width = float(input("Input here the width of this land (in meters): ")) length = float(input("Input here the length of this land (in meters): ")) area(width, length)
true
1f25f848fb152d60b5af77405534750d4c83694c
hugolribeiro/Python3_curso_em_video
/World2/exercise060.py
408
4.3125
4
# Exercise 060: Factorial calculation # Make a program that read any number and show its factorial # Example: 5! = 5 X 4 X 3 X 2 X 1 = 120 number = int(input('Input here a number: ')) factorial = 1 print(f'{number}! = ', end='') for multiply in range(number, 0, -1): factorial = multiply * factorial print(f'{multiply}', end='') print(' X ' if multiply > 1 else ' = ', end='') print(factorial)
true
45a18da87d6d6a4b6d6dc201dbce51a6b44dab87
hugolribeiro/Python3_curso_em_video
/World2/exercise071.py
857
4.21875
4
# Exercise 071: ATM simulator # Make a program that simulates the operation of an ATM. # At the begin, ask to the user what value will be withdraw (an integer number) # and the program will informs how many banknotes of each value will be give. # Observation: Consider that the banking box has these banknotes: R$ 50, R$ 20, R$ 10, R$ 5, R$ 2. # The minimum value to withdraw is R$ 5 c50 = 0 c20 =0 c10 = 0 c5 = 0 c2 = 0 value = 0 while value < 5: value = int(input('Input here value to withdraw: ')) while value % 5 != 0: value -= 2 c2 += 1 c50 = value // 50 value -= c50 * 50 c20 = value // 20 value -= c20 * 20 c10 = value // 10 value -= c10 * 10 c5 = value // 5 value -= c5 * 5 print(f'{c50} banknotes of 50\n' f'{c20} banknotes of 20\n' f'{c10} banknotes of 10\n' f'{c5} banknotes of 5\n' f'{c2} banknotes of 2')
true
63f0901cc32517c7090232184e6179db607d1f87
hugolribeiro/Python3_curso_em_video
/World1/exercise013.py
265
4.125
4
# Exercise 013: Income readjustment # Build an algorithm that read the employee's income and show his new income, with 15% increase. income = float(input(f"Input here the employee's income: ")) new_income = income * 1.15 print(f'The new income is: {new_income}')
true
3127270d8291d1794b18cc66b47a0d547ba9b353
hugolribeiro/Python3_curso_em_video
/World2/exercise052.py
572
4.125
4
# Exercise 052: Prime numbers # Make a program that read an integer number and tell if it is or not a prime number. def verify_prime(num): if num < 2 or (num % 2 == 0 and num != 2): return False else: square_root = int(num ** 0.5) for divisor in range(square_root, 2, -1): if num % divisor == 0: return False return True number = int(input('Input here a number: ')) if verify_prime(number): print(f'The number {number} is a prime number') else: print(f'The number {number} isn\'t a prime number')
true
8fb71045715791f1d73d8394de33b5af4400a102
hugolribeiro/Python3_curso_em_video
/World2/exercise043.py
740
4.625
5
# Exercise 043: body mass index (BMI) # Make a program that read the weight and the height of a person. # Calculate his BMI and show your status, according with the table below: # - Up to 18.5 (not include): Under weight # - Between 18.5 and 25: Ideal weight # - Between 25 and 30: Overweight # - Between 30 and 40: Obesity # - Above than 40: Morbid obesity # Formula: BMI = kg / m² weight = float(input('Input here the weight in kg: ')) height = float(input('Input here the height in meter: ')) bmi = weight / (height ** 2) if bmi < 18.5: print('Under weight') elif 18.5 <= bmi < 25: print('Ideal weight') elif 25 <= bmi < 30: print('Overweight') elif 30 <= bmi < 40: print('Obesity') else: print('Morbid obesity')
true
c99de9678d8cc3cd067ab93f3480a5c75f850bee
hugolribeiro/Python3_curso_em_video
/World3/exercise086.py
510
4.4375
4
# Exercise 086: Matrix in Python # Make a program that create a 3x3 matrix and fill it with inputted values. # At the end, show the matrix with the correct format matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for line in range(0, 3): for column in range(0, 3): matrix[line][column] = int(input(f'Input here a number to line {line} and column {column}: ')) for line in range(0, 3): for column in range(0, 3): print(f'[{matrix[line][column]:^5}]', end='') print()
true
5cad30469285efa036089dd993eaa595bb0ecdf4
as3379/Python_programming
/String_manipulation/reverse_alternate_words.py
629
4.3125
4
def reverseWordSentence(Sentence): # Splitting the Sentence into list of words. words = Sentence.split(" ") # Reversing each word and creating # a new list of words # List Comprehension Technique n = len(words) for i in range (0, n): if i%2 !=0: words[i] = words[i][::-1] # Joining the new list of words # to for a new Sentence newSentence = " ".join(words) return newSentence # Driver's Code Sentence = "GeeksforGeeks is good to learn with you" # Calling the reverseWordSentence # Function to get the newSentence print(reverseWordSentence(Sentence))
true
8e37ac3431bffcc74f9c66f16938409ef2277561
as3379/Python_programming
/String_manipulation/middle_char.py
377
4.25
4
"""Print middle character of a string. If middle value has even then print 2 characters Eg: Amazon -->print az """ def middle_char(S): S = S.replace(" ", "") # mid = "" n = len(S) if n%2 ==0: mid = S[n//2 -1]+ S[n//2] else: mid = S[n//2 -1] print(mid) middle_char("Amazon") middle_char("Amazonprime") middle_char("Amazon prime")
true
0d8d1c23ee883c8ecb465b1ea25b9b2bf60bf01f
blueicy/Python-achieve
/00 pylec/01 StartPython/hw_5_2.py
358
4.1875
4
numscore = -1 score = input("Score:") try: numscore = float(score) except : "Input is not a number" if numscore > 1.0 : print("Score is out of range") elif numscore >= 0.9: print("A") elif numscore >= 0.8: print("B") elif numscore >= 0.7: print("C") elif numscore >= 0.6: print("D") elif numscore >= 0.0: print("F") else: print("Not vaild")
true
489259c1f202adff5817dbedde48efeff65f2258
scienceiscool/Permutations
/permutation.py
2,248
4.15625
4
# CS223P - Python Programming # Author Name: Kathy Saad # Project Title: Assignment 6 - Generators and Iterators - Permutations # Project Status: Working # External Resources: # Class notes # https://www.python.org/ class PermutationIterator: def __init__(self, L): self.counter = 0 self.length_for_counter = len(L) - 1 self.true_length = len(L) self.l = L def __iter__(self): return self def __next__(self): for index, element in enumerate(self.l): theRest = self.l[:index] + self.l[index + 1:] print([element] + theRest) print([element] + theRest[::-1]) raise StopIteration() def main(): # NOTE TO SELF: REMOVE TEST LIST CODE BEFORE SUBMITTING numList1 = [1, 2, 3, 4, 5] # keep #numList2 = [1, 2, 3, 4] #numList3 = [1, 2, 3] #numList4 = [1, 2] #numList5 = [1] letterList1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # keep letterList2 = ['b', 'c', 'a'] # keep #letterList3 = ['k', 'y'] #letterList4 = ['x'] print("Permutations of list [1, 2, 3, 4, 5]:") for permutation in PermutationIterator(numList1): print(permutation) #print() #print("Permutations of list [1, 2, 3, 4]:") #for permutation in PermutationIterator(numList2): # print(permutation) #print() #print("Permutations of list [1, 2, 3]:") #for permutation in PermutationIterator(numList3): # print(permutation) #print() #print("Permutations of list [1, 2]:") #for permutation in PermutationIterator(numList4): # print(permutation) #print() #print("Permutations of list [1]:") #for permutation in PermutationIterator(numList5): # print(permutation) print() print("Permutations of list ['a', 'b', 'c', 'd', 'e', 'f', 'g']:") for permutation in PermutationIterator(letterList1): print(permutation) print() print("Permutations of list ['b', 'c', 'a']:") for permutation in PermutationIterator(letterList2): print(permutation) #print() #print("Permutations of list ['k', 'y']:") #for permutation in PermutationIterator(letterList3): # print(permutation) #print() #print("Permutations of list ['x']:") #for permutation in PermutationIterator(letterList4): # print(permutation) if __name__ == "__main__": main()
true
420505fb8d7e2230e8554772d8e60c2efbb83017
kunalprompt/numpy
/numpyArray.py
735
4.4375
4
''' Hello World! http://kunalprompt.github.io Introduction to NumPy Objects ''' print __doc__ from numpy import * lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print "This a Python List of Lists - \n", lst print "Converting this to NumPy Object..." # creating a numpy object (ie. a multidimensional array) num_obj = array(lst) print num_obj print "Type of Numpy Object - "+str(type(num_obj)) print "Number of dimensions or axes this object has are - "+str(num_obj.ndim) print "Data Type of this object - "+str(num_obj.dtype) x=2;y=1 print "Value of element at %d, %d of this numpy object is -"%(x, y), num_obj[x, y] # note under the hood num_obj[x, y] is converted to num_obj.getitem((x,y)) # you can also refernce it as num_obj[(x,y)]
true
49694169a4ab556bcd9072ff168c8dd894008455
ffnbh777/Udacity-Adventure-Game
/udacity_game.py
2,680
4.125
4
import time import random import sys def print_pause(message_to_print): print(message_to_print) time.sleep(2) def intro(): print_pause("You find yourself in a dark dungeon.") print_pause("In front of you are two passageways.") print_pause("Which way do you want to go right or left?") def play_again(): user_input = input("Would you like to play again? (y/n)").lower() if user_input == 'y': print_pause("Excellent! Restarting the game ...") choice() elif user_input == 'n': print_pause("Thanks for playing... Goodbye, until we meet again!") sys.exit() else: play_again() def passageways(): monsters = ["Dragon", "Goliath", "Goblin", "Grendel"] print_pause(f"Standing in the cave is {random.choice(monsters)}") fight_or_run = input("Would you like to (1) fight or (2) run away?") if fight_or_run == '1': print_pause("As the Monster moves to attack it saw your sword.") print_pause( "You hold Sword in your hand ready for the attack.") print_pause("Monster saw your Sword and runs away.") print_pause("You have taken care of the Monster. You WON!") play_again() elif fight_or_run == '2': print_pause("You run back into the dungeon.") choice() else: error_input() def passageways2(): print_pause("You have found the treasure!") print_pause("You walk back out to the dungeon.") monsters = ["Dragon", "Goliath", "Goblin", "Grendel"] print_pause(f"Standing in the cave is {random.choice(monsters)}") print_pause("Monster tries to stop you.") print_pause("You outrun the Monster.") print_pause("You took the Monster's treasure") print_pause("You WON!") play_again() choice() def choice(): intro() print_pause("Enter R to go Right.") print_pause("Enter L to go Left.") user_choice = input("What would you like to do?(R/L)").upper() if user_choice == 'R': passageways() elif user_choice == 'L': passageways2() else: error_input() def error_input(): user_choice = input("(Please enter R or L)\n").upper() while True: if user_choice == 'R': choice() elif user_choice == 'L': choice() else: user_choice = input("(Please enter R or L)\n").upper() def error_answer(): user_input = input("Please enter y or n:").lower() while True: while user_input != 'y' or user_input != 'n': user_input = input("Please enter y or n:").lower() def game(): choice() game()
true
fc25cd3651f146956a075bc5c258b6181adbcee8
judebattista/CS355_Homework
/hw02/reverseComplement.py
1,980
4.4375
4
# function to find the reverse complement of a DNA strand # pattern: A string representation of DNA consisting of the chars 'A', 'C, 'G', and 'T' # complements: a dictionary translating a nucleotide to its complement # revComp: The pattern's complement, complete with 5' to 3' reversal # We may need to store complement in pattern in order to comply with the book's instructions # However, this makes for much less readable code, so we'll stick with complement as our return value for now def revComp(pattern, complements): comp = [] for ntide in pattern[len(pattern) - 1 : : -1]: comp.append(complements[ntide]) revComp = ''.join(comp) return revComp def simpleReverseComp(pattern, complements): revComp = '' for ntide in reversed(pattern): revComp += complements[ntide] return revComp def mapReverseComp(pattern, complements): mapComp = list(map(lambda ntide: complements[ntide], reversed(pattern))) revComp = ''.join(mapComp) return revComp # function to print the pattern, its reversed string, and its reversed complement # pattern: A string representation of DNA consisting of the chars 'A', 'C, 'G', and 'T' # complements: a dictionary translating a nucleotide to its complement def printComplementDetails(pattern, complements): print('Source: ' + pattern) print('Rev source: ' + pattern[len(pattern)-1::-1]) print('Complement: ' + revComp(pattern, complements)) print('Simple Comp: ' + simpleReverseComp(pattern, complements)) print('Map Comp: ' + mapReverseComp(pattern, complements)) complements = {'A':'T', 'C':'G', 'G':'C', 'T':'A'} source = "ACCGGGTTTT" printComplementDetails(source, complements) with open('reverseComplement.txt', 'r') as infile: text = infile.readline().strip() #print(len(text)) revComp = mapReverseComp(text, complements) #print(len(revComp)) with open('reverseComplementResults.txt', 'w') as outfile: outfile.write(revComp)
true
b78d2fe914cdf429651d076b7627d2daad9269f7
Timeverse/stanCode-Projects
/SC101_Assignment5/largest_digit.py
1,176
4.59375
5
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_largest_digit(281)) # 8 print(find_largest_digit(6)) # 6 print(find_largest_digit(-111)) # 1 print(find_largest_digit(-9453)) # 9 def find_largest_digit(n): """ :param n: This is the integer that will be process to find largest digit :return: The integer representing the largest digit in n """ divisor_counter = 0 largest_n = 0 num_y = 10 if n < 0: n = abs(n) else: n = n return helper(n, largest_n, divisor_counter, num_y) def helper(n, largest_n, divisor_counter, num_y): divisor_counter += 1 if num_y == 0: return largest_n else: # Choose num_x = int(n / (1 * (10 ** (divisor_counter - 1))) % 10) num_y = int(n / (1 * (10 ** divisor_counter)) % 10) if num_x > largest_n: largest_n = num_x # Explore return helper(n, largest_n, divisor_counter, num_y) if __name__ == '__main__': main()
true
7efcb0b3f5aa5622e90423c07dd92952fc3f5c07
TryHarder01/SantaBot
/code/draft_bot_chatting.py
2,639
4.15625
4
""" The conversation logic to get the information from users """ username = 'NAME_GOES_HERE' introduction = "Hello {}, before we start let me check if we've done this before...".format(username) new= """Ok let's do this. I'm going to ask you for three things you like and three things you don't like. Once everyone has done that, I'll mix and match everyone in the company. You'll get matched to somoene in another department, and someone who isn't matched to you.""" dept_string = """First thing I need from you is your department. I'll give you a list of departments and I need you to respond in the exact format so I can match it.""" dept_options = ['Analytics' 'Marketing', 'PD', 'Merchants', 'Accounting', 'CS', 'Tech', 'Purchasing', 'Creative', 'Inbound', 'Outbound', 'Dropship', 'Leadership', 'UX'].sort() dept_choice = "User_submits" dept_correct = "Ok, {}, got it. Let's get to the good stuff.".format(dept_choice) dept_wrong = "Not on my list. Here's the departments you can choose from. Where should I put you?" #add all departments likes_intro = """In three separate messages, send me three things you like. For instance, I like: \n interpreted languages\n pelicans\n peeled potatoes.\n What's the first?""" like_1_response = "like1" likes_2_ask = "Your second like?" like_2_response = "like2" likes_3_ask = "Your third like?" like_3_response = "like3" likes_intro = """In three seperate messages, send me three things you do *not* like. For instance, I do *not* like: \n baths\n playing board games\n iambic pentameter.\n What's one thing you don't like?""" dislike_1_response = "dislike1" likes_2_ask = "Your second dislike?" dislike_2_response = "dislike2" likes_3_ask = "Your third dislike?" dislike_3_response = "dislike3" review= """Whew. Ok. I think I have it, but check this over for me first. You work in {dept_choice}. You like {like_1_response}, {like_2_response}, and {like_3_response}. And you do *not* like {dislike_1_response},{dislike_2_response}, and {dislike_3_response}. Is that right (yes / no).""" review_response = "yes" while review_response.lower() != 'yes': if review_response.lower() == 'no': fix = "ok, which part do you want to edit..." ##allow ways to get into the choices else: unknown = "I don't understand. Please enter yes or no." """ use this to handle timeouts http://stackoverflow.com/questions/492519/timeout-on-a-function-call """
true
c8518987eda51e8866d77f42c7913e2f64bb9d37
tarakaramaraogottapu/CSD-Excercise01
/01_prefix_words.py
1,029
4.34375
4
import unittest question_01 = """ Given a query string s and a list of all possible words, return all words that have s as a prefix. Example 1: Input: s = “de” words = [“dog”, “deal”, “deer”] Output: [“deal”, “deer”] Explanation: Only deal and deer begin with de. Example 2: Input: s = “b” words = [“banana”, “binary”, “carrot”, “bit”, “boar”] Output: [“banana”, “binary”, “bit”, “boar”] Explanation: All these words start with b, except for “carrot”. """ # Implement the below function and run the program def prefix_words(prefix, words): pass class TestPrefixWords(unittest.TestCase): def test_1(self): self.assertEqual(prefix_words( 'de', ['dog', 'deal', 'deer']), ['deal', 'deer']) def test_2(self): self.assertEqual(prefix_words( 'b', ['banana', 'binary', 'carrot', 'bit', 'boar']), ['banana', 'binary', 'bit', 'boar']) if __name__ == '__main__': unittest.main(verbosity=2)
true
1dcba14f0fb6b1e4ec92993a0ad8980fb1588bdf
Puneeth1996/programiz.com
/Python Introduction/Additon with single statement.py
639
4.34375
4
""" # This program adds two numbers num1 = 1.5 num2 = 6.3 # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) # Store input numbers num1 = input('Enter first number: ') num2 = input('Enter second number: ') # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) print('The sum is %f' %(float(input('Enter first number: '))+float(input('Enter second number: ')))) """ print('The sum is %.1f' %(float(input('Enter first number: '))+float(input('Enter second number: '))))
true
332aaf6ab6405d2fdeef7ba789b4736437531b8c
mateo42/Project-Euler
/problem005.py
587
4.15625
4
# smallest positive number that is evenly divisible by all of the numbers from 1 to 20 def multiplesOf20(): '''Yield increasing multiples of 20''' i = 20 while True: yield i i += 20 def divisibleByAll( number ): ''' Checks that arguments is divisible by 3 - 19 ''' # Skip 1, 2, 20 for i in range(3,20): if ( (number % i) != 0): return False return True def findSmallestDivisibleTo20(): '''Loop over multiples of 20, find first one divisible by all numbers up to 20''' for i in multiplesOf20(): if divisibleByAll( i ): return i print findSmallestDivisibleTo20()
true
50d9761e41347ae4992d85276f54ba0a00662c08
Jazaltron10/Python
/Time_Till_Deadline/Time_Till_Deadline.py
556
4.28125
4
from datetime import datetime user_input = input("enter your goal with a deadline separated by colon\n") input_list = user_input.split(":") goal = input_list[0] deadline = input_list[1] deadline_date = datetime.strptime(deadline,"%d/%m/%Y") # calculate how many days from now till deadline today_date = datetime.today() due_date = deadline_date - today_date # due_date_in_days = due_date.days due_date_in_hours = int(due_date.total_seconds()/ 60 /60) print() print(f"Dear user! Time remaining for your goal: {goal} is {due_date_in_hours} hours")
true
ddee8e59a44e8f76b83f63ebcc1054c8e6e1d128
EdgarUstian/CSE116-Python
/src/tests/UnitTesting.py
721
4.1875
4
import unittest from lecture import FirstObject class UnitTesting(unittest.TestCase): def test_shipping_cost(self): small_weights = [15.0, 10.0, 20.0, 25.0, 10.0] large_weights = [45.0, 30.1, 30.0, 55.0] def compute_shipping_cost(weight): if weight < 30: return 5.0 else: return 5.0 + (weight - 30.0) * 0.25 for small_weight in small_weights: self.assertTrue(FirstObject.computeShippingCost( small_weight) == compute_shipping_cost( small_weight), small_weight) for large_weight in large_weights: self.assertTrue(FirstObject.computeShippingCost( large_weight) == compute_shipping_cost( large_weight), large_weight) if __name__ == '__main__': unittest.main()
true
0768f554f6d4780360f4cf27f7fdc3f4734a1f4b
rishav-karanjit/Udemy-Python-Basic
/6. Project 1 - Basic Calculator/1. Getting the data.py
465
4.4375
4
# input() -> Takes user input in the form of string a = int(input("Enter a integer:")) #We have changed string to integer because operations like addition cannot be performed in string b = int(input("Enter a integer:")) sign = input("Enter \n + for addition \n - for substraction \n * for multiplication \n / for division\n") #No need to convert sign variable to integer because we don't expect integer in sign print("a =",a) print("b =",b) print("sign =",sign)
true
504e771762dc1227fab5e0d4572629c1e7a5cbcd
MattSokol79/Python_Control_Flow
/loops.py
824
4.375
4
# Loops for loop and while loop # for loop is used to iterate through the data 1 by 1 for example # Syntax for variable name in name_of_data collection_variable shopping_list = ['eggs', 'milk', 'supermalt'] print(shopping_list) for item in shopping_list: if item == 'milk': print(item) sparta_user_details = { 'first_name' : 'Charlie', 'last_name' : 'Shelby', 'dob' : '22/10/1997', 'address' : '74 Privet Drive', 'course' : 'DevOps', 'grades' : ['A*', 'A', 'A'], 'hobbies' : ['running', 'reading', 'hunting'] } # To print keys and values use a for loop for i, j in sparta_user_details.items(): if isinstance(j, list): print(f"Key: {i}") for k in j: print(f"List Value: {k}") else: print(f"Key: {i}, Value: {j}")
true
2365ccf635085dfa2e38e28d80aa7a1811eb0279
Ch-sriram/python-advanced-concepts
/functional-programming/exercise_2.py
405
4.1875
4
# Small exercises on lambda expressions # Square each element in the list using lambda expression my_list = [5, 4, 3] print(list(map(lambda item: item ** 2, my_list))) # Sort the following list on the basis of the 2nd element in the tuple my_list = [(0, 2), (4, 3), (9, 9), (10, -1)] print(sorted(my_list, key=lambda tup: tup[1])) ''' Output: ------ [25, 16, 9] [(10, -1), (0, 2), (4, 3), (9, 9)] '''
true
0dda899681dd50663c3aa5a81c3ef00a1df6f090
Ch-sriram/python-advanced-concepts
/functional-programming/reduce.py
1,061
4.125
4
''' The reduce() function isn't provided by python directly. reduce() function is present inside the functools package, from which we import the reduce() function. In the functools library, we have functional tools that we can use to work with functions and callable objects. ''' from functools import reduce # syntax for reduce: reduce(function, iterable[, init_value_of_the_internal_acc]) # The reduce function has an accumulator that it takes as the # first parameter and the next parameter is the item from the # iterable. The value of accumulator by default is 0. # whatever we return from the function is stored in the # accumulator parameter, and this is the main reason why we # use the reduce() function. def accumulator(acc, item): return acc + item my_list = [1, 2, 3] print(reduce(accumulator, my_list)) # same as -> reduce(accumulator, my_list, 0) print(reduce(accumulator, my_list, 10)) # 16 # reduce() is really powerful and under the hood, map() and # filter() functions actually use the reduce() method ''' Output: ------ 6 '''
true
795e15a99a91d2857fbdfab497ecaccd1789c0e8
ilarysz/python_course_projects
/data_structures/3_stack/linkedstack.py
920
4.28125
4
from linkedlist import LinkedList class LinkedStack: """ This class is a stack wrapper around a LinkedList. """ def __init__(self): self.__linked_list = LinkedList() def push(self, node): """ Add a node to the start of the linked list property. :param node: The Node to add :return: None """ self.__linked_list.add_start_to_list(node) def pop(self): """ Remove a node from the start of the linked list, and return the removed node. :return: Node, the last node of the linked list after being removed. """ return self.__linked_list.remove_start_from_list() def print_details(self): self.__linked_list.print_list() def __len__(self): """ Return the amount of Nodes in the linked list. :return: """ return self.__linked_list.size()
true
60ce10d064bf776b47d4e35da055b4a88d2a88aa
likhi-23/DSA-Algorithms
/Data Structures/linked_queue.py
1,828
4.1875
4
#Linked Queue class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.tail=None def enqueue(self, data): if self.tail is None: self.head =Node(data) self.tail =self.head else: self.tail.next = Node(data) self.tail = self.tail.next def dequeue(self): if self.head is None: print("Queue Underflow") else: print("Element removed from the queue is ", self.head.data) self.head = self.head.next def first(self): return self.head.data def size(self): temp=self.head count=0 while temp is not None: count=count+1 temp=temp.next return count def isEmpty(self): if self.head is None: return True else: return False def printqueue(self): print("Queue elements are:") temp=self.head while temp is not None: print(temp.data,end="->") temp=temp.next if __name__=='__main__': queue = Queue() print("Queue operations") queue.enqueue(24) queue.enqueue(55) queue.enqueue(68) queue.enqueue(47) queue.enqueue(61) queue.enqueue(72) queue.printqueue() print("\nFirst element is ",queue.first()) print("Size of the queue is ",queue.size()) queue.dequeue() queue.dequeue() print("After applying dequeue() two times") print("First element is ",queue.first()) queue.printqueue() print("\nQueue is empty:",queue.isEmpty()) queue.dequeue() queue.dequeue() queue.dequeue() print("After applying dequeue() three times") print("Size of the queue is ",queue.size()) queue.printqueue() queue.dequeue() print("\nQueue is empty:",queue.isEmpty()) queue.dequeue()
true
91c9488189f2895212594e1834cb54f5de713b8e
lpjacob/RPN-Calculator
/operand_queue.py
1,025
4.15625
4
""" Program to perform demonstrate a static queue in Python by ljacob1@canterbury.kent.sch.uk Purpose: to demonstrate queue operation, Limitations: WIP - not currently fully tested """ """global variables""" queue = [] maxSize = 5 #constant to set max queue size tailPointer = 0 def queueSize(): global queue return len(queue) def enqueue(item): """add an item to the tail of the queue if its not full""" global queue, maxSize, tailPointer if tailPointer < maxSize: queue.append(item) tailPointer print("queue containts", queue) else: print("queue full") def dequeue(): global queue, maxSize, headPointer, tailPointer removedItem = None if len(queue)>0: removedItem = queue.pop(0) print("queue containts", queue) else: print("Queue Empty!") return removedItem if __name__ =="__main__": enqueue("+") enqueue("*") print(dequeue()) enqueue("-") print(dequeue()) print(dequeue()) print(dequeue())
true
91bf3c7be3b61637fa8b66c891a5c3d26fb713f8
zhangqunshi/common-utils
/python/file/remove_duplicate_line.py
607
4.1875
4
# coding: utf8 # # Remove the duplicate line of a file # import sys def remove_duplicate_line(filename): exist_lines = list() with open(filename) as f: for line in f.readlines(): line = line.strip() if not line: continue if line not in exist_lines: exist_lines.append(line) print(line) if __name__ == "__main__": if (not sys.argv) or (len(sys.argv) != 2): print("Usage: python %s <file> " % __file__) sys.exit(1) filename = sys.argv[1] remove_duplicate_line(filename)
true
78123433f18d7959d1f7f264e85c4afd964cb878
coala/workshops
/2016_07_03_doctesting_in_python_lasse/sum.py
320
4.3125
4
def sum(*args): """ Sums up all the arguments: >>> sum(1, 2.5, 3) 6.5 If you don’t provide any arguments, it’ll return 0: >>> sum() 0 :param args: Any numbers to sum up. :return: The sum of all the given """ return args[0] + sum(*args[1:]) if len(args) > 0 else 0
true
15b5608a5d690e4fbc40285ea65c94a81195f624
dhruvilthakkar/Dhruv_Algorithm_and_Games
/check_prime.py
267
4.15625
4
#!/usr/bin/env python from __future__ import print_function def check_prime(num): for i in range(2,num): if num % i == 0: print('Number is not prime') break print('Number is prime') num = input('Enter number to check for: ') check_prime(num)
true
29b21b246bd6eadf38f3e71b23d61a5f4590c05f
Alireza-Helali/Design-Patterns
/ProtoType_p2.py
1,500
4.125
4
from copy import deepcopy """ ProtoType: prototype is creational design pattern that lets you copy existing objects without making your code dependant on your classes """ class Address: def __init__(self, street, building, city): self.street = street self.building = building self.city = city def __str__(self): return f'{self.street}, {self.building}, {self.city}' class Employee: def __init__(self, name, address): self.name = name self.address = address def __str__(self): return f'{self.name} works at {self.address}' class EmployeeFactory: main_office_employee = Employee('', Address('sheykh bahayee', 'mapsa', 'tehran')) aux_office_employee = Employee('', Address('sohrevardi', 'mofid', 'tehran')) @staticmethod def __new_employee(proto, name, city): result = deepcopy(proto) result.name = name result.address.city = city return result @staticmethod def new_main_office_employee(name, city): return EmployeeFactory.__new_employee( EmployeeFactory.main_office_employee, name, city) @staticmethod def new_aux_office_employee(name, city): return EmployeeFactory.__new_employee( EmployeeFactory.aux_office_employee, name, city ) p1 = EmployeeFactory.new_main_office_employee('alireza', 'isfahan') p2 = EmployeeFactory.new_main_office_employee('faezeh', 'tabriz') print(p1) print(p2)
true
5acdaf70d6cb94d97a315d255ca6a1db1e027c44
Alireza-Helali/Design-Patterns
/Interface_Segregation_principle.py
2,207
4.3125
4
# Interface Segregation Principle """ The idea of interface segregation principle is that you dont really want to stick too many elements or too many methods in to an interface. """ from abc import ABC, abstractmethod class Machine(ABC): @abstractmethod def printer(self, document): pass @abstractmethod def fax(self, document): pass @abstractmethod def scan(self, document): pass class MultiFunctionPrinter(Machine): def printer(self, document): print(f'print {document}') def fax(self, document): print(f'faxing {document}') def scan(self, document): print(f'scanning {document}') class OldFashionPrinter(Machine): """THe problem with this class is old fashion printer doesn't support fax and scanning and client instantiate this class see's fax and scan and assume that this machine support this features""" def printer(self, document): print('print document') def fax(self, document): pass # old fashion printer don't have this feature def scan(self, document): pass # old fashion printer don't have this feature """ So instead of having one class and all the methods in it we are going to break that class to smaller classes. in this way machines will have the exact feature that they should had. """ class Printer(ABC): @abstractmethod def print(self, document): pass class Fax(ABC): @abstractmethod def fax(self, document): pass class Scanner(ABC): def scan(self, document): pass class MyCopier(Printer): def print(self, document): print(f'print {document}') class PhotoCopier(Printer, Scanner): def print(self, photo): print(f'print {photo}') def scan(self, photo): print(f'print {photo}') class MultiFunctionMachine(Scanner, Fax, ABC): @abstractmethod def fax(self, document): pass @abstractmethod def scan(self, document): pass class MultiFunctionDevice(MultiFunctionMachine): def fax(self, document): print(f'faxing {document}') def scan(self, document): print(f'scanning {document}')
true
e49b2f20b098d8119943430968da3d841376642c
sarwar1227/Stone-Paper-Scissors-E-Game
/stone_paper_scissors E-Game.py
2,659
4.15625
4
'''Stone Paper Scissors E-Game by SARWAR ALI(github.com/sarwar1227) using Python Technologies Required To Run this Code : Pyhton(32/64 bit) version 2/3+ INSTRUCTIONS TO PLAY THIS GAME : 1.Computer Randomly chose between ston/paper/scissors 2.You are asked to chose your option 3.Based on some camparisons Winner of the game is decided GOOD LUCK FOR THE GAME !!''' import random,os,sys name=input("Enter Your Name : ") choices=['stone','paper','scissors'] def display(): print("Hello",name,",Welcome To Stone Paper Scissors Game") comp_choice=random.choice(choices) try: x=int(input("Choices Available\n1.Stone\n2.Paper\n3.Scissors\nEnter Your Choice:")) except ValueError: print("Only integer Value Allowed !!") input() play_again() if (x==1): user_choice='stone' elif (x==2): user_choice='paper' elif (x==3): user_choice='scissors' else: print("Invalid Choice") if (comp_choice=='stone' and user_choice=='scissors') or (comp_choice=='paper' and user_choice=='stone') or (comp_choice=='scissors' and user_choice=='paper'): print("Computer Choice:",comp_choice,"\n",name,"Choice:",user_choice,"\nBad Luck....Computer Wins !!") if comp_choice=='stone': print("Computer's Stone Crushed Your Scissors !!") elif comp_choice=='paper': print("Computer's Paper Blocked Your Stone") elif comp_choice=='scissors': print("Computer's Scissors Cut Down Your Paper") input() play_again() elif (user_choice=='stone' and comp_choice=='scissors') or (user_choice=='paper' and comp_choice=='stone') or (user_choice=='scissors' and comp_choice=='paper'): print("Computer Choice:",comp_choice,"\n",name,"Choice:",user_choice,"\nCongratulations ",name,"!! You Won the Game !!") if user_choice=='stone': print("Your Stone Crushed Computer's Scissors !!") elif user_choice=='paper': print("Your Paper Blocked Computer's Stone") elif user_choice=='scissors': print("Your Scissors Cut Down Computer's Paper") input() play_again() def play_again(): ch=input("Want to play again? (y/Y) for Yes (n/N) for No:") if ch in ['y','Y']: os.system("cls") display() elif ch in ['n','N']: print("Thanks For Playing...The Game!!\nPress Any Key To End...........") input() sys.exit("Thank For Playing !!") elif ch not in ['y','Y','n','N']: print("Invalid Input") play_again() display()
true
d23a81e251ccfb2000f3de8ac0e93db194e08bee
shasha9/30-days-of-code-hackerrank
/Day_04_ClassVSInstance.py
1,345
4.21875
4
#Task # Write a person class with an instance variable age and a constructor that takes an integer initialAge as a parameter. #The constructor must assign initialAge to age after confirming the argument past as initialAge is not negative; #if a negative argument is passed past as initilAge, the constructor should set age 20 to 0 and print "age is not valid setting age to 0" #In addition you must write the following instance methods: #yearPasses() should increase the age instance variable by 1 #amIOld() should perform the following conditional actions: #if age<13 print "you are young" #if age<=13 and age<18 print "you are a teenager" otherwise print "you are old". class Person: age=0 def __init__(self,initialAge): # Add some more code to run some checks on initialAge if initialAge < 0: print ("Age is not valid, setting age to 0.") else: self.age=initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if self.age < 13: print ("You are young.") elif self.age >= 13 and self.age < 18: print ("You are a teenager.") else: print ("You are old.") def yearPasses(self): # Increment the age of the person in here self.age=self.age+ 1
true
7373b562b5e59201e6ffdcdde140e33dba3ce468
thiteixeira/Python
/Sum_Avg_Variance_StdDeviation.py
898
4.21875
4
#!/usr/bin/env python ''' Compute the Sum, Average, Variance, Std Deviation of a list ''' grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def grades_sum(grades): total = 0 for grade in grades: total += grade return total def grades_average(grades): sum_of_grades = grades_sum(grades) average = sum_of_grades / float(len(grades)) return average def grades_variance(scores): variance = 0.0 average = grades_average(scores) for score in scores: variance += (average - score) ** 2.0 return variance / float(len(scores)) def grades_std_deviation(variance): return variance ** 0.5 print(grades) print('Sum of grades: ' + str(grades_sum(grades))) print('Average: ' + str(grades_average(grades))) print('Variance: ' + str(grades_variance(grades))) print('Std: ' + str(grades_std_deviation(grades_variance(grades))))
true
caeb99fe34437b5d5adc1c31cad03bbc30e31e35
ASHOK6266/fita-python
/w3resource/python3/List/exercise.py
1,614
4.34375
4
''' 1. Write a Python program to sum all the items in a list. list_values = [2,4,5,6] index = 0 while index < len(list_values): print(list_values[index]) index += 1 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2. Write a Python program to multiplies all the items in a list. 3. Write a Python program to get the largest number from a list. lis = [2,7,8,89,78,98,87,34] large = max(lis) print(large) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. #HOW TO FIND THE LENGTH sample = ['abc', 'xyz', 'aba', '1221','1','121'] # x[0] = a empty = [] #empty2 =[] #empty2.extend() for x in sample: if len(x) >= 2 and x[0] == x[-1]: empty.append(x) #empty2.extend(list(x)) # The return format will be in the form of list print(len(empty) 7. Write a Python program to remove duplicates from a list sampleList = ['1','ak','ak','1','5'] tup = ('1','2') se = {'1','55','65'} list1 = [] list2 = [] list1.extend(tup) list1.extend(se) # Always should use append list2.append(tup) print(list2) dict3 = {'as': 33, 'ak': 33, 'an': 33} for k,v in dict3.items(): #print(k) print(dict3.values()) '''
true
7b8cbe2a5228cc3153d40bfeaf976cd1f8857f42
PatrickPitts/Brainworms
/lab2/SeasonsAndDays.py
1,526
4.40625
4
# Author : John Patrick Pitts # Date : June 21, 2021 # File : SeasonsAndDays.py # imports essential libraries import sys # gets data input from the user day_num = eval(input("Enter a number between 1 and 7: ")) season = input("Enter a season: ") day = "" month = "" # lists to check against for type of season spring = ["spring", "Spring", "SPRING"] summer = ["summer", "Summer", "SUMMER"] fall = ["fall", "Fall", "FALL"] winter = ["winter", "Winter", "WINTER"] # assigns values to 'day' based on the value of 'day_num' # exits the script early if input is bad if day_num == 1: day = "Monday" elif day_num == 2: day = "Tuesday" elif day_num == 3: day = "Wednesday" elif day_num == 4: day = "Thursday" elif day_num == 5: day = "Friday" elif day_num == 6: day = "Saturday" elif day_num == 7: day = "Sunday" else: sys.exit() # Assigns a value to 'month' based on 'season' and 'day_num' # exits the script if input is bad if season in spring: month = "March" elif season in winter: month = "December" elif season in fall: month = "September" elif season in summer: if day_num <= 3: month = "June" else: month = "July" else: sys.exit() # prints data to user print("The day is {day}, which day number {day_num}.".format(day=day, day_num=day_num)) print("The month is {month} which is in the {season}".format(month=month, season=season)) # prints extra data to user based on 'season' and 'day_num' if season in summer and day_num == 6: print("Go swimming!")
true
fac443035144eb723c6df6a82fa4405079c49b10
Ewa-Gruba/Building_AI
/Scripts/C3E15_Nearest_Neighbor.py
947
4.15625
4
import math import random import numpy as np import io from io import StringIO import numpy as np x_train = np.random.rand(10, 3) # generate 10 random vectors of dimension 3 x_test = np.random.rand(3) # generate one more random vector of the same dimension def dist(a, b): sum = 0 for ai, bi in zip(a, b): sum = sum + (ai - bi)**2 return np.sqrt(sum) def nearest(x_train, x_test): nearest = -1 ite = -1 min_distance = np.Inf # add a loop here that goes through all the vectors in x_train and finds the one that # is nearest to x_test. return the index (between 0, ..., len(x_train)-1) of the nearest # neighbor for train_item in x_train: distance = dist(x_test, train_item) ite = ite + 1 if distance < min_distance: min_distance=distance nearest=ite print(nearest) nearest(x_train, x_test)
true
8044c59728a243d5ba9e974e0a8c62c3dd9cf750
ingehol/RomanNumerals
/main.py
2,205
4.21875
4
# Function for turning integers into roman numerals. # Creating lists with integers and the corresponding roman numerals. integers = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] romans = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] def int_to_roman(val): i = 12 roman_from_number = "" # while-loop that runs as long as value is greater than 0. while val > 0: # for-loop to see if the value can be divided with the current integer value of i. for _ in range(val // integers[i]): # adds the character corresponding to the current integer to the string then subtracts # it from the overall value (the input) roman_from_number += romans[i] val -= integers[i] i -= 1 return roman_from_number # Roman numerals to integers # Dictionary trans = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def roman_to_int(numeral): num_from_roman = 0 # while-loop that runs as long as the length of numeral is more than 0. while len(numeral) > 0: # After that, it checks if length of the input is greater than 1, and if the next character is equal to # 5x or 10x the value of the current one if len(numeral) > 1 and trans[numeral[1]] in (trans[numeral[0]] * 5, trans[numeral[0]] * 10): # if the next character is greater, you want to subtract the one in front of it. add = trans[numeral[1]] - trans[numeral[0]] numeral = numeral[2:] else: # else it adds the value corresponding to the character. add = trans[numeral[0]] numeral = numeral[1:] num_from_roman += add return num_from_roman # Printing out to see that it works. print(int_to_roman(1994)) print(roman_to_int("MCMXCIV")) # Prints out 1-3999 in both roman numerals and the corresponding integers def up_to_3999(): for i in range(1, 4000): # converts value of i to roman numerals roman = int_to_roman(i) # converts the roman numerals back to an integer integer = roman_to_int(roman) # prints the values print(roman, integer) up_to_3999()
true
10cc4bf9eb93419251371f45e589c194f7cdd2f4
SeanIvy/Learning-Python
/ex6 (2).py
2,000
4.25
4
# --------------------------------- # Header # --------------------------------- # LPTHW - Exercise 6 # Sean Ivy - 050912 # Exercise 6 - Strings and Text # --------------------------------- # Start Code # --------------------------------- # Setting up Variables # --------------------------------- x = "There are %d types of people." % 10 # String within a string. x sets up the variable "There are %d types of people." %d calling a decimal string, so Python is looking for the string to be a number. binary = "binary" # variable binary, calling string "binary". This is showing how double quotes makes it a string. do_not = "don't" # Reinforcing the message from line 17. This time in the form of a contraction. y = "Those who know %s and those who %s." % (binary, do_not) # now 2 strings within a string. y sets up the variable "Those who know %s (string call) and those who %s (another string call)." Line 19 shows how to call multiple variables into the same string. # Using the Variables # --------------------------------- print x print y print "I said: %r." % x # Talk to steve about the use of %r here instead of %s. print "I also said: '%s' ." % y # Just a call back to the variable y, with 2 additional strings inserted into this string. # Setting up more Variables # --------------------------------- hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" # I believe %r is used here because the string will call back to a function call (False) instead of a string? # Using more Variables # --------------------------------- print joke_evaluation % hilarious # Printing the variable joke_evaluation, and setting up what string the %r in 'joke_evaluation' is calling. # Last Variable setup and use # --------------------------------- w = "This is the left side of..." e = "a string with a right side." print w + e # Line 47 is what I call a 'knot' as it ties two strings together. # --------------------------------- # End Code # ---------------------------------
true
770edf3dc3dbde450b0c82e276193f413a633732
aidenyan12/LPTHW
/EX36/ex36.py
2,848
4.15625
4
from sys import exit def cave(): print "You're in a cave, a dragon is living inside to safeguard the magic sword" print "You need to take the sword as a weapon to kill the evil king to safe the country" print "You can choose 'sing' to make the dragon fall alseep or 'fight' with the dragon" action = raw_input("> ") if action == 'sing': print "The dragon fell asleep, you stole the sword and leave!" secret_maze() elif action == 'fight': print "The dragon cuts you into pieces, you're fail..." dead() else: print "Please choose 'sing' or 'fight'" def secret_maze(): print "Welcome to the secret maze!" print "You have to go in right direction to walk through the maze then enter the king's castle " print "There's a crossroad in front of you, you will turn 'left', 'right' or 'say WTF' " loop = False while True: action = raw_input("> ") if action == 'left': print "Wow! The dragon woke up and robbed the sword back to the cave, You go back to cave!!!" cave() elif action == 'right': print "OH! NO! You were caught up and killed by the soiders " dead() elif action == 'say WTF': print "Thant's the magic word for oppeing the entrence of the castle, you directly skip the maze!" castle() else: print "Please choose 'left', 'right' and 'say WTF'. " loop = True def castle(): print "Welcome to the castle, the evil king has been waiting you for a loooooog time." print "The king has a gun and he's going to shoot you ..." print "Input 'skip' to escape the bullets or 'grasp' to catch all the bullets. " catch_bullet = False while True: action = raw_input("> ") if action == 'skip': print " That's cool ~" print " You used your sword to take down the head of evil king. Congratulation!" exit(0) elif action == 'grasp' and not catch_bullet: print "Too many bullets, you can't catch them all, you are dead." dead() elif action == 'grasp' and catch_bullet: print "Fantastic ! You just killed the King with your sword. Congratulation!" catch_bullet = True exit(0) else: print "I got no idea what that means." def dead(): count() print "You're dead. Donate $10 to UNICEF to play again." print "'Yes' or 'No' for donation" donation = False while True: action = raw_input ("> ") if action == 'Yes': start() elif action =='No': print "Bye~" exit(0) else: print "I got no idea what that means." donation = True def start(): print "Please pick a name for your character: 'Lucy' or 'Kevin'." action = raw_input("> ") if action == 'Lucy': print "In fact I think Kevin sounds better, Please restart from Kevin XD" start() elif action == 'Kevin': cave() def count(): i = 0 numbers = [] while i < 101: numbers.append(i) i = i + 10 print numbers, " percent of HP has recovered. " start()
true
07265f21311c4a90056ddf0f4c7458cfdae4e880
DokiStar/my-lpthw-lib
/ex11.py
719
4.21875
4
print("How old are you?", end=' ') # input默认返回字符串类型 age = input() print("How tall are you?", end=' ') height = input() print("How much do you weight?", end=' ') weight = input() print(f"So, you're {age} old, {height} tall and {weight} heavy.") # 更多输入 str = input("Input some text here: ") str2 = input("more things here: ") print("The text you input is", str + str2) # 类似代码 name = input("Your name: ") univiersity = input("Your university: ") print("Hello,", name, "\nyour university is", univiersity) # input转换为数字,使用int()强制转换 num1 = int(input("Input a number here: ")) num2 = int(input("Input another number here: ")) print("num1 + num2 =", num1 + num2)
true
7032001cac6b18552bb161bb3c07f55961cc8230
greenfox-zerda-lasers/matheb
/week-03/day-2/36.py
243
4.25
4
numbers = [3, 4, 5, 6, 7] # write a function that reverses a list def rev(numbers): newlist = [] for i in range(len(numbers)-1, -1, -1): print(numbers[i]) newlist.append(numbers[i]) print(newlist) rev(numbers)
true
cf934c557b66a540408af48e1c5ebb3dcc0ea7e1
andyyu/coding-problems
/maximum_product_of_three.py
1,811
4.125
4
# Andy Yu ''' Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. Difficulty: Easy Problem solutions: This problem would be very trivial if not for the possibility of negative integers. We know that besides the obvious choice of (the product of the 3 largest numbers), we must also consider the scenario of (the product of the two smallest (negative) numbers, and the largest positive number). We can simply consider both scenarios in one pass, keeping track of the two most negative numbers and the three most positive numbers. O(n) time O(1) space ''' def maximumProduct(nums): largest = [float('-inf')] # largest 3, populate with default value so it's not an empty list smallest = [float('inf')] # smallest 2 for num in nums: if num > largest[-1]: # maintain last in list as the smallest of the largest 3 if len(largest) == 3: # if already 3 numbers, delete one to make room for the new del largest[-1] largest.append(num) largest.sort(reverse=True) if num < smallest[-1]: # maintain last in list as the larger of the two if len(smallest) == 2: del smallest[-1] smallest.append(num) smallest.sort() return max(reduce(lambda x, y: x * y, largest, 1), largest[0]*smallest[1]*smallest[0]) # pick the greater of the two scenarios # Note: the above reduce + lambda was for fun, largest[2]*largest[1]*largest[0] would work just as well. if __name__ == '__main__': print maximumProduct([5, 2, -10, -6, 3])
true
c47c78d8b585483eac06ee47a9c55b02b22bb741
andyyu/coding-problems
/is_palindrome.py
686
4.21875
4
# Andy Yu ''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. -------------------------------------------------------------------------------- Difficulty: Easy Solution notes: O(n) time O(1) space ''' def isPalindrome(s): return ''.join(c for c in s.lower() if c.isalnum()) == ''.join(c for c in s[::-1].lower() if c.isalnum())
true
99cbb8dac0fe03bad60919a4ebfcf3be8e5e434a
andyyu/coding-problems
/string_permutation.py
315
4.15625
4
# Andy Yu ''' Print all permutations of a string. Difficulty: Easy Solution notes: O(n*n!) time O(1) space ''' def permutate(string, prefix = ''): if (len(string) == 0): print prefix else: for char in string: permutate(string[:string.index(char)] + string[string.index(char)+1:], prefix + char)
true
b648720e20cae1330c7a094599027bcf991b58ed
andyyu/coding-problems
/is_anagram.py
701
4.125
4
# Andy Yu ''' Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case? Difficult: Easy Solution Notes: O(n) time O(1) space ''' def is_anagram(s, t): letter_dict = {} for letter in s: letter_dict[letter] = letter_dict.get(letter, 0) + 1 for letter in t: letter_dict[letter] = letter_dict.get(letter, 0) - 1 for val in letter_dict.values(): if val != 0: return False return True
true
830c75cf9be01d0b3dbdf8ccf275d5f5aab9a000
andyyu/coding-problems
/invert_binary_tree.py
1,293
4.21875
4
# Andy Yu ''' Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None Difficulty: Easy Solution notes: My first iteration looked something like this - def invert_tree(root): if not root: return None else: temp_left = root.left root.left = invert_tree(root.right) root.right = invert_tree(temp_left) return root After some optimization, we end up with a concise 3 line solution! Note: if we are seeking optimal performance over code brevity, then we should add more "checks". if not root: return None should always be checked for each node. also check things like if not root.left and not root.right: return root if root.right / root.left: root.left/right = invert_tree(root.right) This way our code will only attempt to call invert_tree when possible / needed. This will increase performance (not by much, but if you're really trying to squeeze every bit of speed) O(n) time O(1) space ''' def invert_tree(root): if root: root.left, root.right = invert_tree(root.right), invert_tree(root.left) return root
true
b79af958a03cd31deaf3d794f18fb4eea8f8dafa
andyyu/coding-problems
/last_word_length.py
1,001
4.15625
4
# Andy Yu ''' Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5. Difficulty: Easy Solution notes: Take care to note the case where the string is something like "apple orange ". This should return the length of 'orange' (6), but if you simply split using ' ' as a delimiter and return the length of [-1] of that list, it'll incorrectly return 0. An even shorter solution taking advantage of Python's built in whitespace stripping is def length_of_last_word(s): return len(s.rstrip(' ').split(' ')[-1]) O(n) time O(1) space ''' def length_of_last_word(s): word_list = s.split(' ') no_blanks = [word for word in word_list if word != ''] if len(no_blanks) > 0: return len(no_blanks[-1]) else: return 0
true
9bef8335c8629608d0982148e814acfed3bab9f0
BelfastTechTraining/python
/examples/mymodule.py
865
4.15625
4
def sum_numeric_list(nums): """ Accepts a list of numeric values. Returns the sum of the elements. """ sum = 0 for item in nums: sum += item return sum def prune_dict(dict, keys_to_remove): """ Accepts a dict to priune and a list of keys to remove. Matching keys are deleted and rmainders returned. """ pruned_dict = {} for key in dict.keys(): if key not in keys_to_remove: pruned_dict[key] = dict[key] return pruned_dict if __name__ == '__main__': test_ints = [1, 2, 3, 4, 5] print('The sum of {0} is {1}'.format(test_ints, sum_numeric_list(test_ints))) test_dict = {'Tom': 'The First', 'Dick': 'The Second', 'Harry': 'The Third'} pruned_dict = prune_dict(test_dict, 'Tom') print('Stripping \'Tom\' from {0} gives us {1}'.format(test_dict, pruned_dict))
true
b36f2f7a5bc5cc1dd1bc500bfe4c45d1f34f547f
pdaplyn/adventOfCode2018
/solutions/day1.py
1,326
4.1875
4
""" >>> test = ["+1", "+1", "+1"] >>> calc_frequency(test) [0, 1, 2, 3] >>> test = ["+1", "+1", "-2"] >>> calc_frequency(test) [0, 1, 2, 0] >>> test = ["-1", "-2", "-3"] >>> calc_frequency(test) [0, -1, -3, -6] >>> test = ["+1", "-2", "+3", "+1"] >>> calc_frequency(test) [0, 1, -1, 2, 3] >>> find_first_repeated( test ) 2 """ from advent_util import read_file def calc_frequency(input_changes): changes = [int(x) for x in input_changes] frequency = 0 frequencies = [ ] frequencies.append(frequency) for change in changes: frequency += change frequencies.append(frequency) return frequencies def find_first_repeated(input_changes): changes = [int(x) for x in input_changes] frequency = 0 frequencies = { str(frequency): 1 } while 1: for change in changes: frequency += change if str(frequency) in frequencies: return frequency frequencies[str(frequency)] = 1 input_changes = read_file("../inputs/input1.txt") frequency_results = calc_frequency(input_changes) print("Final frequency is ", frequency_results[-1]) first_repeated = find_first_repeated(input_changes) print("First repeated frequency is ", first_repeated) if __name__ == "__main__": import doctest doctest.testmod()
true
b9ce5e24adecc9b4795c536dc833a0cfd8699d1a
BaggyKimono/pythonfoundationswow
/02 Printpractice.py
956
4.5625
5
""" title: Printpractice author: Ally date: 11/26/18 10:36 AM """ print("hello world") #new line print("hello world\nhell is other people") #end a print statement with a thingy print("newline", end = "-") #tabbed characters print("Testing, testing\t1\t2\t3...") print("Testing, testing\n\t1\n\t\t2\n\t\t\t3...") #Comments ''' This is an example of a multi-line comment in python. If you have a lot to say about how the program runs you can put a block of comments like so! ''' #a function def somefunc(): """ This function does xyz :return: """ #a typical way to describe a detail of a function def greeting(name, year): """ Greet the user with a friendly hello and inform them of the year :param name: a string that stores the users name :param year: an integer that stores the current year :return: the concatenated string """ return "Hello from the other side," + name + "! It is " + str(year)
true
4ba9bb1961d7dfd94f6019cda03c0fa31c0a0a96
ysr20/comp110-fa20-lab02
/draw_polygon.py
601
4.6875
5
""" Module: draw_polygon Program to draw a regular polygon based on user's input. """ import turtle # create a turtle and set the pen color duzzy = turtle.Turtle() duzzy.pencolor("red") # asks user for the length of the pentagon go_forward=int(input("Enter a length for the pentagon: ")) #asks user for number of sides in polygon side_number=int(input("Choose number of sides: ")) #draw polygon for i in range(side_number): duzzy.forward(go_forward) duzzy.left(360/side_number) # keep the turtle window open until we click on it turtle_window = turtle.Screen() turtle_window.exitonclick()
true
0d6fbc8b255a676dbc6b6da8608eee3367615187
Portfolio-Projects42/UsefulResourceRepo2.0
/GIT-USERS/TOM2/WEBEU3-PY1/guessing.py
1,080
4.3125
4
## guessing game where user thinks of a number between 1 and 100 ## and the program tries to guess it ## print the rules of the game print("Think of a number between 1 and 100, and I will guess it.") print("You have to tell me if my guess is less than, greater than or equal to your number.") # set a sentinal value to exit loop correct = False # set the top and bottom bounds top = 100 bottom = 1 ## REPL ## continue looping until a condition is false while not correct: ## have the computer guess the number guess = (top + bottom) // 2 ## print our some prompt print(f"I am guessing it is {guess}") ## take input from user result = input("Less, Greater, or Equal? ").lower() result = result[0] ## evaluate input if result == 'l': top = guess - 1 elif result == 'g': bottom = guess + 1 elif result == 'e': correct = True else: print("Please enter either less, greater or equal") if top == bottom: guess = top correct = True ## print result print(f'\nIt is {guess}!\n')
true
da2734b97e7b3b1449ed1688e1406e4c62e2e726
Portfolio-Projects42/UsefulResourceRepo2.0
/GIT-USERS/TOM2/WEBEU3-PY1/day1.py
1,819
4.15625
4
# This is a comment # lets print a string print("Hello, World!") # variables name = "Tom" age = 40 print("Hello, " + name) # f strings name = "Bob" print(f"Hello, {name}") # collections # create an empty list? lst1 = [] # lst1 = list() # create a list with numbers 1, 2, 3, 4, 5 lst2 = [1, 2, 3, 4, 5] # add an element 24 to lst1 lst1.append(24) # print all values in lst2 for n in lst2: print(n) for (i, n) in enumerate(lst2): print(f"Element {i} is {n}") # while loop i = 0 while i < len(lst2): print(lst2[i]) i += 1 # List Comprehensions # Create a new list containing the squares of all values in 'numbers' numbers = [1, 2, 3, 4, 5] print(numbers) squares = [n**2 for n in numbers] print(squares) squares = [num * num for num in numbers] squares = [1, 4, 9, 16, 25] print(squares) squares = [] for num in numbers: squares.append( num * num ) print(squares) # Filtering with a list comprehension # create a new list of even numbers using the values of the numbers list as inputs numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [n for n in numbers if n % 2 == 0] print(evens) evens = [] for n in numbers: if n % 2 == 0: evens.append(n) print(evens) # create a new list containing only the names that start with 's' make sure they are capitalized (regardless of their original case) names = ['Patrick', 'Melquisedeque', 'Bob', 'steve', 'Sam', 'frank', 'shawn'] s_names = [name.capitalize() for name in names if name[0].lower() == 's'] print(s_names) # Dictionaries # Create a new dictionary d1 = dict() d1 = {} d2 = { 'name': 'Tom', 'age': 40 } # access an element via its key print(d2['name']) # iterate over dict for key in d2: print(f'{key} is {d2[key]}') for (k, v) in d2.items(): print(k) print(v)
true
665e20a76c940043340a84f48abec890420458e0
App-Dev-League/intro-python-course-jul-2020
/Session7/NestedLoops/main.py
279
4.1875
4
#Nested Loops for i in range(5): for j in range(5): print(f"The value of i is {i} and the value of j is {j}") #Nested lists and loops table = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(table) for row in table: print(row) for col in row: print(col)
true
30238131f2827d86fe4f530b1c7b39600c2dbdc4
App-Dev-League/intro-python-course-jul-2020
/Session2/DataTypes/strings.py
473
4.1875
4
#Strings name = "Krish" print(name) print(type(name)) #Indexing and Slicing print(name[0]) print(name[4]) print(name[2:4]) #get characters from 2 to 4 (not included) print(name[-1]) #gets last index print(name[-2]) #gets second to last index print(name[:]) #gets whole string #Length print(len(name)) #Common String methods print(name.index("K")) print(name.replace("Krish", "Bob")) #these give copies and does not modify name print(name.lower()) print(name.upper())
true
7aa74118c759dff5f3ac767deaf623dfcae7b411
Yesidh/holbertonschool-web_back_end
/0x00-python_variable_annotations/5-sum_list.py
516
4.28125
4
#!/usr/bin/env python3 """ =============================================================================== a type-annotated function sum_list which takes a list input_list of floats as argument and returns their sum as a float. =============================================================================== """ from typing import List def sum_list(input_list: List[float]) -> float: """ :param input_list: list with float elements :return: the sum of its elements """ return sum(input_list)
true
d0c5db82d901898df3259ef51bcfc03de773eeee
PatrickJCorbett/MSDS-Bootcamp-Module-5
/module5_python.py
2,777
4.34375
4
#first just a test, print "hello world" print("hello world") ##Exercise 1: print the time #import the datetime function from the datetime package from datetime import datetime #put the current time into a variable now = datetime.now() #print the current time print(now) ##Exercise 2: simple stopwatch #Create the stopwatch as a function #import the time package, needed to perform a time delay import time def Stopwatch(seconds): #Set the Start_Time before waiting Start = datetime.now() #wait the number of seconds defined by the seconds argument time.sleep(seconds) End = datetime.now() return(Start, End) #Run Stopwatch for 10 seconds and store the output in End_Time Start_Time, End_Time = Stopwatch(10) print(Start_Time) print(End_Time) #Calculate the time elapsed in the stopwatch. Should be equal to the seconds argument used, plus a couple milliseconds Elapsed = End_Time - Start_Time print(Elapsed) ##Exercise 3: Print a word provided by the user def printword(): word = input("Enter word: ") print(word) printword() ##Exercise 4: Ask for user input and validate that it is a word #First, will need a dictionary of words to validate against. Can use the nltk library (natural language toolkit) import nltk nltk.download('words') from nltk.corpus import words #'words' is a corpus, use set to convert to a list. Set converts any iterable (which a corpus is) to a sequence english_words = set(words.words()) #define function to ask for user input, check if it is in english_words, and return the outcome def uservalidate(): #ask user for input word = input("Enter input: ") #convert to lowercase to match the english_words format word_lower = word.lower() #if statement: if word_lower is part of the list, say so, otherwise say it isn't if word_lower in english_words: print("{} is an English word!".format(word)) else: print("{} is not an English word...".format(word)) uservalidate() ##Exercise 5: Print list of user inputs #function to ask user for num_inputs number of words and then print them all def userlist(num_inputs): #initialize final list of user inputs as a blank list userinputs = [] #for loop for user to input num_inputs number of inputs for i in range(0, num_inputs): #this range is used because Python is zero-indexed #ask the user to put in word i (I use i + 1 because Python is zero indexed but it sounds better to ask "enter word 1" than "enter word 0") word = input("Enter Word {}:".format(i + 1)) #use the .append method on the userinputs list to add word i userinputs.append(word) for i in range(0, num_inputs): print(userinputs[i]) #Test with three inputs (I used "here" "we" "go") userlist(3)
true
da4610110e6e7e580e52700b9fbe42c6f6fa0a19
Nirvighan/Python-C100-Project-
/ATM.py
1,231
4.125
4
# CREATE THE CLASS class ATM(object): #CREATE __INIT__ FUNCTION #IT IS SAME LIKE CONSTRUCTO IN JAVA def __init__(self,name,age,cardNumber,PIN,TotalAmount): #USE SELF #IT IS SAME LIKE THIS IN JAVA self.name = name self.age = age self.cardNumber = cardNumber self.PIN = PIN self.TotalAmount = TotalAmount #CREATE SOME FUNCTIONS def EnterCardNumber(self): print("ENTER CARD NUMBER") def EnterPIN(self): print("ENTER PIN") def TotalBalance(self): print("RS. 500000") def Withdraw(self): print("AMOUNT WITHDRAW SUCCESSFUL") def Add(self): print("AMOUNT ADDED SUCESSFULLY") #CREATE SOME OBJECTS AND CALL THE CLASS FUNCTIONS #SHOW THE FUNCTIONS USING PRINT person1 = ATM("RAHUL ARORA",34,"1576XXXXXX98","2*****9","$80,000") print(person1.EnterCardNumber()) print(person1.EnterPIN()) print(person1.TotalBalance()) print(person1.Withdraw()) print(person1.Add()) person2 = ATM("GEORGE SUTHERLAND",22,"2400XXXXXX89","6********2","$44,000") print(person2.EnterCardNumber()) print(person2.EnterPIN()) print(person2.TotalBalance()) print(person2.Withdraw()) print(person2.Add())
true
057ed18abae64e416e94891e2c1bdb530ff20db9
jigsaw2212/Understanding-Regular-Expressions
/RedEx_findall.py
971
4.6875
5
#findall() function for regular expressions finds all the matches of the desrired pattern in a string, and returns them as a list of strings #findall automatically does the iteration import re #Suppose we have a list with many email addresses str = 'purple alice-b@google.com, blah monkey bob@abc.com blah dishwasher' emails=[] emails = re.findall(r'[\w.-]+@[\w.-]+', str) print emails #How about :- emails = re.findall(r'([\w.-]+)@([\w.-]+)',str) #Will return tuples for name in emails: print name[0] #to access the part one of each tuple print name[1] #t0 access part 2 of each tuple #Will give an output like:- #('alice-b', 'google.com') #('bob', 'abc.com') #---------------------------------------------------------------- #Just something I discovered while fooling around in Python, probably the easiest way of pattern searching. Yet to explore this fully. if 'c' in 'abcdecf': print 'hello' #WORKS! Python, you are magic! *_*
true
893b3c73e03bb2d07fd0d2b6fa1da8cf1b8dd6ef
vanigupta20024/Programming-Challenges
/CaesarCipher.py
1,468
4.40625
4
''' Caesar cipher: Encryption technique also called the shift cipher. Each letter is shifted with respect to a key value entered. ''' print("Enter 0 for encryption and 1 for decryption:") n = int(input()) enc_text = "" print("Enter the input string: ", end = "") text = input() print("Enter key: ", end = "") key = int(input()) if n == 0: # encryption process for index in range(len(text)): # checking if element is an alphabet if text[index].isalpha(): if text[index].isupper(): temp = (ord(text[index]) - ord('A') + key) % 26 + ord('A') enc_text += chr(temp) elif text[index].islower(): temp = (ord(text[index]) - ord('a') + key) % 26 + ord('a') enc_text += chr(temp) else: # if not alphabet, simply append without changes enc_text += text[index] print("Old text: {0}\nEncrypted text: {1}".format(text, enc_text)) if n == 1: # decryption process for index in range(len(text)): # checking if element is an alphabet if text[index].isalpha(): if text[index].isupper(): temp = (ord(text[index]) - ord('A') - key) if temp < 0: temp += 26 temp += ord('A') enc_text += chr(temp) elif text[index].islower(): temp = (ord(text[index]) - ord('a') - key) if temp < 0: temp += 26 temp += ord('a') enc_text += chr(temp) else: # if not alphabet, simply append without changes enc_text += text[index] print("Old text: {0}\nDecrypted text: {1}".format(text, enc_text))
true
05bed03f2a6c548af9c820ec4872c7ec36c168e8
vanigupta20024/Programming-Challenges
/FindHighestAltitude.py
684
4.125
4
''' There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def largestAltitude(self, gain: List[int]) -> int: for i in range(1, len(gain)): gain[i] += gain[i - 1] if max(gain) < 0: return 0 return max(gain)
true
de4d4235835ca1b871af439494367b2119c909d9
vanigupta20024/Programming-Challenges
/ReshapeTheMatrix.py
1,279
4.34375
4
''' You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] ''' class Solution: def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: num_of_rows = len(nums) num_of_columns = len(nums[0]) if num_of_rows * num_of_columns != r * c: return nums matrix = [] row = col = 0 for row_index in range(r): temp = [] for col_index in range(c): if col >= num_of_columns: col = 0 row += 1 num = nums[row][col] col += 1 temp.append(num) matrix.append(temp) return matrix
true
a64ffa6636d8f087557f9acb8ebe9c08c98226d6
vanigupta20024/Programming-Challenges
/RevVowelsOfString.py
625
4.15625
4
''' Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. Example 1: Input: s = "hello" Output: "holle" ''' class Solution: def reverseVowels(self, s: str) -> str: vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] s = list(s) l, h = 0, len(s) - 1 while l < h: if s[l] not in vowels: l += 1 elif s[h] not in vowels: h -= 1 else: s[l], s[h] = s[h], s[l] l += 1 h -= 1 return "".join(s)
true
fa1a26561714f20ce09c29bc00ab14fb1e2837a9
SelimOzel/ProjectEuler
/Problem003.py
629
4.21875
4
def FindLargestPrime(Number): primeList = [] currentPrime = 2 primeList.append(currentPrime) currentPrime = 3 primeList.append(currentPrime) while(currentPrime < Number/2): isPrime = True # Only check odd numbers currentPrime += 2 for prime in primeList: # Current prime is not prime if(currentPrime % prime == 0): isPrime = False break # Current prime is prime if(isPrime): primeList.append(currentPrime) if(Number % currentPrime == 0): print("Prime Factor: ", currentPrime) def main(): print("Solve Problem") FindLargestPrime(600851475143) if __name__ == "__main__": main()
true
9dbecf5b08709386a86862878123c2c174d50328
SamuelFolledo/CS1.3-Core-Data-Structures-And-Algorithms
/classwork/class_activity/day8.py
377
4.3125
4
#Day 8: Hash Map # Stack coding challenge # Write a function that will reverse a string using a stack def reverse_string(text): my_stack = [] for letter in text: my_stack.append(letter) reversed_string = "" while len(my_stack) != 0: reversed_string += my_stack.pop(-1) #pop last return reversed_string print(reverse_string("abc"))
true
2a9fc322901e7bb2a32d5a8a75b53cd813f3c00b
FluffyFu/UCSD_Algorithms_Course_1
/week4_divide_and_conquer/3_improving_quicksort/sorting.py
2,005
4.21875
4
# Uses python3 import sys import random def partition3(a, l, r): """ Partition the given array into three parts with respect to the first element. i.e. x < pivot, x == pivot and x > pivot Args: a (list) l (int): the left index of the array. r (int): the right index of the array. Returns: lt(int), gt(int), s.t. a[0, lt-1] < pivot, a[lt, gt] == pivot and a[gt+1, :] > pivot We don't need to worry about lt-1 and gt+1 are out of bound, because they'll be taken care of by the recursion base case. """ x = a[l] lt = l gt = r i = l + 1 while i <= gt: if a[i] < x: lt += 1 a[lt], a[i] = a[i], a[lt] i += 1 elif a[i] == x: i += 1 elif a[i] > x: # i should not be incremented here, because the switch moves # unseen element to i. a[gt], a[i] = a[i], a[gt] gt -= 1 a[l], a[lt] = a[lt], a[l] return lt, gt def partition2(a, l, r): x = a[l] j = l for i in range(l + 1, r + 1): if a[i] <= x: j += 1 a[i], a[j] = a[j], a[i] a[l], a[j] = a[j], a[l] return j def randomized_quick_sort_2(a, l, r): """ Use two partitions to perform quick sort. """ if l >= r: return k = random.randint(l, r) a[l], a[k] = a[k], a[l] m = partition2(a, l, r) randomized_quick_sort(a, l, m - 1) randomized_quick_sort(a, m + 1, r) def randomized_quick_sort(a, l, r): """ Use three partitions to perform quick sort. """ if l >= r: return k = random.randint(l, r) a[l], a[k] = a[k], a[l] lt, gt = partition3(a, l, r) randomized_quick_sort(a, l, lt-1) randomized_quick_sort(a, gt+1, r) if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) randomized_quick_sort(a, 0, n - 1) for x in a: print(x, end=' ')
true
c219e62a3d037e0a82ee047c929ca271dd575082
FluffyFu/UCSD_Algorithms_Course_1
/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py
1,061
4.1875
4
# Uses python3 import sys def get_optimal_value(capacity, weights, values): """ Find the optimal value that can be stored in the knapsack. Args: capacity (int): the capacity of the knapsack. weights (list): a list of item weights. values (list): a list of item values. The order matches weight input. Returns: float, optimal value. """ v_per_w = [(value / weight, index) for index, (value, weight) in enumerate(zip(values, weights))] sorted_v_per_w = sorted(v_per_w, key=lambda x: x[0])[::-1] v = 0 for avg_v, index in sorted_v_per_w: if capacity <= 0: break w = min(capacity, weights[index]) capacity -= w v += avg_v * w return round(v, 4) if __name__ == "__main__": data = list(map(int, sys.stdin.read().split())) n, capacity = data[0:2] values = data[2:(2 * n + 2):2] weights = data[3:(2 * n + 2):2] opt_value = get_optimal_value(capacity, weights, values) print("{:.10f}".format(opt_value))
true