blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9c83a43e174e983e35825bdee4867d21e9b657e0
daianasousa/Ensinando-com-as-Tartarugas
/Desenhando_estrelas.py
468
4.1875
4
from turtle import * #uma função para desenhar uma estrela #'def' signica 'define' def drawStar(): pendown() begin_fill() for side in range(5): left(144) forward(50) end_fill() penup() #isso vai desenhar uma estrela cinza clara em um fundo azul escuro color("WhiteSmoke") bgcolor("MidnightBlue") #use a função para desenhar estrelas! drawStar() forward(100) drawStar() left(120) forward(150) drawStar() hideturtle() done()
false
1b34b710d70edbb88e6c677e35ac5fff7c795232
lkr92/Learning-Projects
/Simple Calculator.py
722
4.34375
4
run = True #Simple Calculator that will run on loop upon user request while run: num1 = float(input("Please type a number: ")) operator = input("Please input an operator character: ") num2 = float(input("Please input a second number: ")) if operator == "+": print(num1 + num2) elif operator == "-": print(num1 - num2) elif operator == "/": print(num1 / num2) elif operator == "*": print(num1 * num2) else: print("Invalid Operator!!") if input('Type "yes" for a new request or type anything else to close: ') == "yes" or "Yes" or "YES": run = True else: run = False print("End of program.")
true
692f27d609c9961bf5feed66b17f29066020467f
yamaton/codeeval
/easy/prime_palindrome.py
1,211
4.125
4
""" prime_palindrome.py Created by Yamato Matsuoka on 2012-07-16. Description ----------- Write a program to determine the biggest prime palindrome under 1000. Input: None Output: Prints the largest palindrome on stdout under 1000. """ import math def integerdigits(n): """Construct list of decimal digits from the integer n.""" x = [] quotient = n while quotient > 0: x.append(quotient % 10) quotient /= 10 x.reverse() return x def fromdigits(x): """Constructs an integer from the list x of decimal digits.""" return reduce(lambda i,j: 10*i + j, x) def is_palindrome(n): """Return True if integer n is palindrome.""" x = integerdigits(n) return n == fromdigits(reversed(x)) def is_prime(n): """Return True if integer n is prime number.""" if n == 2: return True elif n % 2 == 0: return False else: max_p = int(math.sqrt(n)) return all(n % p != 0 for p in range(3, max_p+1, 2)) def find_prime_palindrome(upperbound): for n in reversed(range(upperbound)): if is_palindrome(n) and is_prime(n): return n upperbound = 1000 print find_prime_palindrome(upperbound)
true
886eb287181be88f20433007a08dc93bb7fdd82f
yamaton/codeeval
/hard/grid_walk.py
2,029
4.53125
5
#!/usr/bin/env python # encoding: utf-8 """ grid_walk.py Created by Yamato Matsuoka on 2012-07-19. Description: There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself? Input sample: There is no input for this program. Output sample: Print the number of points the monkey can access. It should be printed as an integer — for example, if the number of points is 10, print "10", not "10.0" or "10.00", etc. """ def digits_sum(n): x = 0 quotient = abs(n) while quotient > 0: x += quotient % 10 quotient /= 10 return x def scan_grid(): ini = (0, 0) queue = [ini] visited = set([ini]) delta = [(0, 1), (1, 0)] while queue: p = queue.pop() for direction in delta: x = p[0] + direction[0] y = p[1] + direction[1] if is_accessible(x, y) and (x, y) not in visited: queue.append((x, y)) visited.add((x, y)) return visited def count(points): edge_num = len([1 for (x, y) in points if x == y or y == 0]) - 1 inner_num = len(points) - edge_num - 1 return 8 * inner_num + 4 * edge_num + 1 def is_accessible(x, y): return (0 <= x and 0 <= y and x >= y and digits_sum(x) + digits_sum(y) <= 19) def count_grid_walk(): return count(scan_grid()) if __name__ == '__main__': print count_grid_walk()
true
aa4b8ced0ff163c86e0ddcd53608609a0253c138
yamaton/codeeval
/moderate/jolly_jumpers.py
1,892
4.1875
4
#!/usr/bin/env python # encoding: utf-8 """ jolly_jumpers.py Created by Yamato Matsuoka on 2012-07-17. Description: Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla A sequence of n > 0 integers is called a jolly jumper if the absolute values of the differences between successive elements take on all possible values 1 through n - 1. eg. 1 4 2 3 is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively. The definition implies that any sequence of a single integer is a jolly jumper. Write a program to determine whether each of a number of sequences is a jolly jumper. Input sample: Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain an integer n < 3000 followed by n integers representing the sequence. The integers are space delimited. 4 1 4 2 3 5 1 4 2 -1 6 Output sample: For each line of input generate a line of output saying 'Jolly' or 'Not jolly'. Jolly Not jolly """ import sys def is_jolly_jumber(seq): n = len(seq) if n == 1: return True else: return range(1,n) == sorted(abs(seq[i+1]-seq[i]) for i in range(n-1)) ## previous version # # def is_jolly_jumber(seq): # x = len(seq) # if x == 1: # return True # elif x < 1: # return False # else: # if set(abs(seq[i+1]-seq[i]) for i in range(x-1)) == set(range(1,x)): # return True # else: # return False def jolly_message(tf): if tf: return "Jolly" else: return "Not jolly" if __name__ == '__main__': with open(sys.argv[1], "r") as f: data = [[int(x) for x in line.rstrip().split()] for line in f if line.rstrip()] data = [series[1:] for series in data] out = (is_jolly_jumber(seq) for seq in data) print "\n".join(jolly_message(x) for x in out)
true
6095a278b6d0625b6c4df3738cdac5805657a1d8
yamaton/codeeval
/moderate/point_in_circle.py2
1,346
4.28125
4
#!/usr/bin/env python # encoding: utf-8 """ point_in_circle.py2 Challenge Description ===================== Having coordinates of the center of a circle, it's radius and coordinates of a point you need to define whether this point is located inside of this circle. ## Input sample Your program should accept as its first argument a path to a filename. Input example is the following ``` Center: (2.12, -3.48); Radius: 17.22; Point: (16.21, -5) Center: (5.05, -11); Radius: 21.2; Point: (-31, -45) Center: (-9.86, 1.95); Radius: 47.28; Point: (6.03, -6.42) ``` All numbers in input are between -100 and 100 ## Output sample Print results in the following way. ``` true false true ``` """ import sys import re pattern = r"Center: +\((-?[.0-9]+), +(-?[.0-9]+)\); +Radius: +(-?[.0-9]+); +Point: +\((-?[.0-9]+), (-?[.0-9]+)\)" regex = re.compile(pattern) def reader(s): result = regex.search(s) (x, y, r, px, py) = map(float, result.groups()) return (x, y, r, px, py) def is_point_in_circle(x, y, r, px, py): dist_squared = (x - px)**2 + (y - py)**2 return "true" if dist_squared < r*r else "false" if __name__ == '__main__': with open(sys.argv[1], "r") as f: data = [reader(s) for s in f] out = [is_point_in_circle(x, y, r, px, py) for (x, y, r, px, py) in data] for x in out: print x
true
bef391ae6989b5acc9db9e65fa702c8db2e7dd5f
yamaton/codeeval
/easy/capitalize_words.py2
710
4.625
5
#!/usr/bin/env python # encoding: utf-8 """ Challenge Description: Write a program which capitalizes words in a sentence. ## Input sample Your program should accept as its first argument a path to a filename. Input example is the following ``` Hello world javaScript language a letter ``` ## Output sample: Print capitalized words in the following way. ``` Hello World JavaScript Language A Letter ``` """ import sys def capitalize_words(words): return [w[0].upper() + w[1:] for w in words] if __name__ == '__main__': with open(sys.argv[1], 'r') as f: data = [s.split() for s in f] out = [capitalize_words(words) for words in data] for line in out: print(" ".join(line))
true
9fe52d300f8ec8941b028519e78f8ac9a4387da2
yamaton/codeeval
/moderate/cycle_detection.py
2,596
4.125
4
#!/usr/bin/env python # encoding: utf-8 """ cycle_detection.py Created by Yamato Matsuoka on 2012-07-16. Description: Given a sequence, write a program to detect cycles within it. Input sample: A file containing a sequence of numbers (space delimited). The file can have multiple such lines. e.g 2 0 6 3 1 6 3 1 6 3 1 Ensure to account for numbers that have more than one digit eg. 12. If there is no sequence, ignore that line. Output sample: Print to stdout the first sequence you find in each line. Ensure that there are no trailing empty spaces on each line you print. e.g. 6 3 1 """ import sys # # def cycle_detection(seq): # """ # Detect cycle in seq using Floyd's algorithm. # http://en.wikipedia.org/wiki/Cycle_detection # # This algorithm works given that sequence is as long as you want. # """ # totoise = 1 # index for totoise # hare = 2 # index for hare # # while seq[totoise] != seq[hare]: # totoise += 1 # hare += 2 # # # Find the position of the first repetition of length mu # mu = 0 # totoise = 0 # while seq[totoise] != seq[hare]: # totoise += 1 # hare += 1 # mu += 1 # # # Find the length lam of the shortest cycle starting from seq[mu] # lam = 1 # hare = totoise + 1 # while seq[totoise] != seq[hare]: # hare += 1 # lam += 1 # # return seq[mu:mu+lam] def detect_cycle(seq): """ Crude algorithm to find a cycle such that - Select the subsequence seq[n:] such that n is the minimum. - Return 1 cycle orbit of the subsequence. """ for n in range(len(seq)): x = seq[n:] period = periodicity_len(x) if period > 0: return x[:period] else: return False def periodicity_len(seq): """ Return length of periodic orbit. seq must NOT contain transient. 0 is returned if seq is aperiodic. """ N = len(seq) head = seq[0] for i in range(1, N/2): try: periodicity = i + seq[i:].index(head) except ValueError: continue if periodicity <= N/2: if all( seq[k+periodicity] == seq[k] for k in range(N-periodicity) ): return periodicity else: return 0 if __name__ == '__main__': with open(sys.argv[1], "r") as f: data = [[int(x) for x in line.rstrip().split()] for line in f if line.rstrip()] out = (detect_cycle(x) for x in data if detect_cycle(x)) print "\n".join(" ".join(str(i) for i in x) for x in out)
true
d4da83831df94855162f5133e602a82621467666
yamaton/codeeval
/moderate/string_rotation.py
835
4.4375
4
#!/usr/bin/env python # encoding: utf-8 """ String Rotation Share on LinkedIn Description: You are given two strings. Determine if the second string is a rotation of the first string. Input sample: Your program should accept as its first argument a path to a filename. Each line in this file contains two comma separated strings. e.g. Hello,lloHe Basefont,tBasefon Output sample: Print out True/False if the second string is a rotation of the first. e.g. True True """ import sys def if_string_rotation(s, t): if not len(s) == len(t): return False rotated = [s[i:] + s[:i] for i in range(len(s))] return t in rotated if __name__ == '__main__': with open(sys.argv[1], 'r') as f: data = [line.rstrip().split(',') for line in f] for (s, t) in data: print if_string_rotation(s, t)
true
8d4ed3c4af0a627a1600f7fea201975bfdbca67e
yamaton/codeeval
/hard/string_list.py
1,689
4.125
4
#!/usr/bin/env python # encoding: utf-8 """ string_list.py Created by Yamato Matsuoka on 2012-07-18. Description: Credits: Challenge contributed by Max Demian. You are given a number N and a string S. Print all of the possible ways to write a string of length N from the characters in string S, comma delimited in alphabetical order. Input sample: The first argument will be the path to the input filename containing the test data. Each line in this file is a separate test case. Each line is in the format: N,S i.e. a positive integer, followed by a string (comma separated) eg. 1,aa 2,ab 3,pop Output sample: Print all of the possible ways to write a string of length N from the characters in string S comma delimited in alphabetical order, with no duplicates. eg. a aa,ab,ba,bb ooo,oop,opo,opp,poo,pop,ppo,ppp """ import sys import itertools def deleteduplicates(iterable): """Return iterator by remove duplicates""" seen = [] for x in iterable: if x not in seen: yield x seen.append(x) def tuples(lis,n): lis = "".join(deleteduplicates(lis)) out = [] for i in range(n): out.append(lis) return sorted("".join(x) for x in itertools.product(*out)) def combinations(s, n): """Find all permutations of substring with length n from stirng s""" return ("".join(x) for x in tuples(s,n)) def read(entry): (N, string) = entry.rstrip().split(",") N = int(N) return (N, string) if __name__ == '__main__': with open(sys.argv[1], "r") as f: data = [read(x) for x in f if x.rstrip()] out = (combinations(string, N) for (N, string) in data) print "\n".join(",".join(x) for x in out)
true
903201ab083f1fed72d932aa7ae7f1eec9cc8e82
folkol/tutorials
/python3/4.6.functions.py
658
4.3125
4
def fib(n): """Print a Fibonacci series of to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b print() fib(100) print(fib.__doc__) def fib_list(n): """Returns a list containing the Fibonacci numbers up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a + b return result print(fib_list(100)) def fib(n): """Fibonacci generator.""" a, b = 0, 1 while a < n: yield a a, b = b, a + b def fib_list(n): """Returns a list containing the Fibonacci numbers up to n.""" return list(fib(n)) print(fib_list(100))
true
615fc99fe5103f7a0f9f76ebd0b42272f7804beb
ye-susan/projectEuler
/problem001.py
603
4.28125
4
''' Problem 1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' sum = 0 for num in range(0, 1000): #if num is divisible by 3 and 5 - add num to sum, else, check that it's divisible by 5 OR 3, or else - ignore it if (num % 5 == 0) and (num % 3 == 0): sum += num else: # if num is div by 5 OR 3, add to sum if (num % 5 == 0) or (num % 3 == 0): sum += num print(sum) #This code ouputted solution in 0.125 seconds
true
221cb87c96becce61f3dad6a7fbde4fff4b070eb
BXGrzesiek/Python_Projects
/scripts/fib.py
934
4.3125
4
# script generating a list with fibonacci sequence elements # the user is asked for the number of elements # to reduce the load of computing power, # the list is displayed after all X elements have been generated from time import sleep def fib(n): try: if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 2)+fib(n - 1) except ValueError: print('Only positive integer!') choice = 'y' while choice == 'y' or choice == 'Y': print('Series of Fibonacci numbers') print('\n'*5) n = int(input('How deep you want to go? : ')) print(type(n)) elements = [] for i in range(n): elements.append(fib(i)) print(elements) choice = input('You want to try again? [Y/n] ') if choice == 'y' or choice == 'Y': print('Clearing the screen') sleep(3) print('\n'*30) else: break
true
721e2ff5de164b072bab578c5696097ea5b75453
NielRoman/BSIT302_activity1
/Enployee.py
1,553
4.3125
4
Employee = [] class employ: def __init__(self, name, department, position, rate): self.name = name self.department = department self.position = position self.rate = rate list = True while list: print(""" ************************************ Choose Your Option: [1] Add New Employee's Name [2] Enter Hourly Rate Of New Employee [3] Show Employee's Information [4] Exit """) list = input ("Enter An Option: ") if list == "1": name = str(input("Enter New Employee's Name: ")) department = str(input("Enter New Employee's Department: ")) position = str(input("Enter New Employee's Position: ")) rate = int(input("Enter New Employee's Rate: ")) Employee.append(name) Employee.append(department) Employee.append(position) Employee.append(rate) print("The given information are saved!") elif list == "2": num1 = int(input("Enter Employee's Number: ")) hour = int(input("Enter Employee's Hours: ")) num2 = rate finResult = hour * num2 print("The employee's salary for {} hours, with a rate of ${} per hour, will be ${}".format(hour, num2, finResult)) print("The given information are saved!") elif list == "3": print ("""************************************ Employee's Number: {} Employee's Name: {} Employee's Department: {} Employee's Position: {} Employee's Hourly Rate: {} Employee's Working Hours: {}""".format(num1, name, department, position, rate, hour)) elif list == "4": print("End Of Your Session.") else: print("The user has entered an invalid syntax.")
true
031f6125cfcc9048ef8ef7826828a3a2fc671d70
spettigrew/cs2-codesignal-mod-quizzes
/problem_solving/postive_sum.py
979
4.25
4
""" Given an array of integers, return the sum of all the positive integers in the array. Examples: csSumOfPositive([1, 2, 3, -4, 5]) -> 1 + 2 + 3 + 5 = 11 csSumOfPositive([-3, -2, -1, 0, 1]) -> 1 csSumOfPositive([-3, -2]) -> 0 Notes: If the input_arr does not contain any positive integers, the default sum should be 0. [execution time limit] 4 seconds (py3) [input] array.integer input_arr [output] integer """ def csSumOfPositive(input_arr): # U - return all postive numbers # set numbers to 0 numbers = 0 # make sure sum does not include negative numbers. nums > 0 return sum(numbers for numbers in input_arr if numbers > 0) # def csSumOfPositive(input_arr): # # create the variable we will return # positive_sum = 0 # # loop over the array, check if each number is positive, if it is, add to positive_sum # for num in input_arr: # if num > 0: # positive_sum += num # ​ # ​ # return positive_sum
true
f10ab0281a1c0cd70ab11f07d79e37e062f1b0d9
spettigrew/cs2-codesignal-mod-quizzes
/computer_memory_basics/raindrops.py
1,586
4.5625
5
""" Given a number, write a function that converts that number into a string that contains "raindrop sounds" corresponding to certain potential factors. A factor is a number that evenly divides into another number, leaving no remainder. The simplest way to test if one number is a factor of another is to use the modulo operator. Here are the rules for csRaindrop. If the input number: has 3 as a factor, add "Pling" to the result. has 5 as a factor, add "Plang" to the result. has 7 as a factor, add "Plong" to the result. does not have any of 3, 5, or 7 as a factor, the result should be the digits of the input number. Examples: csRaindrops(28) -> "Plong" 28 has 7 as a factor, but not 3 or 5. csRaindrops(30) -> "PlingPlang" 30 has both 3 and 5 as factors, but not 7. csRaindrops(34) -> "34" 34 is not factored by 3, 5, or 7. [execution time limit] 4 seconds (py3) [input] integer number [output] string """ def csRaindrops(number): # U - 105 is divisible by 3, 5 and 7. or 28% 7 = 0 is the remainder answer_string = "" # if number is divisible by 3 # add Pling if number % 3 == 0: answer_string += "Pling" # if number is divisible by 5 # add Plang if number % 5 == 0: answer_string += "Plang" # if number is divisible by 7 # add Plong if number % 7 == 0: answer_string += "Plong" # if not divisible by any of those # return the number as a string if answer_string == "": # str converts number to a string answer_string = str(number) return answer_string
true
1bf90ec0db09546d69f3b08820a6f395b60c3716
spettigrew/cs2-codesignal-mod-quizzes
/problem_solving/remove_vowels.py
1,237
4.21875
4
"""Given a string, return a new string with all the vowels removed. Examples: csRemoveTheVowels("Lambda School is awesome!") -> "Lmbd Schl s wsm!" Notes: For this challenge, "y" is not considered a vowel. [execution time limit] 4 seconds (py3) [input] string input_str [output] string """ def csRemoveTheVowels(input_str): # U -remove vowels in the string. # set vowels (upper and lower) to have removed vowels = "AaEeIiOoUu" # iterate through the string get all vowels for vowel in vowels: if vowel in input_str: # if there is a vowel,replace it with empty '' input_str = input_str.replace(vowel, '') # return input_str return input_str # def csRemoveTheVowels(input_str): # # create a set of all vowels to use when we are checking if a character is a vowel # vowel_set = ('a', 'e','i', 'o', 'u') # # we will build a new string that has no vowels # result_str = '' # # loop over each character, and check if its a vowel # # if its a vowel, DO NOT add it to result_str, otherwise, add to result # for i in input_str: # if i.lower() not in vowel_set: # result_str += i # return result_str
true
ca75c458d27e49fd0f540b9869f75b5831b2d956
cs-fullstack-2019-fall/python-basics2f-cw-LilPrice-Code
/index.py
2,293
4.375
4
import random # Problem 1: # # Write some Python code that has three variables called greeting, my_name, and my_age. # Intialize each of the 3 variables with an appropriate value, # then rint out the example below using the 3 variables and two different approaches for formatting Strings. # # Using concatenation and the + and 2) Using an f-string. Sample output: # YOUR_GREETING_VARIABLE YOUR_NAME_VARIABLE!!! I hear that you are YOUR_MY_AGE_VARIABLE today! greeting = ("Heyo") myName = ("Shoshard") myAgge = ("22") print(f'{greeting} {myName}!!! I hear that you are {myAgge} today!') # you did not include a version using concatenation # Problem 2: # # Write some Python code that asks the user for a secret password. # Create a loop that quits with the user's quit word. If the user doesn't enter that word, ask them to guess again. # secr = ("red") # the secret password should be defined by the user not hard coded user = "" while user != secr: user = input("Enter the password\n") # Problem 3: # # Write some Python code using f-strings that prints 0 to 50 three times in a row (vertically). # # 1 1 1 # 2 2 2 # 3 3 3 # 4 4 4 # 5 5 5 # . # . # . num1 = 1 while num1 <= 50: print(f'{num1} {num1} {num1}') num1 += 1 # Problem 4: # # Write some Python code that create a random number and stores it in a variable. # Ask the user to guess the random number. Keep letting the user guess until they get it right, then quit. # ran = random.randint(1,10) user = 0 while user != ran: user = int(input("Guess the random between 1 and 10\n")) # Challenge # # Write some Python code to ask the user to create a number for the computer to guess between 1 - 10000. # Write the code so that the computer guesses random numbers between 1 - 10000 and # will keep guessing until the computer guesses the number correctly. Once the computer guesses the random number, # alert the user with an alert box that displays how many guesses it took to guess the random number. user = int(input("Enter a number between 1 and 10,000\n")) tryies = 0 while user > 0 and user < 10001: ran = random.randint(1,10000) if ran == user: print("It took the computer " + str(tryies) + " tries to guess your number.") break else: tryies +=1
true
90f8097c9451b5b17d5ee2035206eb7e9dbea17a
SaCut/data_collections
/lists&tuples.py
794
4.1875
4
# creating a list # shopping_list = ["bread", "chocolate", "avocados", "milk"] # # 0 1 2 3 # print(shopping_list) # print(type(shopping_list)) # list indexing # print(shopping_list[0]) # # change a value in the list # shopping_list[0] = "orange" # print(shopping_list) # # add a value to a list # shopping_list.append("ice-cream") # print(shopping_list) # # remove an item from a list # shopping_list.remove(shopping_list[0]) # print(shopping_list) # # can we mix data types in a list? yes # open_minded_list = [1, 2, 3, "one", "two", "three"] # tuples essentials = ("paracetamol", "tooth paste", "tea bags") print(essentials) print(type(essentials)) # essentials[0] = "cereal" gives back an error, because tuples don't support variable reassignment print(essentials[0])
true
c99cb40b55ea8c0f8da481e3c76bcc730d882581
lincrampton/pythonHackerRankLeetCode
/swapCase.py
504
4.375
4
'''return a string that has upperCase->lowerCase and lowerCase->upperCase e.g., 'I am Sam I am!" would become "i AM sAM iAM!" def swap_case(s): return_string = "" for i in range(len(s)): if s[i].islower(): return_string += s[i].upper() elif s[i].isupper(): return_string += s[i].lower() else: return_string += s[i] return return_string if __name__ == '__main__': s = input() result = swap_case(s) print(result)
true
54482b0ebb8235fb66db096fc1dbe569061751ae
lincrampton/pythonHackerRankLeetCode
/string2npArray.py
284
4.4375
4
'''You are given a space separated list of numbers. Your task is to print a reversed NumPy array with the element type float.''''' linzStr = " 2 3 4 5" linzLst = list(map(int,linzStr.split())) linzLst = linzLst[::-1] import numpy as np linzNp = np.array(linzLst, float) print(linzNp)
true
4616f70fc68c11cfa89707aadd60446df02fd481
luroto/lpthw
/ex6.py
691
4.4375
4
# Setting a first variable types_of_people = 10 # Creating a string using this variable x = f"There are {types_of_people} types of people." #Setting two more variables binary = "binary" do_not = "don't" # Another string using variables and f option y = f"Those who know {binary} and those who {do_not}." # setting variables print(x) print(y) # printing strings print(f"I said: {x}") print(f"I also said: '{y}'") hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" # using the format option for the first time on this course print(joke_evaluation.format(hilarious)) w = "This is the left side of ..." e = "a string with a right side." # adding two strings print(w + e)
true
607f3a7a2ba239bb519df49d0a40181193290459
Nipun99/COHDCBIS182F-020
/Caeser.py
567
4.5
4
----Code for Encrypting---- plaintext = input('Enter Message :') alphabet="abcdefghijklmnopqrstuvwxyz" key=1 cipher='' for c in plaintext: if c in alphabet: cipher += alphabet [(alphabet.index(c) +key)%(len (alphabet))] print('your encrypted message is :' + cipher) ----Code for Decrypting---- plaintext = input('Enter Message :') alphabet="abcdefghijklmnopqrstuvwxyz" key=1 cipher='' for c in plaintext: if c in alphabet: cipher += alphabet [(alphabet.index(c) -key)%(len (alphabet))] print('your encrypted message is :' + cipher)
false
f27ec99e5fa2e7136bc85e98bc0ff208b21e14b2
MDGSF/PythonPractice
/commonfunction/buildin/any.py
555
4.125
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # any(iterable) # Return True if any element of the iterable is true. If the iterable is empty, return False. def main(): a_list = [] print(any(a_list)) # False b_list = [True, True] print(any(b_list)) # True c_list = [True, True, False] print(any(c_list)) # True d_list = ['a', 'b', 'c', ''] print(any(d_list)) # True e_list = ['a', 'b', 'c'] print(any(e_list)) # True f_list = [''] print(any(f_list)) # False if __name__ == "__main__": main()
true
c98c71fc4004811f052f309a22077b557e24aa85
pranithsrujanroy/cpl-dwm
/test/knn_10p_missing.py
2,648
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 13:29:39 2018 @author: Student Assignment 5 1. Find a suitable value of k for a given dataset " CAR EVALUATION DATASET". Use the obtained K-value for developing KNN Classifier. Report the classification accuracy. """ import csv #for importing csv data file import helper_functions #Read the CSV file into the python environment data_list = [] with open('../test/data.txt', 'rt') as csvfile: read_obj = csv.reader(csvfile, delimiter = ',') for row in read_obj: data_list.append(row) #field_headings = data_list[0] #data_list.remove(data_list[0]) #print("Attribute headings are : ",field_headings) complete_data = data_list #PREPROCESSING DATA AND SHUFFLING clean_data = pre_process_data(data_list) #clean_data = data_list import random clean_data_shuffled = clean_data random.shuffle(clean_data_shuffled) print(clean_data[2]) TOTAL_RECORDS = len(clean_data) TRAINING_SIZE = int(0.05 * TOTAL_RECORDS) TESTING_SIZE = TOTAL_RECORDS - TRAINING_SIZE print("TRAINING SIZE: ",TRAINING_SIZE, " TESTING SIZE : ",TESTING_SIZE) #TESTING AND TRAINING DATA training_data_list = clean_data_shuffled[0:TRAINING_SIZE] testing_data_list = clean_data_shuffled[TRAINING_SIZE:TOTAL_RECORDS] training_data = [] training_data_labels = [] for record in training_data_list: training_data.append(record[0:4]) training_data_labels.append(record[4]) testing_data = [] testing_data_labels = [] for record in testing_data_list: testing_data.append(record[0:4]) testing_data_labels.append(record[4]) #CALCULATING k error_matrix = [] for k in range(1,2): k = 5 #found correct_classified = 0 incorrect_classified = 0 error = 0 for record,label in zip(testing_data,testing_data_labels): nearest_neighbours,labels = k_nearest_neighbours(record,k,training_data,training_data_labels) pred_label = predict(record,nearest_neighbours,labels) if(pred_label == label): correct_classified = correct_classified + 1 #print("S") else: incorrect_classified = incorrect_classified + 1 #print("F") #print(pred_label,label) error = incorrect_classified / (correct_classified + incorrect_classified) error_matrix.append(error) print(k,error) #print("k:",k," Correct:",correct_classified," Incorrect:",incorrect_classified," Error:",error," Accuracy:",1-error) #print(error_matrix) #import matplotlib.pylot as plt #plt.xlabel("k") #plt.ylabel("error") #plt.plot(error_matrix)
true
4efe0803924322c8fce38b16d4ece218a8aa8ad3
peefer66/100doc
/day 22_30/Day 30 Error handling & JSON/Start/main.py
625
4.21875
4
# Error catching try: file = open('my_text_file.txt') a_dict = {'key':'value'} print(a_dict['key']) except FileNotFoundError: file = open('my_text_file.txt','w') file.write('Somthing') except KeyError as error_message: print(f'The key {error_message} does not exist') else: content = file.read() print(content) finally: file.close() print('File was closed') #### Raise your own exception height = float(input('Enter height(m): ')) weight = int(input('Enter weight(kg): ')) if height > 3: raise ValueError('Human height should not be above 3m') bmi = weight/height**2 print(bmi)
true
0e58e2d7390beb447817ff85d0ac87bb0d942a46
surge55/hello-world
/02-MIT6x/2 Core Elements/for.py
1,165
4.375
4
################################################################################ ## Course: MITx 6.001x - Intro to CS and Programming Using Python ## Student: surge55 ## Date: June 16, 2022 ## Exercise: for ## In this problem you'll be given a chance to practice writing some for loops. ################################################################################ # 1. Convert the following code into code that uses a for loop # prints 2 # prints 4 # prints 6 # prints 8 # prints 10 # prints Goodbye! print("EXERCISE 1:") for i in range(2, 12, 2): print(i) print('Goodbye!') # 2. Convert the following code into code that uses a for loop # prints Hello! # prints 10 # prints 8 # prints 6 # prints 4 # prints 2 print("EXERCISE 2:") print('Hello!') for i in range(10, 0, -2): print(i) # 3. Write a for loop that sums the values 1 through `end`, inclusive. `end` is a variable that we define for you. # So, for example, if we define `end` to be 6, your code should print the result (21). Which is 1 + 2 + 3 + 4 + 5 + 6 # DO NOT USE a variable called `sum` print("EXERCISE 3:") end = 6 total = 0 for n in range(end+1): total += n print(total)
true
be422176cf425a3cd2d7206f42891b40fb1e35c6
surge55/hello-world
/01-PY4E/01-why_program/wordfind.py
979
4.28125
4
############################################################### ## File Name: wordfind.py ## File Type: Python File ## Author: surge55 ## Course: Python 4 Everybody ## Chapter: Chapter 1 - Why Would you Learn Programming ## Excercise: n/a ## Description: Code walkthrough from book ## Other References: http://www.py4e.com/code3/words.py ############################################################### # 1.8 - What is a program? name = input('Enter file:') handle = open(name, 'r') counts = dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 bigcount = None bigword = None for word, count in list(counts.items()): if bigcount is None or count > bigcount: bigword = word bigcount = count print(bigword, bigcount) # You will need to get through Chapter 10 to fully understand # the awesome Python techniques that were used to make this program.
true
ef39a27ed5643fcec06397894d54eb3965e38863
clairejrlin/stanCode_projects
/stanCode_Projects/boggle_game_solver/anagram.py
2,828
4.1875
4
""" File: anagram.py Name: Claire Lin ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 19 If you correctly implement this program, you should see the number of anagrams for each word listed below: * arm -> 3 anagrams * contains -> 5 anagrams * stop -> 6 anagrams * tesla -> 10 anagrams * spear -> 12 anagrams """ # Constants FILE = 'dictionary.txt' # This is the filename of an English dictionary EXIT = '-1' # Controls when to stop the loop # Global variables dictionary = [] def main(): print('Welcome to stanCode \"Anagram Generator\" (or -1 to quit)') while True: word = input('Find anagram for: ') word = word.lower() if word == EXIT: break else: find_anagrams(word) def read_dictionary(): global dictionary with open(FILE, 'r') as f: for line in f: word_dict = line.strip() dictionary.append(word_dict) # print(dictionary) def find_anagrams(s): """ :param s: str, the input which will be arranged. :return: str, the total arranged words. """ find_lst, s_lst, result = [], [], [] read_dictionary() for ele in s: s_lst.append(ele) find_anagrams_helper(s, find_lst, result, s_lst) print(str(len(result)) + ' anagram: ' + str(result)) def find_anagrams_helper(s, find_lst, result, s_lst): """ :param s: str, the input which will be arranged. :param find_lst: lst, the arranged alpha-word will be store here temporarily. :param result: lst, the final arranged word store in this list, and will be printed. :param s_lst: lst, for dealing with the repeated alpha-word. :return: lst, the arranged words. """ global dictionary n = '' for word in find_lst: n += word if len(n) == len(s): if n in dictionary and n not in result: # base case print('Found: ' + str(n)) print('Searching...') result.append(n) else: for i in range(len(s)): # Thanks to Willie for helping me debug. if s[i] not in find_lst or s[i] in s_lst: find_lst.append(s[i]) s_lst.remove(s[i]) if has_prefix(n): find_anagrams_helper(s, find_lst, result, s_lst) find_lst.pop() s_lst.append(s[i]) def has_prefix(sub_s): """ :param sub_s: str, the first few words in s. :return: bool, True or False. """ global dictionary for i in dictionary: if i.startswith(sub_s): if sub_s in i: return True return False if __name__ == '__main__': main()
true
0862238765dcbfc1de89586e5e99b8c74db37061
JagadeeshLTTS/Python_assignment_Genesis2021_99004951
/Ass_Qn-14.py
482
4.28125
4
def splitToDigits(number): d=[int(i) for i in number] return d def findLargestNumber(digits_list): digits_list.sort(reverse=True) num=digits_list[0] for i in range(1,len(digits_list)): num=num*10+digits_list[i] return num if __name__ == '__main__': number=input("Enter number: ") digits_list=splitToDigits(number) largest_num=findLargestNumber(digits_list) print("Largest number by shuffling digits in the",number,"is:",largest_num)
false
78dd1d37cdc8033f5f4f1280cd003b5a2fef579a
JagadeeshLTTS/Python_assignment_Genesis2021_99004951
/Ass_Qn-9.py
1,258
4.15625
4
def actualDate(date, month, year): while(month>12 or date>31 or (month==2 and date>29 and year%400==0) or (month==2 and date>28 and year%400!=0)): year=year+(month//12) month=month%12 if(month==1 or month==3 or month==5 or month==7 or month==8 or month==10 or month==12): if(date>31): month=month+(date//31) date=date%31 if (month == 4 or month == 6 or month == 9 or month == 11): if (date > 30): month = month + (date // 30) date = date % 30 if(month==2 and (year%400==0)): if(date>29): month = month + (date // 29) date = date % 29 else: if(date>28): month = month + (date // 28) date = date % 28 date=[date,month,year] return date if __name__ == '__main__': date=int(input("Enter date: ")) month=int(input("Enter month ")) year = int(input("Enter year: ")) correct_date=[] correct_date=actualDate(date,month,year) print("Entered date is:", end=" ") print(date, ":", month, ":", year) print("Actual date is:",end=" ") print(correct_date[0],":",correct_date[1],":",correct_date[2])
true
e2e621a2ab8ac4f35abe8535e4f70d51bddf4c99
murtekbey/python-temel
/1-objeler-ve-veri-yapilari/reference.py
605
4.28125
4
# value types => string, integer, float (Numbers) x = 5 y = 25 x = y y = 10 print(x,y) # x değeri hala 25 olarak kalır. # reference types => list a = ["apple", "banana", "lemon"] # a'ya elemanları ekledik. b = ["apple", "peach", "cherry"] # b'ye elemanları ekledik a = b # a'daki listeyi b'deki liste ile eşitleyerek değiştirdik. b[0] = "grape" # b üzerinden 0. indexdeki elemanın değerini "grape" olarak değiştirdik. print(a,b) # bu sefer b değerindeki elemanların üzerinde bir değişiklik yapmamız # a'nın elemanlarınıda etkiledi ve 'apple' elemanı 'grape' olarak değişti.
false
e5737aa69e81287528899376a67fc6e096c9a08f
DmitriiTitkov/python_practice_learning
/ex2/main.py
673
4.28125
4
def divide_numbers(num1, num2): """This function checks if one number can be divided to other without remnant""" if isinstance(num1, int) and isinstance(num2, int): result = num1 % num2 if result == 0: if num2 != 4: print("Number {} can be divided to number {} without remnant".format(num1, num2)) else: print("Can be divided to 4") else: print("Remnant is: " + str(result)) else: raise Exception("Wrong arguments passed to function") check = int(input("please type first number: ")) num = int(input("please type second number: ")) divide_numbers(check, num)
true
49b3857ebdaac0c5a7c86f4fd92debfcec5f66ff
vibhore-vg/Learning-Python
/advancedExamples/dict_3.py
544
4.25
4
#Python that counts letter frequencies # The first three letters are repeated. letters = "abcabcdefghi" frequencies = {} for c in letters: # If no key exists, get returns the value 0. # ... We then add one to increase the frequency. # ... So we start at 1 and progress to 2 and then 3. frequencies[c] = frequencies.get(c, 0) + 1 for f in frequencies.items(): # Print the tuple pair. print(f) """ Output ('a', 2) ('c', 2) ('b', 2) ('e', 1) ('d', 1) ('g', 1) ('f', 1) ('i', 1) ('h', 1) """
true
827d16eafdd4f252eae58dd02931234d72ec2d52
JarredStanford/Intro-Python-I
/src/14_cal.py
1,249
4.46875
4
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import date if sys.argv[2] is None: print("lol") today = date.today() try: month = int(sys.argv[1]) except: month = today.month try: year = int(sys.argv[2][1:-1]) except: year = today.year if len(sys.argv) > 3: print('Please enter no more than 2 variables: a month and a [year].') else: print(calendar.monthcalendar(year, month))
true
567496a8ee5849b1c0d80312f57067b4342d7050
Roberick313/Workshop
/project_4.py
504
4.21875
4
###### Fibonacci number def fibonacci(number): '''This function will calculate the fibonacci of the\n \rEntery parameter''' b = 0 result = '' c = 1 for _ in range(1,number+1): while b < number: result += str(b) + "," b = b+c if c < number: result += str(c)+ ',' c = b+c if result.endswith(','): result = result.removesuffix(',') return result
true
c6ead19db12ad137036599239bcfd0d2c61fdb2e
oryband/code-playground
/sliding-window/medium-truncate-str-by-k.py
2,173
4.15625
4
#/usr/bin/env python """ Given a string constructed from ascii chars and spaces, and a non-negative integer k, truncate the message to size k or less, while also stripping spaces such that the result must end with a word. also, words must not be truncated in the middle. either include whole words or non at all. examples: 'The quick brown fox jumps over the lazy dog', 39 --> 'The quick brown fox jumps over the lazy' 'Codility We test coders', 14 --> 'Codility We' """ def trunc_str_by_k(msg, k): # print('DEBUG "{}"'.format(msg[:k])) # edge case for truncating everything # or if k surpasses message length if k == 0 or k >= len(msg): return msg[:k].rstrip() # if the last char in truncated message is the last char of its word, # return the string as it is. # # otherwise (the char isn't the last char of its word), # remove the entire word containing this char. i = k-1 if msg[k-1] != ' ' and msg[k] != ' ': # NOTE k < len(message) while i >= 0 and msg[i] != ' ': i -= 1 # strip remaining spaces from the right return msg[:i+1].rstrip() if __name__ == '__main__': print('"{}"'.format(trunc_str_by_k('Codility We test coders', 14))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 38))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 39))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 40))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 41))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 42))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 43))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 44))) print('"{}"'.format(trunc_str_by_k('The quick brown fox jumps over the lazy dog', 45))) print('"{}"'.format(trunc_str_by_k('aaa aaa', 0))) print('"{}"'.format(trunc_str_by_k('a', 1))) print('"{}"'.format(trunc_str_by_k('', 2))) print('"{}"'.format(trunc_str_by_k(' ', 2)))
true
cf77b96341ff986dd35b1c5f3100adbb5752bfe1
iamAdarshh/Data-Structures
/Stack.py
1,317
4.21875
4
#Simple Stack. class EmptyStackError(Exception): pass class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return(len(self.items)) def push(self, item): self.items.append(item) def pop(self): self.items.pop() def peek(self): if self.is_empty(): return EmptyStackError("Stack is Empty.") return self.items[-1] def display(self): print(self.items) if __name__=="__main__": st = Stack() while True: print("Stack Operations : ") print("1. Push\n2. Pop\n3. peek\n4. Traverse\n5. Length\n 6. Exit") choice = int(input("Enter your choice : ")) if choice == 1: data = int(input("Enter element : ")) st.push(data) elif choice == 2: st.pop() elif choice == 3: value = st.peek() print("Peek element : %d"%value) elif choice == 4: st.display() elif choice == 5: value = st.size() print("The size of Stack : %d"%value) else: break print("Thankyou") print("Programmed by Adarsh Choudhary")
false
2c7bb1d9e25306149e166a3d3eb5f35971d35f30
kkundann/Algorithm
/BasicPython.py
677
4.375
4
# developed by van Rossum in 1991 # difference between Python 2 and python 3 # python 2:- print statement is not print_function # python 3: has function and invoked with parantheses # print ("Hello, World.") # # print(type('default string ')) # print(type(b'string with b ')) # # for i in range(0,5): # print(i) #python function decorator # In Python, we can define a function inside another function. # In Python, a function can be passed as parameter to another function (a function can also return another function def abc(str): def xyz(): return "Welcome to " return xyz()+str def site(site_name): return site_name print abc(site("GreeksforGeeks"))
true
a6586ccae2d752536921d497d08d681e72ce182c
H4rliquinn/Intro-Python-I
/src/14_cal.py
1,842
4.53125
5
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import datetime def rules(): print('Include a month to see that calendar\nInclude a month and year for years other than 2020\n') def show_calendar(args): now = datetime.now() if len(args) > 2: if test_month(args[1]) and test_year(args[2]): month = int(args[1]) year = int(args[2]) else: return False elif len(args) == 2: if test_month(args[1]): month = int(args[1]) year = now.year else: return False else: month = now.month year = now.year cal = calendar.TextCalendar(firstweekday=0) print(cal.formatmonth(year, month, w=0, l=0)) return True def test_month(month): if not month.isdigit() or int(month) > 12: return False return True def test_year(year): if not year.isdigit(): return False return True # main program if not show_calendar(sys.argv): rules()
true
d3857af92ea1df200f76ed3b09235129a11660b5
alhung/gameoflife
/src/main.py
2,472
4.4375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Game of Life This program is an implementation of Conway's game of life. The purpose of the game is to calculate the next state/generation of a multidimensional grid given an initial state/generation of the grid This implementation resembles a forecasting/prediction model Assumptions for Implementation: - Dealing with 2D grids - Calculating only its next generation? - No live cell off the edges (does this mean edge cells are blank?) """ import numpy as np #import pickle as pk # get # rows def rows(): numRow = input("Type number of rows (in digits): ") numRow_int = int(numRow) return numRow_int # get # columns def columns(): numCol = input("Type number of columns (in digits): ") numCol_int = int(numCol) return numCol_int # create initial random grid sized by user def random_grid(x,y): randomgrid = np.random.randint(2, size=(x,y)) print ("You elected to create a {} x {} grid".format(x, y)) print (randomgrid) return randomgrid # create random first generation seed file with initial state #def seed(grid,x,y): # filename = "seeding" # with open(filename, "w") as f: # f.write(grid) # np.save(f, grid) # pk.dump(grid,f) # print ("\n2) Grid file was created, please open it and update any desired 0 to 1") # input ("\nPress enter after the Grid File has been updated and saved") # print("\nBelow is your initial state") # with open(filename, "r") as f: # values = f.read() # print(values) # return values # ID Moore location - identify corner, noncorner edge, or central def mooresq(first): # x = 0 # y = 0 # c = np.array(x,y) # for r in first: # for c in first: # setup cartesian # x = np.linspace(-1,1,3) # y = np.linspace(-1,1,3) # xx,yy = np.meshgrid(x,y) # print (xx) # print (yy) # count num datapoints as neighbors available # x = np.array([-1, 0, 1]); # y = np.array([-1, 0, 1]); # coordinates = np.array(x, y) # print (coordinates) # for i in np.nditer(first): # num = first.index(i) def main(): print ("\nWelcome to Conway's Game of Life\n") print ("\nPlease follow below instructions to create your desired initial state\n") print ("Select Random Grid Size:") x = rows() y = columns() first = random_grid(x,y) next = mooresq(first) #if __name__ =='__main__': #main(sys.argv) main()
true
0c957382dea60d860597e4702ecebc35bfab6861
kannan-c1609/Accenture
/38_Upper_and_Lower_case.py
891
4.125
4
""" Single File Programming Question Write a Python program that accepts a string and calculate the number of upper case letters and lower case letters. Input Format: A string in the first line Output Format: Print the original string in the first line. Number of upper case characters in the second line Number of lower case characters in the third line Refer to the sample output for the exact format Sample testcases Input 1: The quick Brown Fox Output 1: The quick Brown Fox Upper case characters : 3 Lower case characters : 13 """ def fun(n): lower = 0 upper = 0 for i in n: if(i.isupper()): upper = upper + 1 if(i.islower()): lower = lower + 1 return upper, lower n = input() a , b = fun(n) print(n) print("Upper case characters : %d"%a) print("Lower case characters : %d"%b)
true
22e44b6fbe19de104ad494f2c2bd15532455acf7
kannan-c1609/Accenture
/13_SumOfDivisors.py
579
4.125
4
""" Sum of Divisors Given an integer ‘n’ (1 <= n <= 109), find the sum of its unique divisors. Input Specification: Input 1: the integer ‘n’ Output Specification: Return the sum of divisors of ‘n’. Example 1: Input 1: 6 Output: 12 Explanation: Divisors of 6 are 1, 2, 3 and 6. Sum od number (i.e 1 + 2 + 3 + 6) is 12 Example 2: Input1: 36 Output: 91 """ def sumOfDivisors(n): sum = 0 for i in range(1, n+1): if(n % i == 0): sum = sum + i return sum n = int(input()) print(sumOfDivisors(n))
true
c4e26bd35da92d65d95db31784699242b0cbefee
kannan-c1609/Accenture
/28_Greeting.py
288
4.125
4
""" Create a program that take a name as input and returns a greeting. Examples Input: Gerald Example Output: Hello Gerald! Examples Input: Tiffany Example Output: Hello Tiffany! """ def Greeting(n): return 'Hello ' + n + '!' n = input() print(Greeting(n))
true
8cd48dd8c97dc1a53ada6678bd4cf3d3c1063325
kannan-c1609/Accenture
/33_Maxima_or_minima.py
1,083
4.15625
4
""" Implement the following function: int MaximaOrMinima(int a, int b, int c); Quadratic equation: A quadratic equation is any equation having the form, ax2 + bx + c, where ‘a’ cannot be zero. The function accepts coefficients of a quadratic equation, ‘a’, ‘b’ and ‘c’ as its argument. Implement the function to find the maximum or minimum value of quadratic equation by substituting integer values x, where – 100 <= x <= 100. Return the values as follows: • if a > 0, return the minimum value of the equation. • if a < 0, return the maximum value of the equation. Assumption: a is not equal to zero. Note: Computer value lies within integer range Example: Input: a: 1 b: 2 c: 1 Output: 0 Explanation: Since, (a > 0) output is the minimum value which is at x = – 1, output = 1 * (– 1)2 + 2 * (– 1) + 1 = 0. Sample Input: a: – 2 b: – 8 c: 10 Sample Output: 18 """ def fun(a, b, c): return (a * (-1*-1)) + (b * -1) + c a = int(input()) b = int(input()) c = int(input()) print(fun(a, b, c))
true
8d8afbe05d6b642fbfcf39aebe148abbb9afc2c7
AmanKishore/CodingChallenges
/Cracking the Coding Interview/Sorting and Searching/GroupAnagrams.py
784
4.34375
4
''' Group Anagrams: Write a method to sort an array of strings so that all of the anagrams are next to each other. ''' def GroupAnagrams(strings): anagrams = {} for i in range(len(strings)): key = "".join(sorted(strings[i].lower())) # get the key by sorting the string if key not in anagrams: # Check if dictionary has the key anagrams[key] = [] # Add the key with a list anagrams[key].append(strings[i]) # Add the string to the list keys = anagrams.keys() index = 0 for i in range(len(keys)): # Build the sorted list values = anagrams.get(keys[i]) for j in range(len(values)): # Looping through every value in the key list strings[index] = values[j] index += 1 return strings
true
32c84bd9254d29fcb27604ae5d501bea536f70ac
AmanKishore/CodingChallenges
/Interview Cake/Recursion and Dynamic Programming/Fibonnaci.py
790
4.375
4
''' Fibonacci: Find the Nth fibonacci number. ''' memo = {0 : 0, 1 : 1} def fib(n): # Compute the nth Fibonacci number if n in memo: return memo[n] else: memo[n] = fib(n-1) + fib(n-2) # Store the newest discovered number return memo[n] def fib_bottom_up(n): if n < 0: raise ValueError('Index was negative. No such thing as a negative index in a series.') elif n in [0, 1]: return n # Bottom Up fibonacci serie prev_prev = 0 # 0th fibonacci prev = 1 # 1st fibonacci for _ in range(n - 1): # Go to two before because you already have first two included current = prev + prev_prev # Use the previous two to calculate the current prev_prev = prev prev = current return current
false
6a1ae5ee59a0f726995e79ef161e79cf4a5c16de
vardhan-duvvuri/Challange
/ch23.py
230
4.125
4
def reverseLookup(dictionary, value): output = [] for key,val in dictionary.iteritems(): if val == value: output.append(key) return sorted(output) if __name__ == "__main__": print reverseLookup({'a':1, 'b':2, 'c':2}, 2)
true
1d6bc423fc32cec33981e5c4a10b61d59959ddf7
jb4503/PHYS4100_JBermeo
/Problem2.py
1,648
4.40625
4
import math import argparse import sys # A spaceship travels from Earth in a straight line at relativistic speed v to another planet x light years away. # Write a program to ask the user for the value of x and the speed v as a fraction of the speed of light c, # then print out the time in years that the spaceship takes to reach its destination (a) in the rest frame of # an observer on Earth and (b) as perceived by a passenger on board the ship. # Use your program to calculate the answers for a planet 10 light years away with v = 0.99c. # Let's ask for velocity first def main(): parser1 = argparse.ArgumentParser(description= "Parses the values for this problem") parser1.add_argument('x', type=float, help="Distance traveled in light years: ") parser1.add_argument('v', type=float, help="Speed of the spaceship as a fraction of the speed of light, c: ") args = parser1.parse_args() v = args.v while v >= 1 or v <= 0: print("That's not a valid value for the velocity!") v = float(input("Enter the velocity as a fraction of the speed of light, c: ")) x = args.x while x <= 0: print("That's not a valid value for the distance!") x = float(input("Enter the distance in light years: ")) # Equation for dilation gamma = 1 / (math.sqrt(1 - v ** 2)) # Distance x_c = x / gamma # Time time_earth = round((x / v), 2) time_spaceship = round((x_c / v), 2) print("The time in Earth's frame is {} years".format(str(time_earth))) print("The time in spaceship's frame is {} years".format(str(time_spaceship))) if __name__ == '__main__': main()
true
cd260a299fd88a32a46742e90355b1a9db4657d5
jb4503/PHYS4100_JBermeo
/PHYS4100_HW1.py
930
4.3125
4
import math import argparse # A ball is dropped from a tower of height h with initial velocity zero. # Write a program that asks the user to enter the height in meters of the tower # and then calculates and prints the time the ball takes until it hits the ground, # ignoring air resistance. Use your program to calculate the time for a ball dropped from a 100 m high tower. # Initial Velocity v_0 = 0; # Ask user for tower height: h = int(input("Enter the tower's height in meters : ")) while h <= 0: print("Height can't be negative!") h = int(input("Enter the tower's height in meters : ")) deltaY= - h # Don't fprget about little g g = 9.8; # acceleration a = -g # Now let's calculate the time it takes to hit the ground # We can use deltaY = V_0*t + 1/2 a t^2 # Since V_0 is 0, deltaY becomes 1/2 a*t^2 t = str(round(math.sqrt( (2*deltaY)/a), 2)) print ('It would take the ball '+t+' seconds to hit the ground')
true
b04dc337d96da4ef5c88ce017fc99f81160721f6
JaySwitzer/InformationTechnology
/calculator.py
414
4.28125
4
num1 = int(input("Enter Number 1: ")) num2 = int(input("Enter Number 2: ")) oper = input ("Enter the operator:") if oper == "*": ans = num1 * num2 print (num1,oper,num2,"=",ans) elif oper == "/": ans = num1 / num2 print (num1,oper,num2,"=",ans) elif oper == "+": ans = num1 + num2 print (num1,oper,num2,"=",ans) elif oper == "-": ans = num1 - num2 print (num1,oper,num2,"=",ans)
false
b416ec27c7e16d158e89b82a96d32a7c190c728e
Duk4/Microsoft-Python-for-beginners
/complex_conditions.py
488
4.1875
4
gpa = float(input('What was your Grade Point Average? ')) lowest_grade = float(input('What was your lowest grade? ')) # if gpa >= 0.85: # if lowest_grade >= 0.70: # print('You made the honour role!') # if gpa >= 0.85 and lowest_grade >= 0.70: # print('You made the honour role!') if gpa >= 0.85 and lowest_grade >= 0.70: honour = True else: honour = False if honour: print('You made the honour role!') else: print('You have not made the honour role!')
false
a2e1faf19f6a4f1bafdeddeb05cd070b95900bd2
Duk4/Microsoft-Python-for-beginners
/nums.py
645
4.21875
4
# pi = 3.14159 # print(pi) # first_number = 6 # second_number = 2 # print(first_number + second_number) # print(first_number ** second_number) # first_number = input('Enter first number: ') # second_number = input('Enter second number: ') # print(first_number + second_number) you get a string # print(first_number ** second_number) strings can't have exponents # print(int(first_number) + int(second_number)) # print(float(first_number) + float(second_number)) days_in_feb = 28 # print('There are ' + days_in_feb + ' days in February') won't work, because (string + int + string) print('There are ' + str(days_in_feb) + ' days in February')
true
5840505b583e8a27ad247cac1e3dc56447c3ed46
jrcolas/Learning-Python
/100DaysBootcamp/Day12/numberGuessing.py
1,450
4.15625
4
from art import logo from random import randint import os EASY_GUESS = 10 HARD_GUESS = 5 randomNumber = randint(1,100) os.system('cls') print(logo) print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100.") difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ").lower() attempts = 0 def guess_game(atpt): '''Takes in the number of attempts left for the user to use''' print(f"You have {atpt} attempts remaining to guess the number.") user_guess = int(input("Take a guess: ")) while user_guess != randomNumber and atpt != 1: if user_guess < randomNumber: atpt -= 1 print("Too low.") print(f"You have {atpt} attempts remaining to guess the number.") user_guess = int(input("Take a guess: ")) else: atpt -= 1 print("Too high.") print(f"You have {atpt} attempts remaining to guess the number.") user_guess = int(input("Take a guess: ")) if user_guess == randomNumber: print("Congratulations! You guessed it right!") if user_guess != randomNumber: print(f"You've used up all of your attempts. The number was {randomNumber}.") if difficulty == "easy": attempts_left = EASY_GUESS - attempts elif difficulty == "hard": attempts_left = HARD_GUESS - attempts else: print("You done messed up!") guess_game(attempts_left)
true
3503bbf670e20960ffb54294ae13695cbbdb3de2
Michaelllllll25/Python-Learn
/Lists.py
2,435
4.34375
4
######################################### 5.1. Creating a list empty_list = [] empty_list #[] another_empty_list = list() another_empty_list #[] odd_nums = [1, 3, 5, 7, 9] odd_nums #[1, 3, 5, 7, 9] my_friends = ["Jim", "Joe", "Sally"] my_friends #['Jim', 'Joe', 'Sally'] vowels = ['a', 'e', 'i', 'o', 'u'] vowels #['a', 'e', 'i', 'o', 'u'] vowels = list("aeiou") vowels #['a', 'e', 'i', 'o', 'u'] letters = list("hello") letters #['h', 'e', 'l', 'l', 'o'] friends = "Jim Sally Joe".split(" ") friends #['Jim', 'Sally', 'Joe'] friends = "Jim, Sally, Joe".split(", ") friends #['Jim', 'Sally', 'Joe'] ######################################### 5.2. Accessing list elements marks = [6, 2, 8, 5, 0, 4, 1] # Initalizing a list marks[0] # Access single element by index #6 marks[3] #5 ######################################### 5.3. Slicing a list marks = [6, 2, 8, 5, 0, 4, 1] marks[3:5] # Slice list from index 3 up to (not including) 5 #[5, 0] marks[:5] # Slice list from beginning up to (not including) 5 #[6, 2, 8, 5, 0] marks[3:] # Slice list from 3 to the end #[5, 0, 4, 1] marks[:-1] # Slice list from beginning to (not including) the last element #[6, 2, 8, 5, 0, 4] marks[:] # Slice from beginning to the end (copy whole list) #[6, 2, 8, 5, 0, 4, 1] marks[::2] # Slice from beginning to the end stepping by 2 #[6, 8, 0, 1] marks[::-1] # Slice from beginning to the end backwards #[1, 4, 0, 5, 8, 2, 6] ######################################### 5.4. Appending elements to a list friends = ['Jim', 'Sally', 'Lucy'] friends.append("ABC") friends #['Jim', 'Sally', 'Lucy', 'ABC'] friends.append("Bob") friends #['Jim', 'Sally', 'Lucy', 'ABC', 'Bob'] ######################################### 5.5. Reassign element at list index friends = ['Jim', 'Sally', 'Lucy', 'ABC', 'Bob'] friends[2] = "Abigail" friends #['Jim', 'Sally', 'Abigail', 'ABC', 'Bob'] ######################################### 5.6. Remove list element using .remove friends = ['Jim', 'Sally', 'Lucy', 'ABC', 'Bob'] friends.remove("Lucy") friends #['Jim', 'Sally', 'ABC', 'Bob'] ######################################### 5.7. Remove list element at index using del friends = ['Jim', 'Sally', 'ABC', 'Bob'] del friends[2] friends #['Jim', 'Sally', 'Bob']
false
2846974b37536874fc1b2fe56ea204171fcd66b1
surajsomani/Basic_Python
/Python Basics/22_Reading_CSV.py
1,244
4.46875
4
import csv #library to handle csv files with open('example.csv') as csvfile: #naming the file as csvfile readCSV = csv.reader(csvfile, delimiter=',') #reading the file for row in readCSV: #reading each row print(row) #print all columns in 1st row print(row[0]) #print 1st column Here also index starts with 0 print(row[0],row[1],row[2],) #print 1st, 2nd and 3rd column with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') dates = [] colors = [] for row in readCSV: color = row[3] date = row[0] dates.append(date) colors.append(color) print(dates) print(colors) with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') dates = [] colors = [] for row in readCSV: color = row[3] date = row[0] dates.append(date) colors.append(color) print(dates) print(colors) # now, remember our lists? whatColor = input('What color do you wish to know the date of?:') coldex = colors.index(whatColor) theDate = dates[coldex] print('The date of',whatColor,'is:',theDate) #if you enter something that doesn't exist, you will get an ugly error.
true
0b798c3c17c0b3302603edc792beb7c7ef9701cb
ferasmis/Repeated-Number-Finder-In-A-List
/RepeatedNumberList.py
241
4.15625
4
## Author: Feras ## Description: A program that finds repeated values in a list def repeated(myList): for i in myList: if myList.count(i) > 1: return i print("The repeated number is: ", repeated([1,2, 45, 67, 45]))
true
ffc6e2fda607020f9c8f320cb42a607e79d7f44b
shawl6201/CTI110
/P3T1_AreasOfRectangles_LeslieShaw.py
748
4.5
4
#CTI-110 #P3T1- Areas of Rectangles #Leslie Shaw #October 6, 2018 #This program is to determine which rectangle has the greater area #Get the length and width of rectangle 1 length1=int(input('Enter the length of rectangle 1:')) width1=int(input('Enter the width of rectangle 1:')) #Get the length and width of rectangle 2 length2=int(input('Enter the length of rectangle 2:')) width2=int(input('Enter the width of rectangle 2:')) #Calculate the areas of the rectangles area1=length1*width1 area2=length2*width2 #Determine which has the greater area if area1>area2: print('Rectangle 1 has the greater area.') elif area2>area1: print('Rectangle 2 has the greater area.') else: print('Both have the same area.')
true
cc909d85ba280a5dc383da83f73abdec347a00aa
77kHlbG/Python
/CeaserCypher.py
1,123
4.21875
4
#!/usr/bin/python -tt import sys # Define a main() function def main(): rotation=1 # Get cyphertext from user cyphertext = input('Enter cyphertext: ') plaintext = cyphertext cyphertext = cyphertext.upper() print('\n') print('Performing Rotation Cypher...') # Repeats for all 25 possible rotations for rotation in range ( 1 , 26 ): # Rotates each character in cyphertext string for i in range( len( cyphertext ) ): # Use to skip non-alphabetic characters if ord( cyphertext[i] ) + rotation >= 91: # Add 6 to skip non-alphabetic characters between Upper and Lower case plaintext = plaintext[:i] + chr( ord( cyphertext[i] ) + rotation + 6 ).upper() # Increment character by rotation value else: plaintext = plaintext[:i] + chr( ord( cyphertext[i] )+ rotation ).upper() # Print plaintext from each rotation print( 'ROT-' + str( rotation ) + ":" , plaintext ) rotation = rotation + 1 # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
true
0f05e0f4891bf5964df0b986d46e195c8571825f
BrianHarringtonUTSC/CMS-URG
/VideoStyleDifferences/Lecture_4/functions.py
1,332
4.34375
4
''' You are building a login system for your new app. In order to protect the users, you require their password to have certain propoerties, they are listed below: 1. Must be at least 8 characters long 2. Must have at least 1 uppercase letter 3. Must have at least 1 lowercase letter 4. Must have at least 1 numeric digit 5. Does NOT contain spaces Write a program that takes in a password as a string, and returns True if the password satisfies all 5 criterias. If it doesn't, return False. If the entered password is "ilovelasagna4", your function should return False, as the password does not contain an uppercase letter. Don't forget to check your code by running a few examples, including the one given above. ''' def validate_password(password): ''' PLEASE WRITE BELOW THIS COMMENT ''' length_FLAG = (length(password) >= 8) uppercase_FLAG = False lowercase_FLAG = False digit_FLAG = False no_space_FLAG = (' ' not in password) for letter in password: if (not uppercase_FLAG): uppercase_FLAG = isupper(letter) if (not lowercase_FLAG): lowercase_FLAG = islower(letter) if (not digit_FLAG): digit_FLAG = isdigit(letter) return (length_FLAG and uppercase_FLAG and lowercase_FLAG and digit_FLAG and no_space_FLAG)
true
a81fc2dd8f67097c6d8b3e4ac6c35e2961665bac
lichader/leetcode-challenge
/problems/median_of_two_sorted_arrays.py
1,832
4.125
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 """ from typing import List """ We actually only need to iterate half elements of m+n because we only need to know the value of elements in the middle """ class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: merged = [] len1 = len(nums1) len2 = len(nums2) total_size = len1 + len2 left = 0 right = 0 import math if total_size % 2 == 0: right = int(total_size / 2) left = right - 1 else: right = math.floor(total_size / 2) left = right p1 = 0 p2 = 0 while len(merged) < (right + 1) : i1 = None i2 = None if p1 < len1: i1 = nums1[p1] if p2 < len2: i2 = nums2[p2] if i1 != None and i2 != None: if i1 < i2: merged.append(i1) p1 += 1 elif i1 > i2: merged.append(i2) p2 += 1 else: merged.append(i1) merged.append(i1) p1 += 1 p2 += 1 elif i1 != None: merged.append(i1) p1 += 1 elif i2 != None: merged.append(i2) p2 += 1 return (merged[left] + merged[right]) / 2
true
4c0e01485636e314bc7356fda4bf0c77e8f71757
SergioO21/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,591
4.3125
4
#!/usr/bin/python3 """ matrix_divided function """ def matrix_divided(matrix, div): """ # Divides all elements of a matrix. Args: matrix (list) = The matrix div (int) = Matrix divisor - ``matrix`` must be a list of lists of integers or floats, otherwise raise a ``TypeError`` exception. - Each ``row of the matrix`` must be of the same size, otherwise raise a ``TypeError`` exception. - ``div`` must be a number (integer or float), otherwise raise a ``TypeError`` exception. - ``div`` can’t be equal to (0), otherwise raise a ``ZeroDivisionError`` exception. - All elements of the ``matrix`` should be divided by ``div``, rounded to 2 decimal places. Return: A new matrix. """ different_size = "Each row of the matrix must have the same size" no_number = "matrix must be a matrix (list of lists) of integers/floats" rows_size = [] new_matrix = [] index_matrix = 0 if type(div) != int and type(div) != float: raise TypeError("div must be a number") elif div == 0: raise ZeroDivisionError("division by zero") for row in matrix: rows_size.append(len(row)) new_matrix.append([]) for index in row: if type(index) != int and type(index) != float: raise TypeError(no_number) new_matrix[index_matrix].append(round((index / div), 2)) index_matrix += 1 for x in rows_size: if rows_size[0] != x: raise TypeError(different_size) return new_matrix
true
e8b1f3c9dd3e97b74d37ca22c4b88403954ff202
SergioO21/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/tests/6-max_integer_test.py
2,299
4.1875
4
#!/usr/bin/python3 """ Unittest for ``max_integer`` function """ import unittest max_integer = __import__('6-max_integer').max_integer class test_max_integer(unittest.TestCase): """ # unittests for the function ``max_integer(list=[])`` """ def test_one_argument(self): self.assertEqual(max_integer([9]), 9) self.assertEqual(max_integer([-10]), -10) def test_positive_numbers(self): self.assertEqual(max_integer([1, 2, 3, 4, 5]), 5) self.assertEqual(max_integer([700, 0, 12, 6587]), 6587) def test_negative_numbers_list(self): self.assertEqual(max_integer([-3, -5, -44]), -3) self.assertEqual(max_integer([-700, -8, -1000]), -8) def test_float_numbers_list(self): self.assertEqual(max_integer([10.5, 8.9, 9.4]), 10.5) self.assertEqual(max_integer([9.6, 71.5, 9.4]), 71.5) def test_same_numbers(self): self.assertEqual(max_integer([9, 7, 9]), 9) self.assertEqual(max_integer([10, 10, 10]), 10) def test_none_list(self): self.assertEqual(max_integer([]), None) def test_string_list(self): """ This function compare with the ASCII values """ item = ["Hello", "World", "Bye", "Holberton"] self.assertEqual(max_integer(item), "World") def test_tuple_list(self): item = [(7, 8, 9), (10, 11, 12)] self.assertEqual(max_integer(item), (10, 11, 12)) def test_dictionary_list(self): item = [{"First": 10, "Second": 20}, {"Third": 1, "Fourth": 2}] with self.assertRaises(TypeError): max_integer(item) def test_string_value(self): """ This function compare with the ASCII values """ self.assertEqual(max_integer("Hello World"), "r") self.assertEqual(max_integer("sergio"), "s") self.assertEqual(max_integer("Python"), "y") self.assertEqual(max_integer("Awesome"), "w") def test_mixed_list(self): item = ["Hello", 5, 10, "Bye"] with self.assertRaises(TypeError): max_integer(item) item = [10.5, 9, 3.4, 12] self.assertEqual(max_integer(item), 12) item = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] self.assertEqual(max_integer(item), [7, 8, 9]) if __name__ == "__main__": unittest.main()
false
808811951c539c67504735063f407442135aa7d9
meighanv/05-Python-Programming
/LABS/Threading/multithreading.py
1,309
4.21875
4
""" Running things concurrently is known as multithreading Running things in parallel is known as multiprocessing I/O bound tasks - Waiting for input and output to be completed, reading and writing from file system, network operations These all benefit more from threading You get the illusion of running code at the same time, however other code starts running while other code is waiting cpu bound tasks - Good for number crunching using CPU data crunching These benefit more from multiprocessing and running in parallel Using multiprocessing might be slower if you have overhead from creating and destroying files """ import threading import time start = time.perf_counter() def do_something(): print('Sleeping 1 second...') time.sleep(1) print('Done Sleeping...') # create 2 threads t1 = threading.Thread(target=do_something) t2 = threading.Thread(target=do_something) # start the thread t1.start() t2.start() # make sure the threads complete before moving on to calculate finish time t1.join() t2.join() finish = time.perf_counter() print(f'Finished in {finish-start} second(s)')
true
4a23b8eca75e3ab4d85135818bf5c496292894d4
meighanv/05-Python-Programming
/LABS/Labs-3-4/lab3-4-9-shipCharge.py
1,160
4.21875
4
#Setting up main function def main(): #Calling Charge function passing result of the getWeight function as an argument calcCharge(float(getWeight())) #Defining function to capture and validate the user's input of the number of packages purchased def getWeight(): #Getting initial input packageWeight = input('What is the weight of your package:\n') #Validating input to be numeric and greater than 0.00 while float(packageWeight) < 0 or packageWeight.replace('.','').isnumeric() == False: packageWeight = input('Invalid input. What is the weight of your package:\n') #Returning result to main return packageWeight #Function to determine shipping charge def calcCharge(num): #Charge for less than 2 pounds if num <= 2.00: print('The shipping charge is $1.10') #Charge for over 2 pounds upt0 6 elif num > 2 and num <= 6: print('The shipping charge is $2.20') #Charge for over 6 pounds upto 10 elif num > 6 and num <= 10: print('The shipping charge is $3.70') #Charge for more than 10 pounds elif num > 10: print('The shipping charge is $3.80') main()
true
37c5c209079b920c816c6a06442630b6ee933fe2
meighanv/05-Python-Programming
/LABS/Classes/cellphone.py
2,698
4.5
4
""" Wireless Solutions, Inc. is a business that sells cell phones and wireless service. You are a programmer in the company’s IT department, and your team is designing a program to manage all of the cell phones that are in inventory. You have been asked to design a class that represents a cell phone. The data that should be kept as attributes in the class are as follows: ​ • The name of the phone’s manufacturer will be assigned to the __manufact attribute. • The phone’s model number will be assigned to the __model attribute. • The phone’s retail price will be assigned to the __retail_price attribute. ​ The class will also have the following methods: • An __init__ method that accepts arguments for the manufacturer, model number, and retail price. • A set_manufact method that accepts an argument for the manufacturer. This method will allow us to change the value of the __manufact attribute after the object has been created, if necessary. • A set_model method that accepts an argument for the model. This method will allow us to change the value of the __model attribute after the object has been created, if necessary. • A set_retail_price method that accepts an argument for the retail price. This method will allow us to change the value of the __retail_price attribute after the object has been created, if necessary. • A get_manufact method that returns the phone’s manufacturer. • A get_model method that returns the phone’s model number. • A get_retail_price method that returns the phone’s retail price. """ # The CellPhone class pulls data about the cell phone class CellPhone: # The __init__ method initializes the attributes def __init__(self,manufact, model, price): self.__manufact = manufact self.__model = model self.__retail_price = price #The set_manufact method accepts an argument for the phone's manufacturer def set_manufact(self, manufact): self.__manufact = manufact # The set_model method accepts an argument for the phone's model number def set_model(self, model): self.__model = model # The set_retail_price method accepts and arguement for retail price def set_retail_price(self, price): self.__retail_price = price # The get_manufact method returns the phones manufacturer def get_manufact(self): return self.__manufact # The get_model method returns the phones model number def get_model(self): return self.__model # The get_price method returns the phones price def get_retail_price(self): return self.__retail_price
true
3e52bda4af910dccd9710c8d2bfd86388fe4fe07
meighanv/05-Python-Programming
/LABS/recursion/rec-lines.py
442
4.53125
5
""" 3. Recursive Lines Write a recursive function that accepts an integer argument, n. The function should display n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line showing 2 asterisks, up to the nth line which shows n asterisks. """ def main(): recLines(7) def recLines(n): if n == 0: return 0 else: print('*' + recLines(n-1)*'*') return n main()
true
d00a40884ba51cd5e12a01541e6dd828b884088a
meighanv/05-Python-Programming
/LABS/Classes/animals.py
1,084
4.125
4
class Mammal: # Initializing Mammal object attributes def __init__(self, species): self.__species = species def show_species(self): print('I am a ', self.__species) def make_sound(self): print('Grrr') class Dog(Mammal): # Initializing Dog subclass object attributes def __init__(self): Mammal.__init__(self, 'Dog') # This is an overide because it has the same name # as above, but this one will overwrite the 'Grrr' # sound def make_sound(self): print('Woof') class Cat(Mammal): # Initializing Dog subclass object attributes def __init__(self): Mammal.__init__(self, 'Cat') # This is an overide because it has the same name # as above, but this one will overwrite the 'Grrr' # sound def make_sound(self): print('Meow') # Define Main def main(): cat = Cat() cat.make_sound() cat.show_species() dog = Dog() dog.make_sound() dog.show_species() mammal = Mammal('fish') mammal.make_sound() mammal.show_species() main()
false
6963e9b7069b8bcd986331c1fe8a244eca289398
meighanv/05-Python-Programming
/LABS/DICTIONARIES-SETS/dict-set-wordcount.py
1,981
4.4375
4
#This program is to grab all the unique words in a file. def main(): #this is the dictionary to store a word count for each unique word wordcount = {} #Stores the lines of the file specified by the user source = readFile() #This calls the function to extract all the words from a file words = getWords(source) #This stores the return of the function which casts the words list as a set, making all words unique. unique = getUnique(words) countWords(wordcount,words,unique) print('Here is the count for each word in the file:') for i in wordcount: print('{}: {}'.format(i, wordcount[i])) #this simple takes an array and casts/returns it as a set def getWords(original): #Iterate through each line newlist = [] for i in original: #Split the lines by spaces (a typical delimeter in English between words) line = i.split(' ') #Add the words in the line to the list. newlist += line #Clean up each word in the list, getting rid of . \n "" and ? cleanlist = [] for i in newlist: i = i.replace('\n','').replace('.','').replace('!','').replace('?','').replace('"','') #ensures than all words are lower case to ensure set is properly unique i = i.lower() cleanlist.append(i) return cleanlist #Casts any list to a set and returns result to main def getUnique(array): uniqueItems = set(array) return uniqueItems def readFile(): #Getting filename from input for filename filename = input('Provide the new file name:\n') #Reads the file of filename f = open(filename, 'r') #Recording file contents in array contents = f.readlines() f.close() return contents def countWords(wordCount,words,unique): for uni in unique: count = 0 for word in words: if uni.lower() == word.lower(): count += 1 wordCount.update({uni: int(count)}) main()
true
9274734c6e50e164d86eb699a38088f1c6259aa1
meighanv/05-Python-Programming
/LABS/Labs-3-4/lab3-4-8-Discount.py
1,400
4.21875
4
#Setting up main function def main(): #Calling Discount function passing result of the numPurchase function as an argument calcDiscount(int(numPurchase())) #Defining function to capture and validate the user's input of the number of packages purchased def numPurchase(): #Getting initial input packages = input('How many packages did you buy:\n') #Validating input to be numeric and greater than 0 while int(packages) < 0 or packages.isnumeric() == False: packages = input('Invalid input. How many packages did you buy:\n') #Returning result to main return packages #Function to determine the level of discount def calcDiscount(num): #No discount if less than 10 packages purchased if num < 10: print('There is no discount for {} purchases'.format(num)) #20 percent discount 10-19 packages purchased elif num >= 10 and num <= 19: print('There is a 20 percent discount for {} purchases'.format(num)) #30 percent discount 20-49 packages purchased elif num >= 20 and num <= 49: print('There is a 30 percent discount for {} purchases'.format(num)) #40 percent discount 50-99 packages purchased elif num >= 50 and num <= 99: print('There is a 40 percent discount for {} purchases'.format(num)) elif num >= 100: print('There is a 50 percent discount for {} purchases'.format(num)) main()
true
11fbcfd7fa221cccbb29bb6c115b4a4abee7903d
meighanv/05-Python-Programming
/LABS/Classes/cashregister.py
2,056
4.46875
4
""" 7. Cash Register This exercise assumes that you have created the RetailItem class for Programming Exercise 5. Create a CashRegister class that can be used with the RetailItem class. The CashRegister class should be able to internally keep a list of RetailItem objects. The class should have the following methods: • A method named purchase_item that accepts a RetailItem object as an argument. Each time the purchase_item method is called, the RetailItem object that is passed as an argument should be added to the list. • A method named get_total that returns the total price of all the RetailItem objects stored in the CashRegister object’s internal list. • A method named show_items that displays data about the RetailItem objects stored in the CashRegister object’s internal list. • A method named clear that should clear the CashRegister object’s internal list. Demonstrate the CashRegister class in a program that allows the user to select several items for purchase. When the user is ready to check out, the program should display a list of all the items he or she has selected for purchase, as well as the total price. """ from functools import reduce class CashRegister: def __init__ (self): self.__purchase = [] self.__total = 0.0 def set_total(self): # This code below was replaced by the uncommented lambda function # total = 0 # for i in self.__purchase: # total += float(i.get_price()) * float(i.get_unitCount()) receipt = (item.get_price()*item.get_unitCount() for item in self.__purchase) self.__total = reduce((lambda x,y: x + y), receipt) def purchase_item(self,item): self.__purchase.append(item) def get_total(self): return self.__total def show_items(self): for i in self.__purchase: print(i.get_desc()) def clear_register(self): self.__purchase = [] self.__total = 0.0
true
041e263bf20440e54deb57f50d18db2dc7586953
yohn-dezmon/python-projs
/mad_lib_git.py
734
4.53125
5
# Prompt user for their name name = input("What is your name? ") # Greeting with users name print(f'''Hey {name}! Welcome to Mad Libs the program! Please provide us with...''') # Prompt user for a noun, adjective, and verb(ING) noun = input("A noun: ") adj = input("An adjective: ") verb = input("A verb ending in ing: ") # Print space between the prompts and the story print(''' ''') # Print the story using the inputs from the user. The title is in capitals and is cenetered. print(f'''Voila! Here is your story: \t\tTHE LOST BURRITO One day a burrito lost its {noun}. The burrito was so sad! He looked everywhere for this very {adj} {noun}. It was so dear to him, that he lost himself {verb} for the {noun}! Poor burrito!''')
true
f97b49d71868b3e45bfb79f831aecf16dc1f5d6a
aishsharma/Karan-Projects
/Solutions/Numbers/Prime_Factorization.py
1,272
4.3125
4
""" Author: Aishwarya Sharma Question: Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them. """ from math import sqrt from typing import List # Tests if a number is prime or not. Uses simple formula for test. def is_prime(n: int)->bool: if n <= 1: return False elif n <= 3: return True elif (n % 2 == 0) or (n % 3 == 0): return False i = 5 while i**2 <= n: if (n % i == 0) or (n % (i + 2) == 0): return False i += 6 return True def get_prime_factors(n: int)->List: if n < 2: print("Input should be at least 2.") return [] elif is_prime(n): print("Input is a prime number") return [] prime_factors = [] for i in range(2, round(sqrt(n)) + 1): if n % i == 0 and is_prime(i): prime_factors.append(i) return prime_factors def app(): try: n = int(input("Enter a number and I will give you its prime factors: ")) except ValueError: print("Input must be a number > 1") prime_factors = get_prime_factors(n) print("The prime factors of {0} are: ".format(n)) print(prime_factors) if __name__ == '__main__': app()
true
bad3f3bc881470c895cf0ea118bd2192a29b381a
jeff87b/Python-module-1
/Day 1-5/007 The area of a square with if and else.py
405
4.28125
4
print ("This program calculates the area of a square.") side1 = float(input("Enter side number one: ")) side2 = float(input("Enter side number two:")) print("The area is:", side1*side2) if side1<0: print("You have entered a negative first number") else: print("The first number is ok") if side2<0: print("You have entered a negative second number") else: print("The second number is ok")
true
2f218b9f31c503b5ff1ed49b311a44a8e1e9c31b
jeff87b/Python-module-1
/Day 6-10/Day 8/02.py
316
4.125
4
yearEntered = int(input("Enter a year: ")) def isLeapYear(year_entered): leapYearAlg = year_entered % 4 moreLeapYearAlg = year_entered % 100 if leapYearAlg == 0 and moreLeapYearAlg == 0: print("Yes it's a leap year") else: print("No, it's not a leap year") isLeapYear(yearEntered)
false
0bd2d83a82395c518a0860e6d490dfad023e8b3d
katharinameislitzer/smartninjacourse
/Class3_Python3/example_01210_read_analyse_exercise_solution.py
422
4.15625
4
# open the file "height.txt" # it contains the height of each person in the class # separated by a come "," # write a program which reads the file # saves the different heights in a list # and calculates the average height with open("height.txt") as file: a = file.read().split(",") height_avg=0 number_of_people=len(a) for i in a: height_avg += int(i) height_avg=height_avg/number_of_people print(height_avg)
true
7ead56c5eff91f2c77a07160363211d7c124d579
katharinameislitzer/smartninjacourse
/Class1_Python3/example_0500_calculator_excercise_2.py
899
4.375
4
# print welcome to user name = input("Please enter your name: ") print(f"Welcome {name}") # read user input for operation operation = input("Please enter a mathematical sign (+, -, *, /): ") print(f"You entered {operation}") # read user input for first value first_value = int(input("Please enter number one: ")) print(f"You entered {first_value}") # read user input for second value second_value = int(input("Please enter number two: ")) print(f"You entered {second_value}") # calculate depending on operators result = None if operation is "+": print(f"The result is {first_value + second_value}") elif operation is "-": print(f"The result is {first_value - second_value}") elif operation is "*": print(f"The result is {first_value * second_value}") elif operation is "/": print(f"The result is {first_value / second_value}") else: print("nope, try again") # and print result
true
a8ad2f52a50cc7be3a9fc3f86c6a206bc1369e11
HaoxuZhang/python-learning
/some-tests/iter.py
245
4.25
4
list=[1,2,3,4] it=iter(list) print(next(it)) print(next(it)) for x in it: print(x,end=" ") #该函数输出为 ''' 1 2 3 4 ''' #iter返回的是一个迭代器,第一次使用next函数会让迭代器指向第一个元素并且保存位置
false
550dd8ab9ba9d4ad3527ed8461efa4623fc6497a
pransil/skLearnMnistViz
/plot_mnist_filters.py
2,337
4.28125
4
""" ===================================== Visualization of MLP weights on MNIST ===================================== Sometimes looking at the learned coefficients of a neural network can provide insight into the learning behavior. For example if weights look unstructured, maybe some were not used at all, or if very large coefficients exist, maybe regularization was too low or the learning rate too high. This example shows how to plot some of the first layer weights in a MLPClassifier trained on the MNIST dataset. The input data consists of 28x28 pixel handwritten digits, leading to 784 features in the dataset. Therefore the first layer weight matrix have the shape (784, hidden_layer_sizes[0]). We can therefore visualize a single column of the weight matrix as a 28x28 pixel image. To make the example run faster, we use very few hidden units, and train only for a very short time. Training longer would result in weights with a much smoother spatial appearance. """ print(__doc__) import matplotlib.pyplot as plt from sklearn.datasets import fetch_mldata from sklearn.neural_network import MLPClassifier def main(): mnist = fetch_mldata("MNIST original") # rescale the data, use the traditional train/test split X, y = mnist.data / 255., mnist.target X_train, X_test = X[:60000], X[60000:] y_train, y_test = y[:60000], y[60000:] # mlp = MLPClassifier(hidden_layer_sizes=(100, 100), max_iter=400, alpha=1e-4, # solver='sgd', verbose=10, tol=1e-4, random_state=1) mlp = MLPClassifier(hidden_layer_sizes=(40,60,40), max_iter=10, alpha=3e-2, solver='adam', verbose=10, tol=1e-4, random_state=1, learning_rate_init=.0001) mlp.fit(X_train, y_train) print("Training set score: %f" % mlp.score(X_train, y_train)) print("Test set score: %f" % mlp.score(X_test, y_test)) fig, axes = plt.subplots(4, 4) # use global min / max to ensure all weights are shown on the same scale vmin, vmax = mlp.coefs_[0].min(), mlp.coefs_[0].max() for coef, ax in zip(mlp.coefs_[0].T, axes.ravel()): ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin, vmax=.5 * vmax) ax.set_xticks(()) ax.set_yticks(()) plt.show() if __name__ == '__main__': main()
true
3bc4c4a6489d517288488c4bc1c33802177a65cc
Mpreyzner/python_algorithms
/n_queens.py
2,564
4.3125
4
# The N Queen is the problem of placing N chess queens on an N×N chessboard # so that no two queens attack each other. # 1) Start in the leftmost column # 2) If all queens are placed # return true # 3) Try all rows in the current column. Do following for every tried row. # a) If the queen can be placed safely in this row then mark this [row, # column] as part of the solution and recursively check if placing # queen here leads to a solution. # b) If placing queen in [row, column] leads to a solution then return # true. # c) If placing queen doesn't lead to a solution then umark this [row, # column] (Backtrack) and go to step (a) to try other rows. # 3) If all rows have been tried and nothing worked, return false to trigger # backtracking. n = 4 def print_solution(board): for i in range(n): for j in range(n): print(board[i][j]), print("") # A utility function to check if a queen can # be placed on board[row][col]. Note that this # function is called when "col" queens are # already placed in columns from 0 to col -1. # So we need to check only left side for # attacking queens def is_safe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, n, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def solve_util(board, column): # base case: If all queens are placed # then return true if column >= n: return True # Consider this column and try placing # this queen in all rows one by one for i in range(n): if is_safe(board, i, column): # Place this queen in board[i][col] board[i][column] = 1 # recur to place rest of the queens if solve_util(board, column + 1): return True # backtrack board[i][column] = 0 # if queen can not be place in any row in return False def solve_n_queens(): board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if solve_util(board, 0): print_solution(board) return True print("Solution does not exist") return False solve_n_queens()
true
a4061d17e097fc2a7753ce54998eac01619272b1
simransidhu8/C98---Functions
/countWordsFromFile.py
299
4.28125
4
def countWordsFromFile() : fileName = input("Enter file name: ") numberOfWords = 0 f = open(fileName) for line in f : words = line.split() numberOfWords = numberOfWords + len(words) print("Number of words: ") print(numberOfWords) countWordsFromFile()
true
0da0ed62861394a7c4f59eb442dc4a77e1f810fc
Pycone/Python-for-Beginners
/src/ch4/ch4.py
1,350
4.28125
4
''' List example ''' numbers = [1, 2] numbers.append(3) numbers.remove(3) len(numbers) numbers.pop() numbers = [5, 7, 1, 2, 3] numbers.sort() numbers[0] numbers[1] numbers[2] = 'hello python' print (numbers) numbers = [[1,2,3],[4,5,6]] students = [] students.append(['David', 123, True]) students.append(['Hubert', 321, False]) print (students) print (type(students)) students = ['David', 'Hubert', 'Kobe', 'Curry'] students[0:2] students[:4] students[0:] students[:] students[:-1] name = 'David' name[0:2] name[:4] name[0:] name[:] name[:-1] name[0:4:1] name[1::1] name[2::2] name[::2] name[::-1] ''' Set example ''' Warriors = set() Warriors.add('Curry') Warriors.add('Thompson') Warriors.add('Durant') Warriors.remove('Durant') print ('David' in students) {'Hubert', 'David', 'Kobe'} #{{'Hubert', 'David', 'Kobe'}} #{['Hubert', 'David', 'Kobe']} set('kkbox') print (set(['Hubert', 'David', 'Kobe'])) print (type(set(['Hubert', 'David', 'Kobe']))) ''' Tuple example ''' (1, 2, 3) print (type((1, 2))) student = ('David', 123) name, student_id, = student print (name, student_id) ''' Dict example ''' Warriors = {"Curry":"G","Green":"F","Durant":"F"} students = {'David' : 1, 'Hubert' : 2, 'Kobe' : 3} students['David'] students['Hubert'] = 5 del students['Hubert'] students.items() students.keys() students.values() print (type(students))
false
862fbb1580e0dd290a61dae003c552128fe97c64
HunterLaugh/codewars_kata_python
/kata_4_Validate_Sudoku_with_size_N_N.py
2,053
4.125
4
''' 4 kyu Validate Sudoku with size `NxN` Given a Sudoku data structure with size NxN, N > 0 and √N == integer, write a method to validate if it has been filled out correctly. The data structure is a multi-dimensional Array(in Rust: Vec<Vec<u32>>) , ie: [ [7,8,4, 1,5,9, 3,2,6], [5,3,9, 6,7,2, 8,4,1], [6,1,2, 4,3,8, 7,5,9], [9,2,8, 7,1,5, 4,6,3], [3,5,7, 8,4,6, 1,9,2], [4,6,1, 9,2,3, 5,8,7], [8,7,6, 3,9,4, 2,1,5], [2,4,3, 5,6,1, 9,7,8], [1,9,5, 2,8,7, 6,3,4] ] Rules for validation Data structure dimension: NxN where N > 0 and √N == integer Rows may only contain integers: 1..N (N included) Columns may only contain integers: 1..N (N included) 'Little squares' (3x3 in example above) may also only contain integers: 1..N (N included) ''' # ---- row ||| column +++ palace class Sudoku(object): def __init__(self,value): self.L=value def getN(self): return len(self.L) def get_listN(self): return list(range(1,N+1)) def is_N_N(self): for i in range(N): if len(self.L[i])!=n: return False return True def is_row(self): for each in self.L: each.sort() if each!=listN: return False return True def is_column(self): j=0 # column while j<N: i=0 # row temp=[] while i<N: temp.append(self.L[i][j]) i+=1 temp.sort() if temp!=listN: return False j+=1 return True def is_palace(self): pass N=self.getN() listN=self.get_listN() def is_valid(self): if self.is_N_N(): if self.is_row(): if self.is_column(): return True return False testValue=[ [7,8,4, 1,5,9, 3,2,6], [5,3,9, 6,7,2, 8,4,1], [6,1,2, 4,3,8, 7,5,9], [9,2,8, 7,1,5, 4,6,3], [3,5,7, 8,4,6, 1,9,2], [4,6,1, 9,2,3, 5,8,7], [8,7,6, 3,9,4, 2,1,5], [2,4,3, 5,6,1, 9,7,8], [1,9,5, 2,8,7, 6,3,4] ] testSudoku=Sudoku(testValue) print(testSudoku.is_valid())
true
d720678c5d305947059da4ea89fa966aeecd0b51
HunterLaugh/codewars_kata_python
/kata_6_Format_words_into_a_sentence.py
1,028
4.21875
4
''' Format words into a sentence Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned. formatWords(['ninja', 'samurai', 'ronin']) // should return "ninja, samurai and ronin" formatWords(['ninja', '', 'ronin']) // should return "ninja and ronin" formatWords([]) // should return "" ''' def format_words(words): if not words: return "" L=[] for each in words: if each: L.append(each) if not L: return "" n=len(L) if n==1: return L[0] elif n==2: return L[0]+' and '+L[1] else: i=0 while i<n-2: L[i]=L[i]+',' i+=1 L.insert(n-1,'and') return ' '.join(L) l=['one','two', 'three','four'] print(format_words(l))
true
e782a8a494d70e5f2d4b0000b1f1d2658513b2ee
HunterLaugh/codewars_kata_python
/kata_5_Regex_for_Gregorian_date_validation.py
1,115
4.15625
4
''' Regex for Gregorian date validation Your task is to write regular expression that validates gregorian date in format "DD.MM.YYYY" Correct date examples: "23.12.2008" "01.08.1994" Incorrect examples: "12.23.2008" "01-Aug-1994" " 01.08.1994" Notes: maximum length of validator is 400 characters to avoid hardcoding. (shortest solution to date is 170 characters) validator should process leap days (February, 29) correctly. the date is Gregorian, it's important to determine if year is leap: https://en.wikipedia.org/wiki/Gregorian_calendar ''' date_validator = r'([01][0-9]|2[0-9]|3[01]).([0][13578]|1[12])' # TEST CASE import re test.assert_equals(bool(re.match(date_validator,'01.01.2009')), True, 'Basic correct date: 01.01.2009') test.assert_equals(bool(re.match(date_validator,'01-Jan-2009')), False, 'Incorrect mask: 01-Jan-2009') test.assert_equals(bool(re.match(date_validator,'05.15.2009')), False, 'Incorrect month: 15.15.2009')
true
3936d910807507e628b4a0ef156a3a8f9eac24eb
HunterLaugh/codewars_kata_python
/kata_8_Who_ate_the_cookie.py
879
4.5625
5
''' 8 kyu Who ate the cookie For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is: "Who ate the last cookie? It was (name)!" Ex: Input = "It was Monica" --> Output = "Who ate the last cookie? It was Zach! (The reason you return Zach is because the input is a string) Note: Make sure you return the correct message with correct spaces and punctuation. ''' def cookie(x): x_type=type(x) res='' if x_type==str : res="Who ate the last cookie? It was Zach!" elif x_type==int or x_type==float: res="Who ate the last cookie? It was Monica!" else: res="Who ate the last cookie? It was the dog!" return res
true
91ce21140d3ef1fc0a0aa0771979746d4fb330b9
Wallkon/Ejercicios-de-The-Python-Workbook
/Exercise_12_Distance_Between_Two_Points_on_Earth.py
1,929
4.5625
5
""" The surface of the Earth is curved, and the distance between degrees of longitude varies with latitude. As a result, finding the distance between two points on the surface of the Earth is more complicated than simply using the Pythagorean theorem. Let (t1, g1) and (t2, g2) be the latitude and longitude of two points on the Earth’s surface. The distance between these points, following the surface of the Earth, in kilometers is: distance = 6371.01 × arccos(sin(t1) × sin(t2) + cos(t1) × cos(t2) × cos(g1 − g2)) The value 6371.01 in the previous equation wasn’t selected at random. It is the average radius of the Earth in kilometers. Create a program that allows the user to enter the latitude and longitude of two points on the Earth in degrees. Your program should display the distance between the points, following the surface of the earth, in kilometers. Hint: Python’s trigonometric functions operate in radians. As a result, you will need to convert the user’s input from degrees to radians before computing the distance with the formula discussed previously. The math module contains a function named radians which converts from degrees to radians. Esta página puede servir, pero no da el mismo resultado: http://keisan.casio.com/exec/system/1224587128 """ import math AVG_RADIUS_HEARTH_KILOMETERS = 6371.01 t1_grades = float(input("ingrese t1: ")) g1_grades = float(input("ingrese g1: ")) t2_grades = float(input("ingrese t2: ")) g2_grades = float(input("ingrese g2: ")) t1_rads = math.radians(t1_grades) g1_rads = math.radians(g1_grades) t2_rads = math.radians(t2_grades) g2_rads = math.radians(g2_grades) #distance = 6371.01 × arccos(sin(t1) × sin(t2) + cos(t1) × cos(t2) × cos(g1 − g2)) distancia = AVG_RADIUS_HEARTH_KILOMETERS * math.acos(math.sin(t1_rads) * math.sin(t2_rads) * math.cos(t2_rads) * math.cos(g1_rads - g2_rads) ) print("La distancia es de {} km".format(distancia))
true
b98068b9164c4daa471c65ea6ec25082dd26db0f
EDalSanto/ThinkPythonExercises
/cartalk1_triple_double.py
594
4.375
4
fin = open("ThinkPython/words.txt") def triple_double(word): """Tests if a word contains three consecutive double letters""" i = 0 doubles = 0 while i < len(word)-1: if word[i] == word[i+1]: doubles += 1 if doubles == 3: return True i += 2 else: doubles = 0 i += 1 return False def find_triple_double(): """Reads a word list and prints words with triple double letters""" for line in fin: word = line.strip() if triple_double(word): print word
true
9bd1d9c2a6a087a028eed2119926ea5bc3f94811
Hammad-Ishaque/pydata-practise
/DesignPatterns/FactoryPattern.py
868
4.125
4
from abc import ABCMeta, abstractmethod # What particular instance to create class IPerson(metaclass=ABCMeta): @abstractmethod def person_method(self): """ :return: """ class Student(IPerson): def __init__(self): self.name = "I am Student" def person_method(self): print("This is Student!") class Teacher(IPerson): def __init__(self): self.name = "I am Teacher" def person_method(self): print("This is Teacher!") class PersonFactory: @staticmethod def build_person(person_type): if person_type == "Student": return Student() if person_type == "Teacher": return Teacher() return -1 choice = input("What type of person do you want to create?\n") person = PersonFactory.build_person(choice) person.person_method()
true
53fe220d2fcb589571740e9f1998c8977385b350
KazZBodnar/pythoncalc
/main.py
1,793
4.3125
4
import math #help = input("PythonCalc V 1.0; Say 'help' for more info, and 'ready' to start the calculator.") #if help== "help" or "Help": # print("Signs: '+', '-', '*', '/', '^2', 'sqrt', '^3', '!', 'power'.") #else: print("PythonCalc V 1.0 type help for a list of commands") sign = input("What sign should I use?") if sign== "+": num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) print(num1+num2) elif sign== "-": num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) print (num1-num2) elif sign== "*": num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) print (num1*num2) elif sign== "/": num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) print (num1/num2) elif sign== "^2": num1 = int(input("What is the number you wish to be squared? ")) print (num1**2) elif sign== "^3": num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) print (num1**3) elif sign== "power": num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) print (num1**num2) elif sign== "sqrt": num1 = int(input("What is the number you seek the squae root of? ")) print (math.sqrt(num1)) elif sign== "!": num1 = int(input("What is the number you seek the factorial of? ")) print (factorial(num1)) elif sign== "help": print("you can add, subtract, multiply, divide, square, cube, do exponents, find square root, and find factorial.") else: print("I am sorry, but I am unable to process your request.")
true
eb39c96d98e1e0813a65215471616a5fe75c71ad
hermineavagyan/OOP
/userClass.py
2,077
4.125
4
class User: #defining a class attriute bank_name = "First Dational Dojo" #creating the class constructor def __init__(self, name, email_address): self.name = name self.email = email_address self.account_balance = 0 # increases the user's balance by the amount specified def make_deposit(self, amount): self.account_balance += amount #decreases the user's balance by the amount specified def make_withdrawal(self, amount): self.account_balance -= amount #prints the user's name and account balance to the terminal def display_user_balance(self): print(self.name, self.account_balance) #decrease the user's balance by the amount and # add that amount to other other_user's balance def transfer_money(self, other_user, amount): self.account_balance -= amount other_user.account_balance += amount #prints greeting message togteher with the user name def greeting(self): print("Hello my name is", self.name) print("my email is ", self.email) #creating 3 users user1 = User("Adrien", "adrien@yahoo.com") user2 = User("Hermine", "hermine@codingdojo.com") user3 = User("Bob", "bob@codingdojo.com") #first user makes 3 deposits and 1 withdrawals user1.make_deposit(400) user1.make_deposit(400) user1.make_deposit(600) user1.make_withdrawal(200) #second user makes 2 deposits and 2 withdrawals user2.make_deposit(500) user2.make_deposit(800) user2.make_withdrawal(300) user2.make_withdrawal(100) #third user makes 1 deposits and 3 withdrawals user3.make_deposit(800) user3.make_withdrawal(300) user3.make_withdrawal(500) user3.make_withdrawal(150) #call display_user_balance method to display the users' account balances user1.display_user_balance() user2.display_user_balance() user3.display_user_balance() user1.transfer_money(user3,200) print() print("After calling transfer money method the account balances of the first and the third user") # after calling transfer money method the account balances of the first and the third user user1.display_user_balance() user3.display_user_balance()
true
c069162616ae7c88cd340cf425e63b90e0770f46
cs-fullstack-2019-spring/python-loops-cw-leejr1983
/PythonLoopsCW.py
1,708
4.34375
4
from _ast import If def main(): # problem1() #problem2() #problem3() problem4() # Exercise 1: # Print -20 to and including 50. # Use any loop you want. def problem1(): for numbers in range(-20,51): print (numbers) # Exercise 2: # Create a loop that prints even numbers from 0 to and including 20. def problem2(): for numbers in range (0,21,2): print(numbers) # Exercise 3: # Prompt the user for 3 numbers. Then print the 3 numbers along with their average after the 3rd number is entered. # Refer to example below replacing NUMBER1, NUMBER2, NUMBER3, and THEAVERAGE with the actual values. # Ex.Output # The average of NUMBER1, NUMBER2, and NUMBER3 is THEAVERAGE def problem3(): userInput= int(input("Please enter number 1")) userInput2= int(input("Please enter number 2")) userInput3= int(input("please enter number 3")) average= int((userInput + userInput2 + userInput3) /3) print("The average of",str(userInput),str(userInput2),str(userInput3),"is",str(average)) # Exercise 4: # Password Checker - Ask the user to enter a password. Ask them to confirm the password. # If it's not equal, keep asking until it's correct or they enter 'Q' to quit. def problem4(): userInput= input("Please enter password") userInput2= input("Please verify your password") while (userInput2 != userInput or "q"): if (userInput == userInput2): print ("Thank you") break elif (userInput2 == "q"): print ("User has chosen to quit") break else: userInput2= input("Please verify your password") if __name__ == '__main__': main()
true
50249cbfbfd0eb2e6a64cb97c00743ad91541cdf
Prabithapallat01/pythondjangoluminar
/flow_controls/looping/samlefor.py
343
4.125
4
#for i in range(start,stop): #loop body #for i in range(1,10): #print(i) #for i in range (10,0,-1): # print(i) # to print total of first 50 numbers #total=0 #for i in range(1,51): # total=total+i #print(total) # to print given number is prime or not #to print allprime numbers btwn 5 to 50 #low=5 #upperlimi=50 #2 read a number
true
59793bcf0f03f686239659306a7df2e18d72335a
chefmohima/python
/stack_list_implement.py
938
4.125
4
class Stack: #list-based stack implementation def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def push(self,item): self.items.append(item) def pop(self): if self.items == []: raise EmptyStackError("Stack is empty!") else: item = self.items.pop() return item def display(self): print(self.items) print("********************") def peek(self): if self.items == []: raise EmptyStackError("Stack is empty!") else: print(self.items[-1]) #Client code to test stack operations s = Stack() s.push(10) s.push(9) s.push(8) s.push(7) s.display() s.pop() s.pop() s.peek() s.display()
false
fb167dcdd270d019402443230887932aecdd3ed4
cs-fullstack-2019-fall/codeassessment2-LilPrice-Code
/q3.py
708
4.40625
4
# ### Problem 3 # Given 2 lists of claim numbers, write the code to merge the 2 lists provided to produce a new list by alternating values between the 2 lists. Once the merge has been completed, print the new list of claim numbers (DO NOT just print the array variable!) # ``` # # Start with these lists # list_of_claim_nums_1 = [2, 4, 6, 8, 10] # list_of_claim_nums_2 = [1, 3, 5, 7, 9] # ``` # Example Output: # ``` # The newly created list contains: 2 1 4 3 6 5 8 7 10 9 # ``` # Starting variables nums1 = [2, 4, 6, 8, 10] nums2 = [1, 3, 5, 7, 9] numall=[] # adding to Array for x in range(0,len(nums1)): numall.append(nums1[x]) numall.append(nums2[x]) # Printing Array print(numall)
true
29e7eb490b503b8ce6f4c6ff9f582ef9e2163913
AmelishkoIra/it-academy-summer-2021
/task1_hw4.py
1,423
4.5
4
"""Функции из Homework4 для тестирования""" def compare_lists(list_one, list_two): """ Функция считает, сколько различных чисел содержится одновременно как в первом списке, так и во втором. """ compare = list_one & list_two return len(compare) def compare_lists_difference(list_one, list_two): """ Функция считает, сколько различных чисел входит только в один из списков. """ compare_difference = list_one ^ list_two return len(compare_difference) def counting_different_words(text): """ Функция определяет, сколько различных слов содержится в веденном тексте. """ text_without_spaces = text.split(" ") set_text = set(text_without_spaces) return len(set_text) def euclidean_algorithm(a, b): """ Функция вычисляет наибольший общий делитель двух чисел при помощи алгоритма Евклида. """ while a != 0 and b != 0: if a > b: a = a % b else: b = b % a else: return "Наибольший общий делитель: {}".format(a + b)
false
462c756db5826b1b0586f32e6bc0687f85128719
Leg3nd3/Project_97
/guessNumber.py
426
4.25
4
import random number = random.randint(1, 5) guess = int(input("Enter a number from 1 to 5: ")) while number != "guess": print if guess < number: print("Guess is low") guess = int(input("Enter a number from 1 to 5: ")) elif guess > number: print("Guess is high") guess = int(input("Enter a number from 1 to 5: ")) else: print("You guessed it!") break
true
6184fe53341c9eb095ec008871ae31ecf8f5219e
nadiamarra/learning_python
/triangle.py
776
4.28125
4
def area(base,height): """(number,number)-> number Return the area of a triangle with dimensions base and height. >>>area(10,5) 25.0 >>>area(2.5,3) 3.75 """ return base*height/2 def perimeter(side1,side2,side3): """(number,number,number) -> number Return the perimeter of a triangle with sides of length side1, side2 and side3. >>>perimeter(3,4,5) 12 >>>perimeter(10.5,6,9.3) 25.8 """ return side1+side2+side3 def semiperimeter(side1,side2,side3): """(number,number,number)-> float Return the semiperimeter of a triangle with sides of length side1,side2 and side3. >>>semiperimeter(3,4,5) 6.0 >>>semiperimetre(10.5,6,9.3) 12.9 """ return perimeter(side1,side2,side3)/2
true
8a68d28e002f59a91c15da4bf2a283958fbf7857
nadiamarra/learning_python
/rock_paper_scissors_against_computer.py
1,696
4.15625
4
import random player_wins=0 computer_wins=0 while player_wins<2 and computer_wins<2: print("rock...\npaper...\nscissors...") print(f"Player Score:{player_wins} Computer Score:{computer_wins}") player=input("Player, make your move: ") rand_num=random.randint(0,2) if rand_num==0: computer="rock" elif rand_num==1: computer="paper" else: computer="scissors" print(f"Computer plays {computer}") if player==computer: print("It's a tie!") elif player=="rock": if computer=="scissors": print("Player wins!") player_wins+=1 elif computer=="paper": print("Computer wins!") computer_wins+=1 elif player=="paper": if computer=="rock": print("Player wins!") player_wins+=1 elif computer=="scissors": print("Computer wins!") computer_wins+=1 elif player=="scissors": if computer=="paper": print("Player wins!") player_wins+=1 elif computer=="rock": print("Computer wins!") computer_wins+=1 else: print("Something went wrong") print(f"FINAL SCORES... Player:{player_wins} Computer:{computer_wins}") if player_wins>computer_wins: print("Bravoooo") else: print("Shit")
true
39148beb2114fccdf719e143a4da66607eee1b22
nadiamarra/learning_python
/invert_dict.py
962
4.21875
4
fruit_to_colour={ 'banana':'yellow', 'cherry':'red', 'orange':'orange', 'pear':'green', 'peach':'orange', 'plum':'purple', 'pomegranate':'red', 'strawberry':'red' } #inverting fruit_to_colour colour_to_fruit={} #accumulator set as the new dict name for fruit in fruit_to_colour: #iterating over the keys colour=fruit_to_colour[fruit] #assigning all the values to the variable colour #adding to the new dict colour_to_fruit[colour]=fruit ###issue: there are more than one fruit for each of the colours associated ###with those three missing fruits ## ###if colour is not already a key in the accumulator ###add colour:[fruit] as an entry ## ## if not(colour in colour_to_fruit): ## colour_to_fruit[colour]=[fruit] ## #####otherwise, append fruit to the existing list ## ## else: ## colour_to_fruit[colour].append(fruit) ##
true