blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
23f9d9fc5134daddae2aa9bc7c15853370b464ae
EddyScript/Git-With-Eddy
/Calculator.py
1,092
4.28125
4
# Assignment 1--------------------------------------------- def calculator(): first_number = int(input("Enter a number: ")) operator = input("Enter an operator: ") ops = ["+","-","*","/"] if operator in ops: second_number = int(input("Enter another number: ")) else: print("Sorry," + "'" + operator + "'"+ " is not valid.") quit_prompt = input("Press Q to quit OR enter to try again: ") q_button = ["Q","q"] if quit_prompt in q_button: quit() print(calculator()) def sub(number1,number2): print(number1 + number2) if operator == "+": sub(first_number,second_number) def sub(number1,number2): print(number1 - number2) if operator == "-": sub(first_number,second_number) def multi(number1,number2): print(number1 * number2) if operator == "*": multi(first_number,second_number) def div(number1,number2): print(number1 / number2) if operator == "/": div(first_number,second_number) calculator()
false
dc66d84ad39fb2fe87895ca376652e9d95781326
amshapriyaramadass/learnings
/Hackerrank/Interviewkit/counting_valley.py
789
4.25
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countingValleys' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER steps # 2. STRING path #Sample Input # #8 #UDDDUDUU #Sample Output #1 # def countingValleys(steps, path): sealevel = 0 valeylevel = 0 for path1 in path: if path1 == 'U': sealevel += 1 else: sealevel -= 1 if path1 == 'U' and sealevel == 0: valeylevel += 1 return valeylevel # Write your code here if __name__ == '__main__': steps = int(input().strip()) path = input() result = countingValleys(steps, path) print(result)
true
35775689bab1469a42bae842e38963842bf54016
scottherold/python_refresher_8
/ExceptionHandling/examples.py
731
4.21875
4
# practice with exceptions # user input for testing num = int(input("Please enter a number ")) # example of recursion error def factorial(n): # n! can also be defined as n * (n-1)! """ Calculates n! recursively """ if n <= 1: return 1 else: return n * factorial(n-1) # try/except (if you know the errortype) # it's best to be explicit about exceptions that you are handling and it # is good practice to have different try/except blocks for multiple # potential exceptions try: print(factorial(num)) # example of multiple exceptions handling simultaneously) except (RecursionError, OverflowError): print("This program cannot calculate factorials that large") print("Program terminating")
true
52c84ab4101801d394c4c8ee1dc3621e54b8285c
Reyes2777/100_days_code
/python_class/exercise_1.py
515
4.15625
4
#Write a Python program to convert an integer to a roman numeral. class Numbers: def int_to_roman(self, number_i): value = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] roman_numbers = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] roman_num = [] for i in range(len(value)): count = int(number_i / value[i]) roman_num.append(roman_num[i]*count) number_i = number_i - count return ''.join(roman_num)
false
9aeb414b897c3948dfe4313d40b30bd7471a3d49
priyal-jain-84/Projects
/sudoku project.py
2,429
4.25
4
# Sudoku project using backtracking method # board=[ [7,3,0,9,5,0,0,0,0], [2,0,0,6,7,0,5,8,0], [0,0,5,0,1,0,4,0,0], [1,9,0,0,6,3,2,0,5], [0,4,0,0,0,0,6,0,0], [5,6,8,2,0,7,0,0,0], [0,2,0,0,8,1,3,0,0], [0,0,1,0,0,9,7,6,0], [0,7,0,5,2,0,8,0,9] ] # to print the board in a good and understandable manner def print_board(boa): for i in range (len(boa)): if i%3==0 and i!=0: print("-------------------------------") for j in range(len(boa)): if j%3 == 0 and j!= 0: print(" | ",end="") if j==8: print(boa[i][j]) else: print(str(boa[i][j]) + " ", end=" ") # to find all the empty elements in the board def find_empty(boa): for i in range (len(boa)): for j in range(len(boa)): if boa[i][j]==0: return (i,j) # to check if the value is valid for any position def valid(boa,pos,num): # to check whether the no. is appearing in the given row.. for i in range(len(boa)): if boa[pos[0]][i]== num: return False # to check whether the no. is appearing in the given column.. for i in range(len(boa)): if boa[i][pos[1]] == num: return False # to check whether the no. is appearing in the given square box.. x0 = (pos[1] // 3 ) * 3 y0 = (pos[0] // 3 ) * 3 for i in range (0,3): for j in range(0,3): if boa[y0+i][x0+j] == num: return False # if non of the condition is false then the value is valid so it will return True return True # fuction which uses all this function and return the final solution def solution(boa): find =find_empty(boa) if not find: return True else: row,column = find for i in range(0,10): if valid (boa,(row,column),i): boa[row][column] = i if solution(boa): return True boa[row][column]=0 return False print("Question Board\n____________________________\n") print_board(board) solution (board) print("\nSolution Board\n____________________________\n") print_board(board)
false
8923477b47a2c2d283c5c4aba9ac797c589fbf7e
nobin50/Corey-Schafer
/video_6.py
1,548
4.15625
4
if True: print('Condition is true') if False: print('Condition is False') language = 'Python' if language == 'Python': print('It is true') language = 'Java' if language == 'Python': print('It is true') else: print('No Match') language = 'Java' if language == 'Python': print('It is Python') elif language == 'Java': print('It is Java') else: print('No Match') user = 'Admin' logged_in = True if user == 'Admin' and logged_in: print('Admin Page') else: print('Bad Creeds') user = 'Admin' logged_in = False if user == 'Admin' and logged_in: print('Admin Page') else: print('Bad Creeds') user = 'Admin' logged_in = False if user == 'Admin' or logged_in: print('Admin Page') else: print('Bad Creeds') user = 'Admin' logged_in = False if not logged_in: print('Please Log In') else: print('Welcome') a = [1, 2, 3] b = [1, 2, 3] print(id(a)) print(id(b)) print(a is b) a = [1, 2, 3] b = [1, 2, 3] b = a print(id(a)) print(id(b)) print(a is b) print(id(a) == id(b)) condition = False if condition: print('Evaluated to true') else: print('Evaluated to false') condition = None if condition: print('Evaluated to true') else: print('Evaluated to false') condition = 0 if condition: print('Evaluated to true') else: print('Evaluated to false') condition = "" if condition: print('Evaluated to true') else: print('Evaluated to false') condition = {} if condition: print('Evaluated to true') else: print('Evaluated to false')
true
6a22f2e3cd18309c2b74becebafa184467ce9b87
Piper-Rains/cp1404practicals
/prac_05/hex_colours.py
591
4.375
4
COLOUR_CODES = {"royalblue": "#4169e1", "skyblue": "#87ceeb", "slateblue": "#6a5acd", "slategray1": "#c6e2ff", "springgreen1": "#00ff7f", "thistle": "#d8bfd8", "tomato1": "#ff6347", "turquoise3": "#00c5cd", "violet": "#ee82ee", "black": "#000000"} print(COLOUR_CODES) colour_name = input("Enter colour name: ").lower() while colour_name != "": if colour_name in COLOUR_CODES: print(colour_name, "has code:", COLOUR_CODES[colour_name]) else: print("Invalid colour name entered") colour_name = input("Enter colour name: ").lower()
false
e8893f7e629dede4302b21efee92ff9030fe7db2
Piper-Rains/cp1404practicals
/prac_05/word_occurrences.py
468
4.25
4
word_to_frequency = {} text = input("Text: ") words = text.split() for word in words: frequency = word_to_frequency.get(word, 0) word_to_frequency[word] = frequency + 1 # for word, count in frequency_of_word.items(): # print("{0} : {1}".format(word, count)) words = list(word_to_frequency.keys()) words.sort() max_length = max((len(word) for word in words)) for word in words: print("{:{}} : {}".format(word, max_length, word_to_frequency[word]))
true
6abf00b079ceab321244dbe606f05bac9a347be0
siva237/python_classes
/Decorators/func_without_args.py
1,331
4.28125
4
# Decorators: # ---------- # * Functions are first class objects in python. # * Decorators are Higher order Functions in python # * The function which accepts 'function' as an arguments and return a function itslef is called Decorator. # * Functions and classes are callables as the can be called explicitly. # def hello(a): # return a # hello(5) # ----------------------- # def hello(funct): # # # return funct # ---------------------- # # 1. Function Decorators with arguments # 2. Function Decorators without arguments # 3. Class Decorators with arguments # 4. Class Decorators without arguments. class Student: def __init__(self): pass def __new__(self): pass def __call__(self): pass obj = Student() # def validate(func): # def abc(x, y): # if x > 0 and y > 0: # print(func(x, y)) # else: # print("x and y values should be greater than 0") # return abc # @validate # def add(a, b): # return a + b # out = add(20, 20) # @validate # def sub(a, b): # return a - b # print(out) # out1 = sub(20, 10) # print(out1) def myDecor(func): def wrapper(*args, **kwargs): print('Modified function') func(*args, **kwargs) return wrapper @myDecor def myfunc(msg): print(msg) # calling myfunc() myfunc('Hey')
true
39a9ed0ca6f8ce9095194deb21f2c685cfcb079c
mantrarush/InterviewPrep
/InterviewQuestions/SortingSearching/IntersectionArray.py
1,037
4.21875
4
""" Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? """ def intersection(nums1: [int], nums2: [int]) -> [int]: # Keys are integers from nums1 and values are the frequency of that integer nums = {} intersection = [] for num in nums1: if num in nums: nums[num] = nums[num] + 1 else: nums[num] = 1 for num in nums2: if num in nums and nums[num] > 0: nums[num] = nums[num] - 1 intersection.append(num) return intersection
true
4a81b3f14a778f7db90f588f71e7e1f49c471f50
jskim0406/Study
/1.Study/2. with computer/4.Programming/2.Python/8. Python_intermediate/p_chapter03_02.py
1,524
4.125
4
# 클래스 예제 2 # 벡터 계산 클래스 생성 # ex) (5,2) + (3,4) = (8,6) 이 되도록 # (10,3)*5 = (50,15) # max((5,10)) = 10 class Vector(): def __init__(self, *args): '''Create vector. ex) v = Vector(1,2,3,4,5) ==>> v = (1,2,3,4,5)''' self.v = args print("vector created : {}, {}".format(self.v, type(self.v))) def __repr__(self): '''Return vector information''' return self.v def __getitem__(self,key): return self.v[key] def __len__(self): return len(self.v) def __add__(self, other): '''Return element-wise operation of sum''' if type(other) != int: temp = () for i in range(len(self.v)): temp += (self.v[i] + other[i],) return temp else: temp = () for i in range(len(self.v)): temp += (self.v[i] + other,) return temp def __mul__(self, other): '''Return Hadamard Product. element-wise operation''' if type(other) != int: temp = () for i in range(len(self.v)): temp += (self.v[i] * other[i],) return temp else: temp = () for i in range(len(self.v)): temp += (self.v[i] * other,) return temp v1 = Vector(1,2,3,4,5) v2 = Vector(10,20,30,40,50) print() print(v1.__add__.__doc__) print() print(v1+v2, v1*v2, sep='\n') print() print(v1+3, v1*3, sep='\n') print()
false
6a39d9c02444a887957b2e07fb3b9144abbb6283
meniscus/AtCoder
/ARC/ARC012/A.py
269
4.25
4
day = input() if (day == "Sunday" or day == "Saturday") : print(0) elif (day == "Monday") : print(5) elif (day == "Tuesday") : print(4) elif (day == "Wednesday") : print(3) elif (day == "Thursday") : print(2) elif (day == "Friday") : print(1)
false
66da83e7687f9d598add37baee9aecf6ff44c10a
shfhm/Practice-Python
/Check Power of 2.py
226
4.40625
4
#function that can determine if an input number is a power of 2 import math def sqrtt(x): i=math.sqrt(x) if i**2==x: print('the input is power 2 of %s' %(i) ) else: print('it\'s not the power 2')
true
2e70910939fedcde1d3c98da05618a8ff871abd0
diego-ponce/code_snippets
/code_challenges/sort_stack.py
1,380
4.15625
4
def pop_until(fromstack, tostack, val): ''' pops from fromstack onto tostack until val is greater than the last value popped. Returns the count of items popped. ''' count = 0 while fromstack: if fromstack[-1] < val: return count pop_val = fromstack.pop() tostack.append(pop_val) count += 1 return count def push_until(fromstack, tostack, n): ''' pushes values from fromstack onto tostack n times ''' for _ in range(n): tostack.append(fromstack.pop()) def sort_stack(astack:list) -> list: ''' sorts elements from astack onto a tmpstack and returns the sorted tmpstack. astack is emptied of values. ''' tmpstack = [] while astack: val = astack.pop() # tmpstack is empty if not tmpstack: tmpstack.append(val) # tmpstack is ordered when appending val elif tmpstack[-1] < val: tmpstack.append(val) # tmpstack is unordered when appending val, so pop tmpstack until # the order is retained, then push popped (previously ordered) values back onto tmpstack else: depth = pop_until(tmpstack, astack, val) tmpstack.append(val) push_until(astack, tmpstack, depth) return tmpstack astack = [1,-11,0,1,2] print(sort_stack(astack))
true
ae56bc91c4fe03e9d6e2066aa43858cf2b3c63b1
houxianxu/learnToProgramCoursera
/week4/a2.py
2,929
4.34375
4
#!/usr/bin/python3.2 def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return get_length(dna1) - get_length(dna2) > 0 def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ res = 0 for i in dna: if i == nucleotide: res += 1 return res def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ res = dna1.find(dna2) if res == -1: return False else: return True def is_valid_sequence(dna): """ (str) -> bool Return True if and only if the DNA sequence is valid (that is, it contains no characters other than 'A', 'T', 'C' and 'G'). >>> is_valid_sequence('ATCGGC') True >>> is_valid_sequence('AFDATCGGC') False """ res = True for i in dna: if i not in 'AGCT': res = False break else: continue return res def insert_sequence(dna1, dna2, index): """(str, str, int) -> str Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index. >>>insert_sequence('CCGG', 'AT', 2) 'CCATGG' """ res = '' len1 = get_length(dna1) len2 = get_length(dna2) if index == 0: res = dna2 + dna1 elif index == len1: res = dna1 + dna2 else: for i in range(index): res += dna1[i] for item in dna2: res += item for i in range(index, len1): res += dna1[i] return res def get_complement(nucleotide): """ (str) -> str Return the nucleotide's complement. >>>get_complement('A') T >>>get_complement('C') G """ if nucleotide == 'A': return 'T' elif nucleotide == 'T': return 'A' elif nucleotide == 'G': return 'C' elif nucleotide == 'C': return 'G' def get_complementary_sequence(dna): """ (str) -> str Return the DNA sequence that is complementary to the given DNA sequence. >>> get_complementary_sequence('ATCG') TAGC """ res = '' for i in dna: res += get_complement(i) return res
false
a54f2d23123a452a9a4b4ed7be2e1ea6cebf4b5b
emmadeeks/CMEECourseWork
/Week2/Code/lc1.py
2,225
4.65625
5
#!/usr/bin/env python3 #Author: Emma Deeks ead19@imperial.ac.uk #Script: lc1.py #Desc: List comprehensions compared to for loops #Arguments: No input #Outputs: Three lists containing latin names, common names and mean body masses for each species of birds in a given list of birds #Date: Oct 2019 # Creates a list of bird species, common name and body mass birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) """ Uses List comprehensions to create three lists containing latin names, common names and mean body masses for each species of birds """ #List comprehension for list with latin names first_words = {w[0] for w in birds} #Comprehension that indexes the first line of the list print("The Latin names of the birds using comprehensions: \n", first_words, "\n") #List comprehension for list with common names first_words = {w[1] for w in birds} # common name is second in list print("The common names of the birds using comprehensions:\n ", first_words, "\n") #List comprehension for list with body mass first_words = {w[2] for w in birds} # The body mass is third in the list print("The body mass of the birds using comprehensions: \n", first_words, "\n") #For loop indexing a list of latin names from a list of birds first_words = set() # This is to be appended with the desired latin names, common names and body mass # This is then printed to screen after for loop has run through index of list for w in birds: first_words.add(w[0]) print("The Latin names of the birds using for loops: \n", first_words, "\n") #For loop indexing a list of common names from a list of birds first_words = set() for w in birds: first_words.add(w[1]) print("The common names of the birds using for loops: \n", first_words, "\n") #For loop indexing a list of body mass from a list of birds first_words = set() #Creates empty set that can be appened to in for loop for w in birds: first_words.add(w[2]) print("The body mass of the birds using for loops: \n", first_words, "\n")
true
3e953d2ae7128c97dcdad05b1f4dd97cbd58f77d
emmadeeks/CMEECourseWork
/Week2/Sandbox/comprehension_test.py
1,903
4.46875
4
## Finds list those taxa that are oak trees from a list of species #There is a range of 10 and i will run throough the range and print the numbers- remember it starts from 0 x = [i for i in range(10)] print(x) #Makes an empty vector (not vector LIST) called x and fils it by running through the range 10 and appending the list x = [] for i in range(10): x.append(i) print(x) #i.lower means print in lower case and so just print the list made in lower case x = [i.lower() for i in ["LIST", "COMPREHENSIONS", "ARE", "COOL"]] print(x) #Makes a list then specifies the range is x and fills it in lower case and prints it x = ["LIST", "COMPREHENSIONS", "ARE", "COOL"] for i in range(len(x)): #explicit loop x[i] = x[i].lower() print(x) #Same as above but just in a different way x = ["LIST", "COMPREHENSIONS", "ARE", "COOL"] x_new = [] for i in x: #implicit loop x_new.append(i.lower()) print(x_new) #This is a nested loop and it makes a matrix. flatten matrix i believe will just ake the matrix less 3d matrix = [[1,2,3], [4,5,6], [7,8,9]] flattened_matrix = [] for row in matrix: for n in row: flattened_matrix.append(n) print(flattened_matrix) #same just in a list comprehension matrix = [[1,2,3], [4,5,6], [7,8,9]] flattened_matrix = [n for row in matrix for n in row] print(flattened_matrix) #create a set of all the first letters in a sequence of words using a loop words = (["These", "are", "some", "words"]) first_letters = set() #creates an empty set object for w in words: first_letters.add(w[0]) #only include the first letter print(first_letters) #Letters are unordered and they need to be put in order so use a comprehension #Note this still doesnt order them just does the same thing words = (["These", "are", "some", "words"]) first_letters = set() for w in words: first_letters.add(w[0]) #adding only the first letter print(first_letters)
true
0cca2868af0d5c598552626a20bdd749e57e2364
emmadeeks/CMEECourseWork
/Week2/Code/oaks.py
1,565
4.59375
5
#!/usr/bin/env python3 #Author: Emma Deeks ead19@imperial.ac.uk #Script: oaks.py #Desc: Uses for loops and list comprehensions to find taxa that are oak trees from a list of species. #Arguments: No input #Outputs: Oak species from list #Date: Oct 2019 """ Uses for loops and list comprehensions to find taxa that are oak trees from a list of species. """ ## Finds just those taxa that are oak trees from a list of species taxa = [ 'Quercus robur', 'Fraxinus excelsior', 'Pinus sylvestris', 'Quercus cerris', 'Quercus petraea', ] #find all species that start with quercus def is_an_oak(name): """ Find all the species that start with the name quercus """ return name.lower().startswith('quercus ') ##Using for loops oaks_loops = set() #creates an empty object for species in taxa: #calls upon the taxa list if is_an_oak(species): # calls the function and if it i add the the empty set oaks_loops.add(species) print("List of oaks found in taxa: \n", oaks_loops) #fills out species ##Using list comprehensions oaks_lc = set([species for species in taxa if is_an_oak(species)]) print("List of oaks found in taxa: \n", oaks_lc) ##Get names in UPPER CASE using for loops oaks_loops = set() for species in taxa: if is_an_oak(species): oaks_loops.add(species.upper()) print("List of oaks found in taxa: \n", oaks_loops) ##Get names in UPPER CASE using list comprehensions oaks_lc = set([species.upper() for species in taxa if is_an_oak(species)]) print("List of oaks found in taxa: \n", oaks_lc)
true
d3ec3a217a17c9ab7963663f0db285dfd80945e7
carinasauter/D04
/D04_ex00.py
2,018
4.25
4
#!/usr/bin/env python # D04_ex00 # Create a program that does the following: # - creates a random integer from 1 - 25 # - asks the user to guess what the number is # - validates input is a number # - tells the user if they guess correctly # - if not: tells them too high/low # - only lets the user guess five times # - then ends the program ########################################################################## # Imports import random # Body def random_guess_game(): x = random.randint(1, 25) count = 0 while count < 5: user_input = '' while user_input == '': try: user_input = int( input("Please guess my number between 1 and 25: ")) if 1 <= user_input < x: print("Too low, you have " + str(4 - count) + " attempts left") count += 1 elif x < user_input <= 25: print("Too high, you have " + str(4 - count) + " attempts left") count += 1 elif user_input == x: print('You guessed correctly!') count = 7 else: print("That integer is not between 1 and 25.\nYou have " + str(4 - count) + " attempts left") count += 1 except: count += 1 if count == 5: print('That was not a valid input.') break else: print("That was not a valid input. Please insert an integer between 1 and 25.\nYou have " + str(5 - count) + " attempts left") if count == 5: print("Sorry, you ran out of attempts") ########################################################################## def main(): return random_guess_game() if __name__ == '__main__': main()
true
098556b0003a35c50a5631496c5d24c38a7c3e12
CODEvelopPSU/Lesson-4
/pythonTurtleGame.py
1,176
4.5
4
from turtle import * import random def main(): numSides = int(input("Enter the number of sides you want your shape to have, type a number less than 3 to exit: ")) while numSides >= 3: polygon(numSides) numSides = int(input("Enter the number of sides you want your shape to have, type a number less than 3 to exit: ")) else: print("Thank you for using the polygon generator!") def polygon(x): sideLength = 600/x colors = ["gold", "red", "blue", "green", "purple", "black", "orange"] shapeColor = random.choice(colors) borderColor = random.choice(colors) borderSize = (x % 20) + 1 makePolygon(x, sideLength, borderColor, borderSize, shapeColor) def makePolygon(sides, length, borderColor, width, fillColor): clear() angle = 360/sides shape("turtle") pencolor(borderColor) fillcolor(fillColor) pensize(width) begin_fill() while True: if sides != 0: forward(length) left(angle) sides -= 1 else: break end_fill() main()
true
d62805b6544a217f531eaf387853a7120c479d3f
ArturAssisComp/ITA
/ces22(POO)/Lista1/Question_7.py
1,115
4.125
4
''' Author: Artur Assis Alves Date : 07/04/2020 Title : Question 7 ''' import sys #Functions: def sum_of_squares (xs): ''' Returns the sum of the squares of the numbers in the list 'xs'. Input : xs -> list (list of integers) Output: result -> integer ''' result = 0 for number in xs: result += number**2 return result def test(did_pass): ''' Print the result of a test. OBS: Função retirada dos slides Python 1.pptx. ''' linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} is OK.".format(linenum) else: msg = "Test at line {0} FAILED.".format(linenum) print(msg) def test_suite(): ''' Run the suite of tests for code in this module (this file). OBS: Função retirada dos slides Python 1.pptx. ''' test(sum_of_squares([2, 3, 4]) == 29) test(sum_of_squares([ ]) == 0) test(sum_of_squares([2, -3, 4]) == 29) #Main: if __name__=='__main__': test_suite()
true
590591e904740eb57a29c07ba3cf812ac9d5e921
ArturAssisComp/ITA
/ces22(POO)/Lista1/Question_4.py
1,580
4.15625
4
''' Author: Artur Assis Alves Date : 07/04/2020 Title : Question 4 ''' import sys #Functions: def sum_up2even (List): ''' Sum all the elements in the list 'List' up to but not including the first even number (Is does not support float numbers). Input : List -> list (list of integers) Output: result -> integer or None if no number was added to result. ''' result = None for number in List: if number%2 == 0: break else: if result == None: result = number else: result += number return result def test(did_pass): ''' Print the result of a test. OBS: Função retirada dos slides Python 1.pptx. ''' linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} is OK.".format(linenum) else: msg = "Test at line {0} FAILED.".format(linenum) print(msg) def test_suite(): ''' Run the suite of tests for code in this module (this file). OBS: Função retirada dos slides Python 1.pptx. ''' test(sum_up2even([]) == None) test(sum_up2even([2]) == None) test(sum_up2even([-4]) == None) test(sum_up2even([0]) == None) test(sum_up2even([2, 3, 4, 5, 6]) == None) test(sum_up2even([1, 3, 5, 7, 9]) == 25) test(sum_up2even([27]) == 27) test(sum_up2even([27, 0]) == 27) test(sum_up2even([-3]) == -3) #Main: if __name__=='__main__': test_suite()
true
58c1e655e91256c0e0aed84e0c61f4a7818434d9
zelenyid/amis_python
/km73/Zeleniy_Dmytro/9/task1.py
303
4.15625
4
from math import sqrt # Розрахунок відстані між точками def distance(x1, y1, x2, y2): dist = sqrt((x2-x1)**2 + (y2-y1)**2) return dist x1 = int(input("x1: ")) y1 = int(input("y1: ")) x2 = int(input("x2: ")) y2 = int(input("y2: ")) print(distance(x1, y1, x2, y2))
false
b74253bc3566b35a29767cc23ceb5254cb303441
MailyRa/calculator_2
/calculator.py
1,093
4.125
4
"""CLI application for a prefix-notation calculator.""" from arithmetic import (add, subtract, multiply, divide, square, cube, power, mod, ) print("Welcome to Calculator") #ask the user about the equation def calculator_2(): user_input = (input(" Type your equation ")) num = user_input.split(' ') #if the first letter is a "q" then I kno they want to quit if num == ["q"]: print("Thank you, have a good day") #the rest of the other functions if num[0] == "+": return int(num[1]) + int(num[2]) elif num[0] == "-": return int(num[1]) - int(num[2]) elif num[0] == "*": return int(num[1]) * int(num[2]) elif num[0] == "/": return int(num[1]) / int(num[2]) elif num[0] == "square": return int(num[1]) * int(num[1]) elif num[0] == "cube": return int(num[1]) * int(num[1]) * int(num[1]) elif num[0] == "pow": return int(num[1]) ** int(num[2]) elif num[0] == "mod": return int(num[1]) % int(num[2]) print(calculator_2())
true
6a9febac0dcf6886c3337991eb7c5dde84ee281b
pdhawal22443/GeeksForGeeks
/GreaterNumberWithSameSetsOFDigit.py
2,055
4.15625
4
'''Find next greater number with same set of digits Given a number n, find the smallest number that has same set of digits as n and is greater than n. If n is the greatest possible number with its set of digits, then print “not possible”. Examples: For simplicity of implementation, we have considered input number as a string. Input: n = "218765" Output: "251678" Input: n = "1234" Output: "1243" Input: n = "4321" Output: "Not Possible" Input: n = "534976" Output: "536479" Algo :: Following is the algorithm for finding the next greater number. I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”. II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6. III) Swap the above found two digits, we get 536974 in above example. IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976. ''' import pdb #ex - 534976 lst = [5,3,4,9,7,6] def arrange(lst): flag = 0 for i in range(len(lst)-1,0,-1): if lst[i] > lst[i-1]: flag = 1 #this is to check that such number found break if flag == 0: print("Not Possible") exit(0) x = lst[i-1] #step-1 of algo #algo step2 temp = lst[i] small = i for k in range(i+1,len(lst)): if lst[k-1] > x and lst[small] > lst[k]: small = k #step 3 lst[i-1],lst[small] = lst[small],lst[i-1] pdb.set_trace() res = lst[0:i] + sorted(lst[i:]) print(''.join(map(str,res))) arrange(lst)
true
52fc107624d46f57e2b99394196053e444eb7136
PawelKapusta/Python-University_Classes
/Lab8/task4.py
387
4.15625
4
import math def area(a, b, c): if not a + b >= c and a + c >= b and b + c >= a: raise ValueError('Not valid triangle check lengths of the sides') d = (a + b + c) / 2 return math.sqrt(d * (d - a) * (d - b) * (d - c)) print("Area of triangle with a = 3, b = 4, c = 5 equals = ", area(3, 4, 5)) print("Area of triangle with a = 15, b = 4, c = 50 equals = ", area(15, 4, 50))
true
849402be8f503d46883dc5e8238821566b33598b
Rajatku301999mar/Rock_Paper_Scissor_Game-Python
/Rock_paper_scissor.py
2,350
4.21875
4
import random comp_wins=0 player_wins=0 def Choose_Option(): playerinput = input("What will you choose Rock, Paper or Scissor: ") if playerinput in ["Rock","rock", "r","R","ROCK"]: playerinput="r" elif playerinput in ["Paper","paper", "p","P","PAPER"]: playerinput="p" elif playerinput in ["Scissor","scissor", "s","S","SCISSOR"]: playerinput="s" else: print("I dont understand, try again.") Choose_Option() return playerinput def Computer_Option(): computerinput=random.randint(1,3) if computerinput==1: computerinput="r" elif computerinput==2: computerinput="p" else: computerinput="s" return computerinput while True: print("") playerinput=Choose_Option() computerinput=Computer_Option() print("") if playerinput=="r": if computerinput=="r": print("You choose Rock, Computer choose Rock, Match Tied...") elif computerinput=="p": print("You choose Rock, Computer choose Paper, You Lose...") comp_wins+=1 elif computerinput=="s": print("You choose Rock, Computer choose Scissor, You Win...") player_wins+=1 elif playerinput=="p": if computerinput=="r": print("You choose Paper, Computer choose Rock, You Win...") player_wins+=1 elif computerinput=="p": print("You choose Paper, Computer choose Paper, Match Tied...") elif computerinput=="s": print("You choose Paper, Computer choose Scissor, You Lose...") comp_wins+=1 elif playerinput=="s": if computerinput=="r": print("You choose Scissor, Computer choose Rock, You Lose...") comp_wins+=1 elif computerinput=="p": print("You choose Scissor, Computer choose Paper, You Win...") player_wins+=1 elif computerinput=="s": print("You choose Scissor, Computer choose Scissor, Match Tied...") print("") print("Player wins: "+ str(player_wins)) print("Computer wins: " + str(comp_wins)) print("") playerinput=input("Do you want to play again? (y,n)") if playerinput in ["Y","y","Yes","yes"]: pass elif playerinput in ["N","n","No","no"]: break else: break
true
f9ac9c75d756a1548225c139265206ffb70e3bfc
manzeelaferdows/week3_homework
/data_types.py
1,481
4.1875
4
str = 'Norwegian Blue', "Mr Khan's Bike" list = ['cheddar', ['Camembert', 'Brie'], 'Stilton', 'Brie', 'Brie'] tuples = (47, 'spam', 'Major', 638, 'Ovine Aviation') tuples2 = (36, 29, 63) set = {'cheeseburger', 'icecream', 'chicken nuggets'} dict = {'Totness': 'Barber', 'BritishColumbia': 'Lumberjack'} print(len(list)) print(min(tuples2)) print(max(tuples2)) print(sum(tuples2)) a = 'Mash Potato' b = 'Gravy' print(a, b) a, b = b, a print(a, b) Gouda, Edam, Caithness = range(3) print(range) Belgium = 'Belgium,10445852,Brussels,737966,Europe,1830,Euro,Catholicism,Dutch,French,German' Belgium2 = Belgium*2 print(Belgium2) thing = 'Hello' print(type(thing)) thing = ('Hello',) print(type(thing)) list[:0] = ['Newham', 'Hackney'] print(list) list += ['Southwark', 'Barking'] print(list) list.extend(['Dagenham', 'Croydon']) print(list) list.insert(5, 'Tottenham') print(list) list[5:5] = ['Edmonton'] print(list) list2 = list.pop(1) print(list2) list3 = list.pop(3) print('the two items we removed:', list2, 'and', list3, "Now the list is shorter:", list) list.remove('Edmonton') print(list) print(list.count('Brie')) print(list.index('Brie')) list.reverse() print(list) set1 = {5, 6, 7, 8, 9} set2 = {10, 11, 12, 13} print(set1) print(set2) set1.remove(9) print(set1) set2.add(9) print(set2) print(len(set2)) list4 = [1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5] list4b = ["cat", "dog", "cat", "dog"] list4_set = set(list4) list4 = list(list4_set) print(list4)
false
866df365ca6ec790f67224b2208e90eca5eeb811
vaamarnath/amarnath.github.io
/content/2011/10/multiple.py
665
4.125
4
#!/usr/bin/python import sys def checkMultiple(number) : digits = {"0":0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":0, "7":0, "8":0, "9":0} while number != 0 : digit = number % 10 number = number / 10 digits[str(digit)] += 1 distinct = 0 for i in range(0, 10) : if digits[str(i)] != 0 : distinct += 1 return distinct number = int(sys.argv[1]) counter = 1 while True : multiple = number * counter if checkMultiple(multiple) == 1 : print "Found the multiple with least number of distinct digits" print multiple, counter break counter += 1 print multiple,
true
e1289e9769ad313bc415a66d5e5600e5007fec90
dhansolo/R-P-S
/main.py
684
4.21875
4
from random import randint player = raw_input('rock (r), paper (p), or scissors (s)? ') while player != 'r' and player != 'p' and player != 's': player = raw_input('Must choose rock (r), paper (p), or scissors (s) ') # end='' tells print to print an extra space instead of a line in python 3 and above computer = randint(1, 3) if computer == 1: computer = 'r' elif computer == 2: computer = 'p' else: computer = 's' print(player, 'vs', computer) if(player == computer): print('TIE!') elif(player == 'r' and computer == 's' or player == 's' and computer == 'p' or player == 'p' and computer == 'r'): print('PLAYER WINS!') else: print('COMPUTER WINS!')
false
7cee4713aa67c45851d8ac66e6900c25c95ccef1
UCMHSProgramming16-17/final-project-shefalidahiya
/day05/ifstatement2.py
366
4.375
4
# Create a program that prints whether a name # is long name = "Shefali" # See if the length of the name counts as long if len(name) > 8: # If the name is long, say so print("That's a long name") # If the name is moderate elif len(name) < 8: print("That's a moderate name") # If the name is short else len(name) < 5: print("That's a short name")
true
1a9dea57415668bf56fd5e0b0193952a1af49e27
freaking2012/coding_recipes
/Python/LearnBasics/HashPattern2.py
365
4.3125
4
''' This program takes input a even number n. Then it prints n line in the following pattern For n = 8 ## #### ###### ######## ######## ###### #### ## ''' n=input("Enter number of lines in patter (should be even): ") for i in range(1,n/2+1): print (' ' * (n/2-i)) + ('##' * i) for i in range(1,n/2+1): print (' ' * (i-1)) + ('##' * (n/2-i+1))
true
4ca634a62c46930073c67fbb01bea13796de8edb
leoP0/OS1
/Small Python/mypython.py
1,376
4.1875
4
#Python Exploration #CS344 #Edgar Perez #TO RUN IT JUST DO: 'python mypython.py' (whitout the ' ') #Modules import random import string import os import io #function that generates random lowercase leters given a range def random_char(y): return ''.join(random.choice(string.ascii_lowercase) for x in range(y)) #create files if they dont exist file1 = open("uno", "w+") #uno means one lol file2 = open("dos", "w+") #dos means two file3 = open("tres", "w+")#tres means three #after creat the files write the random letters plus "\n" character at the end # There is probaly a better way but this is what I did: file1.write((random_char(10)) + "\n") file2.write((random_char(10)) + "\n") file3.write((random_char(10)) + "\n") #close files after being read file1.close() file2.close() file3.close() # Read files created file1 = open("uno", "r") #uno means one lol file2 = open("dos", "r") #dos means two file3 = open("tres", "r")#tres means three #Display to stdout only 10 characters print file1.read(10) print file2.read(10) print file3.read(10) #close files after being read file1.close() file2.close() file3.close() # Generate first integer from 1 to 42 randomN1 = random.randint(1,42) print randomN1 # Generate first integer from 1 to 42 randomN2 = random.randint(1,42) print randomN2 # Display the result of (random number1 * random number2) print (randomN1*randomN2)
true
5548df9c3f3e31ffce2cdb3e0f6fda197bf7ab72
tazdaboss/python_basic
/datatype_learn/number_operation.py
226
4.1875
4
num1=int(input("enter num1:\t")) num2=int(input("enter num2:\t")) print("add",num1+num2) print("subtract",num1*num2) print("divide",num1/num2) print("remainder",num1%num2) print("quotient",num1//num2) print("power",num1**num2)
false
b6f5c5dc5b1c4703650b0e12ba82517d237c92ea
SanjayMarreddi/Open-CV
/Object_Detection/1.Simple_Thresholding.py
2,452
4.375
4
# Now we are focused on extracting features and objects from images. An object is the focus of our processing. It's the thing that we actually want to get, to do further work. In order to get the object out of an image, we need to go through a process called segmentation. # Segmentation can be done through a variety of different ways but the typical output is a binary image. A binary image is something that has values of zero or one. Essentially, a one indicates the piece of the image that we want to use and a zero is everything else. # Binary images are a key component of many image processing algorithms. These are pure, non alias black and white images, the results of extracting out only what you need. They act as a mask for the area of the sourced image. After creating a binary image from the source, you do a lot when it comes to image processing. # One of the typical ways to get a binary image, is to use what's called the thresholding algorithm. This is a type of segmentation that does a look at the values of the sourced image and a comparison against one's central value to decide whether a single pixel or group of pixels should have values zero or one. import numpy as np import cv2 # "0" tells opencv to load the GRAY IMAGE bw = cv2.imread('detect_blob.png', 0) height, width = bw.shape[0:2] cv2.imshow("Original BW",bw) # Now the goal is to ample a straightforward thresholding method to extract the objects from an image. We can do that by assigning all the objects a value of 1 and everything else a value of 0. binary = np.zeros([height,width,1],'uint8') # One channel binary Image thresh = 85 # Every pixel is compared against this for row in range(0,height): for col in range(0, width): if bw[row][col]>thresh: binary[row][col]=255 # I just said that a binary image is consisting of either 0s or 1s, but in this case we want to display the image in the user interface, and because of OpenCV's GUI requirements, we want to actually show a 255 or 0 value-based image. That way, the binary image will appear white where we actually want our objects. cv2.imshow("Slow Binary",binary) # Slower method due to two for Loops # Faster Method using OPENCV builtins. # Refer Documentation to explore More ret, thresh = cv2.threshold(bw,thresh,255,cv2.THRESH_BINARY) cv2.imshow("CV Threshold",thresh) # This is a Simple example of IMAGE SEGMENTATION using Thresholding ! cv2.waitKey(0) cv2.destroyAllWindows()
true
dddf7daa3fd9569dbeb61fdba7f39f070aa4be39
Ironkey/ex-python-automatic
/Chapter 01-02/Hello World.py
597
4.21875
4
# This program says hello and asks for my name. print('Hello wolrd!') print ('What is your name?') # ask for their name myName = input() print('It is good to meet you, ' + myName) print('The Length of your name is:') print(len(myName)) print('What is your age?') # ask for their age myAge = input() print('You will be ' + str(int(myAge) +1) + ' in a year.') print('호구야 실수값좀 입력해라: ') myround = float(input()) if str(type(myround)) == "<class 'float'>" : print('니가 입력한 값을 반올림해주마 :' + str(round(myround))) else: print('실수값 모르냐')
true
4c69bf913b87c5c3373368d83464ecd9e49e9184
mennonite/Python-Automation
/Chapter 8 -- Reading and Writing Files/Practice Projects/madlibs_Regex.py
920
4.25
4
#! python3 # madlibs_Regex.py - opens and reads a text file and lets the user input their own words (solved using REGEX) import re # open text file madlibFile = open('.\\Chapter 8 -- Reading and Writing Files\\Practice Projects\\test.txt') # save the content of the file into a variable content = madlibFile.read() madlibFile.close() # build a regex to identify replaceable words madlibsRegex = re.compile(r'(ADJECTIVE|NOUN|ADVERB|VERB)') matches = madlibsRegex.findall(content) # for each match, prompt the user to replace it for match in matches: userWord = input('Gimme %s %s:\n' % ('an' if match.startswith('A') else 'a', match.lower())) content = content.replace(match, userWord, 1) print(content) # the resulting text is saved to a new file madlibAnswers = open('.\\Chapter 8 -- Reading and Writing Files\\Practice Projects\\test-answer.txt', 'w') madlibAnswers.write(content) madlibAnswers.close()
true
cb5a0fa4c5e15ece58b25f8a0fedb9fb56f26c5f
rohitprofessional/test
/f_string.py
386
4.4375
4
letter = "Hey my name is {1} and I am from {0}" country = "India" name = "Rohit" print(letter.format(country, name)) print(f"Hey my name is {name} and I am from {country}") print(f"We use f-strings like this: Hey my name is {{name}} and I am from {{country}}") price = 49.09999 txt = f"For only {price:.2f} dollars!" print(txt) # print(txt.format()) print(type(f"{2 * 30}"))
true
f9d5c0e1ab4ec959bb7988e185c83b2ba49a23a5
rohitprofessional/test
/PRACTICE/stop_watch.py
534
4.125
4
#---------------STOP WATCH-------- import time time_limit = int(input("Enter the stopwatch time.: ")) # hours = int(time_limit/3600) # minutes = int(time_limit/60) % 60 # seconds = (time_limit) % 60 # print(hours,minutes,seconds) for x in range(time_limit,0,-1): seconds = (x) % 60 minutes = int(x/60) % 60 hours = int(x/3600) time.sleep(1) # it'll delay o/p by given sec print(f"{hours:02}:{minutes:02}:{seconds:02}") # print(minutes,"minutes left",":",seconds,"seconds left")
true
608257fd5528026be5797f7ca712d9328ca7382b
rohitprofessional/test
/CHAPTER 01/localVSglobal_variable.py
1,353
4.5
4
# It is not advisable to update or change the global variable value within in a local block of code. As it can lead to complexity # in the program. But python provides a global keyword to do so if you want to. # Although it is also not advisable to use global variable into a local function. It is a maintainable programming practice. def local(m,n): # global x # changing global variable value by accessing it # x = 30 # using the word 'global' m = 5 # local variable and can be accessible within the block only n = 8 # after the block ends variable scope/use out of block also ends print("\ninside the function:") print(f"\n\t3.local to func variable x: {m}, address{id(m)}") print(f"\n\t2.local to func variable y: {n}, address{id(n)}") # print(f"2. local variable x: {x}, address{id(x)}") # local variable # print(f"2. local variable y: {y}, address{id(y)}") return print("\t\tmain-->>") x = 10 # global variable and can be use anywhere in prog y = 20 # global variable and can be use anywhere in prog print("Variables before func call:") print(f"\n1.global variabel x: {x}, address{id(x)}") print(f"\n2.global variabel y: {y}, address{id(y)}") local(x,y) print(f"\n5.global variable x: {x}, address{id(x)}") print(f"\n6.global variable : {y}, address{id(y)}")
true
e49eb95627c1f9262aad83447236cc085a6f5afd
rohitprofessional/test
/CHAPTER 07/intro to for loops.py
1,151
4.375
4
# -------------------- FOR LOOP UNDERSTANDING ------------------------------- '''So here we range is a function w/c helps compiler to run the for loop. Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).''' print("-----------------------------FOR LOOP-------------------------------") print("Table of 2") # By default 0 , n , 1 -->> If we pass only one value, ie., n. for n in range(1,11,1): # (Initialization, Condition, Increament) print("1 *", n ," = ", n*2) #------------------------- REVERSE FOR LOOP ------------------------------ print("---------------------------REVERSE FOR LOOP---------------------------------") print("Revrse table of 2") for n in range(10,0,-1): print("1 *", n ," = ", n*2) print("------------------------------------------------------------")
true
37940d1160cc5a78595a58676589eca91d3d7fdc
AlanaMina/CodeInPlace2020
/Assignment1/TripleKarel.py
1,268
4.28125
4
from karel.stanfordkarel import * """ File: TripleKarel.py -------------------- When you finish writing this file, TripleKarel should be able to paint the exterior of three buildings in a given world, as described in the Assignment 1 handout. You should make sure that your program works for all of the Triple sample worlds supplied in the starter folder. """ def main(): # Pre-condition: Three building with white walls # Post-condition: Three buildings with painted walls for i in range(3): paint_building() turn_right() turn_left() # Pre-condition: Karel is facing certain point # Post-condition: Karel will turn three times anticlockwise the initial point def turn_right(): turn_left() turn_left() turn_left() # Pre-condition: One of the buildings has white walls # Post-condition: One of the buildings gets all its walls painted def paint_building(): for i in range(2): paint_wall() turn_left() move() paint_wall() # Pre-condition: A wall is white # Post-condition: The wall is painted def paint_wall(): while left_is_blocked(): put_beeper() move() # There is no need to edit code beyond this point if __name__ == "__main__": run_karel_program()
true
3da0242e36ee059b8471559ae4491a435b90e234
AlanaMina/CodeInPlace2020
/Assignment5/word_guess.py
2,881
4.1875
4
""" File: word_guess.py ------------------- Fill in this comment. """ import random LEXICON_FILE = "Lexicon.txt" # File to read word list from INITIAL_GUESSES = 8 # Initial number of guesses player starts with def play_game(secret_word): """ Add your code (remember to delete the "pass" below) """ nro = INITIAL_GUESSES guess = "" aux = [] for i in range(len(secret_word)): guess += "-" for i in range(len(secret_word)): aux.append("-") while ("-" in guess) and (nro > 0): print("The word now looks like this: " + str(guess)) print("You have " + str(nro) + " guesses left") letter = input("Type a single letter here, then press enter: ") if len(letter) != 1: print("Guess should only be a single character.") else: letter = letter.upper() if letter in secret_word: print("That guess is correct") res = [] for idx, val in enumerate(secret_word): if val in letter: res.append(idx) for j in range(len(guess)): aux[j] = guess[j] if len(res) > 1: for m in range(len(res)): aux[res[m]] = str(letter) else: i = secret_word.index(letter) aux[i] = str(letter) guess = "" for n in range(len(aux)): guess += aux[n] else: print("There are no " + str(letter) + "'s in the word") nro -= 1 if nro == 0: print("Sorry, you lost. The secret word was: " + str(secret_word)) elif "-" not in guess: print("Congratulations, the word is: " + str(secret_word)) def get_word(): """ This function returns a secret word that the player is trying to guess in the game. This function initially has a very small list of words that it can select from to make it easier for you to write and debug the main game playing program. In Part II of writing this program, you will re-implement this function to select a word from a much larger list by reading a list of words from the file specified by the constant LEXICON_FILE. """ aux = [] with open(LEXICON_FILE) as file: for line in file: line = line.strip() aux.append(line) index = random.randrange(122000) return str(aux[index]) def main(): """ To play the game, we first select the secret word for the player to guess and then play the game using that secret word. """ secret_word = get_word() play_game(secret_word) # This provided line is required at the end of a Python file # to call the main() function. if __name__ == "__main__": main()
true
6033405dc1913c086c43a57b8ed06e70a481a8c1
mrahmed0116/Practise1
/sortbasedonvalues.py
429
4.28125
4
''' Sort dictionary based on keys ''' dict1= {'x':4,'y':3,'z':2,'a':1,'b':1, 'c':0} s1 = sorted(dict1.keys()) print(s1) output={} for s in s1: for i in dict1: if i == s: output[i] = dict1[i] print(output) ''' Sort dictionary based on values ''' s2 = sorted(dict1.values()) print(s2) output1={} for j in s2: for i in dict1: if j == dict1[i]: output1[i] = dict1[i] print(output1)
false
6ed8de9512fcf7f26e356d1e8def736dfe7e5051
keerthz/luminardjango
/Luminarpython/languagefundamentals/secondlargest.py
353
4.1875
4
num1=int(input("enter num1")) num2=int(input("enter num2")) num3=int(input("enter num3")) if((num2>num1) & (num1>num3)): print("num1 is largest",num1) elif((num3>num2) & (num2>num1)): print("num2 is largest",num2) elif((num1>num3) & (num3>num2)): print("num3 is largest",num3) elif((num1==num2) & (num2==num3)): print("they are equall")
false
4f06365db3bb2fdfa5e6c62e722e03f1ca916a7b
twillis209/algorithmsAndDataStructures
/arraySearchAndSort/insertionSort/insertionSort.py
422
4.125
4
def insertionSort(lst): """ Executes insertion sort on input. Parameters ---------- lst : list List to sort. Returns ------- List. """ if not lst: return lst sortedLst = lst[:] i = 1 while i < len(sortedLst): j = i - 1 while j >= 0 and sortedLst[j] > sortedLst[j+1]: temp = sortedLst[j] sortedLst[j] = sortedLst[j+1] sortedLst[j+1] = temp j -= 1 i +=1 return sortedLst
true
18290f2b984ca71bdbc4c147ec052ba17e246ad0
twillis209/algorithmsAndDataStructures
/arraySearchAndSort/timsort/timsort.py
1,029
4.25
4
import pythonCode.algorithmsAndDataStructures.arraySearchAndSort.insertionSort as insertionSort def timsort(): pass def reverseDescendingRuns(lst): """ Reverses order of descending runs in list. Modifies list in place. Parameters --------- lst : list List to sort. Returns ------- List. """ runStack = getRunStack(lst) while runStack: start, stop = runStack.pop() lst = reverseSubsequence(lst, start, stop) return lst def reverseSubsequence(lst, start, stop): """ """ if start >= stop: return lst else: lst[start], lst[stop] = lst[stop], lst[start] return reverseSubsequence(lst, start+1,stop-1) def getRunStack(lst): """ Identifies all runs of descending elements. Parameters ---------- lst : list List to sort. Returns ------- List. """ runStack = [] i = 0 while i < len(lst)-1: # Descending if lst[i] > lst[i+1]: j = i+1 while j < len(lst)-1 and lst[j] > lst[j+1]: j += 1 runStack.append((i,j)) i = j+1 else: i += 1 return runStack
true
227ffd15cf6fd13ac446c356d96c0761e1932f4d
ruteshr/python
/string_palindraome.py
243
4.15625
4
#String is Palindrome string=list(str(input("enter a String :"))) a="" for i in string: a=i+a if("".join(string)==a): print('{} is palindrome'.format("".join(string)) ) else: print('{} is not palindrome'.format("".join(string)) )
false
df296049dd2cd2d136f15afdf3d8f1ebec49871d
wulianer/LeetCode_Solution
/062_Unique_Paths.py
902
4.25
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 3 x 7 grid. How many possible unique paths are there? Note: m and n will be at most 100. """ class Solution(object): memo = {} def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if (m, n) in self.memo: return self.memo[(m, n)] if m == 1 or n == 1: self.memo[(m, n)] = 1 return 1 res = self.uniquePaths(m-1, n) + self.uniquePaths(m, n-1) self.memo[(m, n)] = res return res s = Solution() print(s.uniquePaths(100, 100))
true
fb10a2f3e98da33e6f5cbbe1f1d08f41dc452855
vincenttchang90/think-python
/chapter_1/chapter_1_exercises.py
1,190
4.375
4
#chapter 1 exercises #1-1 # In a print statement, what happens if you leave out one of the parentheses, or both? ## print 'hello') or print('hello' return errors # If you are trying to print a string, what happens if you leave out one of the quotation marks, or both? ## print('hello) or print(hello') return errors while print(hello) says hello is not defined #You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2? ## 2++2 returns 4, +1+2 returns 3 so it seems you can specify a number is positive with a + # In math notation, leading zeros are okay, as in 02. What happens if you try this in Python? ## 2+02 returns an invalid token error # What happens if you have two value with no operator between them? ## returns invalid syntax #1-2 # How many seconds are there in 42 minutes 42 seconds? ## 42*60+42 = 2562 # How many miles are there in 10 kilometers? Hint: there are 1.61 kilometeres in a mile. ## 10/1.61 = 6.2 miles # If you run a 10 kilometer race in 42 minutes 52 seconds, what is your average pace? What is your average speed in miles per hour? ## 6:52 minutes per mile. 8.73 miles per hour
true
526886cff12e987b705d2443cd0bc1741a552f36
bharatanand/B.Tech-CSE-Y2
/applied-statistics/lab/experiment-3/version1.py
955
4.28125
4
# Code by Desh Iyer # TODO # [X] - Generate a random sample with mean = 5, std. dev. = 2. # [X] - Plot the distribution. # [X] - Give the summary statistics import numpy as np import matplotlib.pyplot as plt import random # Input number of samples numberSamples = int(input("Enter number of samples in the sample list: ")) # Generate sample list sampleList = [random.normalvariate(5, 2) for x in range(numberSamples)] # Printing details print('\nGenerated sample list containing {} elements: '.format(numberSamples)) print(sampleList) print('\n\nCalculated Mean = {:.3f}\nRounded Calculated Mean = {}\n\nCalculated Std. Deviation = {:.3f}\nRounded Calculated Std. Deviation = {}'.format( np.mean(sampleList), round(np.mean(sampleList)), np.std(sampleList), round(np.std(sampleList)) ) ) plt.hist(sampleList) plt.show() # Reference: # https://stackoverflow.com/questions/51515423/generate-sample-data-with-an-exact-mean-and-standard-deviation
true
c5d76587c717609f3a2f3da3a9136f92b3fee367
bmgarness/school_projects
/lab2_bmg74.py
755
4.125
4
seconds = int(input('Enter number of seconds to convert: ')) output = '{} day(s), {} hour(s), {} minute(s), and {} second(s).' secs_in_min = 60 secs_in_hour = secs_in_min * 60 # 60 minutes per hour secs_in_day = secs_in_hour * 24 # 24 hours per day days = 0 hours = 0 minutes = 0 if seconds >= secs_in_day: days = seconds // secs_in_day # Interger Division seconds = seconds % secs_in_day # Remainder Divsion if seconds >= secs_in_hour: hours = seconds // secs_in_hour # Interger Divsion seconds = seconds % secs_in_hour # Remainder Divsion if seconds >= secs_in_min: minutes = seconds //secs_in_min # Interger Divsion seconds = seconds % secs_in_min # Remainder Divsion print(output. format(days, hours, minutes, seconds))
true
ec32d18f39290dc135c190a49764ae585be27ccd
ayeshaghoshal/learn-python-the-hard-way
/ex14.py
1,252
4.5
4
# -*- coding: utf-8 -*- print "EXERCISE 14 - Prompting and Passing" # Using the 'argv' and 'raw_input' commands together to ask the user something specific # 'sys' module to import the argument from from sys import argv # define the number of arguments that need to be defined on the command line script, user_name = argv # instead of using raw_data in the previous formats, this is a new way. # Defines what character will show up when a raw input is required by the user prompt = '@ ' # print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name # the following line defines that a prompt is required by the user likes = raw_input(prompt) print "Where do you live %s?" % user_name lives = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) # Use of triple brackets and % command together to combine string and raw input data # since this line of code comes after 'likes', 'lives' and 'computer', we know what value to insert print """ Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)
true
8c787b221b005f2f997f7d927a008d3ff9fa1514
ayeshaghoshal/learn-python-the-hard-way
/ex19.py
2,520
4.40625
4
# -*- coding: utf-8 -*- print "EXERCISE 19 - Functions and Variables" # defining the function that commands the following strings to be printed out # there are 2 parameters that have to be defined in brackets def cheese_and_crackers(cheese_count, boxes_of_crackers): # use of the parameters is the same method as writing string and designating values to it print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man, that's enough for a party!" print "Get a blanket.\n" # a new method of displaying the function directly by designating it values print "We can just give the function numbers directly:" # the following function will promth the command to print the stated 4 sentences above cheese_and_crackers(20,30) # another method of printing the same function print "OR, we can use variables from our script:" # designate a value to new variables amt_of_cheese = 10 amt_of_crackers = 30 # the new variables will replace the old parameters to state the defined values right above cheese_and_crackers(amt_of_cheese,amt_of_crackers) # use just numbers to define the two parameters inside the defined function print "We can even do math inside too:" cheese_and_crackers(20 + 25, 48 + 50) # Showcases the use of both variables and math to display the defined function # as long as there are only 2 paramenters defined within the brackets!!! print "And we can combine the two, variables and math:" cheese_and_crackers(amt_of_cheese + 20, amt_of_crackers + 450) #STUDY DRILLS - NEW FUNCTION! def animals_on_farm(cows, chickens, sheep): print "Can you spot %d cows?" % cows print "I bet you won't be able to identify %d red chickens!" % chickens print "Did you sheer all %d sheep this season?" % sheep print "I hope so! otherwise they will all look like cotton balls! HAHAHA\n" animals_on_farm(10, 4, 23) animals_on_farm(3 + 4, 51 + 1, 2 + 7) a = 20 b = 14 c = 24 # can replace the name of parameters inside the function () animals_on_farm(a, b, c) animals_on_farm(a + 2, b*2, c - 10) print "We can assign the function to a variable and simply call it by its new variable name" poo = animals_on_farm poo(2, 4, 8) print "We can pass a function as arguments" print "Now ask the user for the number of cows, chickens and sheep! - brackets within brackets" animals_on_farm(int(raw_input("How many cows?")), int(raw_input("How many chickens?")), int(raw_input("How many sheep?)")))
true
cce19d5079460040e6174142d487e9fac7a22adf
jamesfeng1994/ORIE5270
/HW2/tree/tree_print.py
2,454
4.15625
4
class Tree(object): def __init__(self, root): self.root = root def get_depth(self, current, n): """ This function is to get the depth of the tree using recursion parameters: current: current tree node n: current level of the tree return: the depth of the tree """ if current is not None: return max(self.get_depth(current.left, n + 1), self.get_depth(current.right, n + 1)) else: return n def traverse_tree(self, current, n, tree_list): """ This function is to traverse the tree and store keys of tree nodes parameters: current: current tree node n: current tree level tree_list: a list storing keys of tree nodes (from parents to kids) return: a list storing all nodes' keys (from root to leaves) """ depth = self.get_depth(self.root, 0) if n == 0: tree_list = [[] for i in range(depth)] tree_list[n].append(current.value) if current.left is not None: tree_list = self.traverse_tree(current.left, n + 1, tree_list) elif n < depth - 1: tree_list[n + 1].append(None) if current.right is not None: tree_list = self.traverse_tree(current.right, n + 1, tree_list) elif n < depth - 1: tree_list[n + 1].append(None) return tree_list def print_tree(self): """ This function is to print the tree by returning a matrix return: a matrix representing the tree """ tree_list = self.traverse_tree(self.root, 0, []) depth = self.get_depth(self.root, 0) for i in range(depth - 1): for j in range(len(tree_list[i])): if tree_list[i][j] is None: tree_list[i + 1].insert(2 * j, None) tree_list[i + 1].insert(2 * j + 1, None) tree_matrix = [['|' for i in range(2 ** depth - 1)] for j in range(depth)] for i in range(depth): for j in range(len(tree_list[i])): if tree_list[i][j] is not None: tree_matrix[i][2 ** (depth - i - 1) - 1 + j * 2 ** (depth - i)] = tree_list[i][j] return tree_matrix class Node(object): def __init__(self, value, left, right): self.value = value self.left = left self.right = right
true
180595fd0f78376e8b9d3da6af980876a743fcda
Vandeilsonln/Python_Automate_Boring_Stuff_Exercises
/Chapter-9_Organizing-Files/selective_copy.py
1,268
4.125
4
#! python3 # selective_copy.py - Once given a folder path, the program will walk through the folder tree # and will copy a specific type of file (e.g. .txt or .pdf). They will be copied to a new folder. import os, shutil def copy_files(folderPath, destinyPath, extension): """ Copy files from 'folderPath' to 'destinyPath' according to 'extension'. folderPath (str) - absolute path of the origin folder. destinyPath (str) - absolute path of the destination folder extension (str) - extension that will work as a filter. Only files with this extension will be copied. """ try: for currentFolder, subfolders, filenames in os.walk(folderPath): print(f'Looking for {extension} files in {currentFolder}') for file in filenames: if file.endswith(extension): print(f'\tFound file: {os.path.basename(file)}.') newFilePath = os.path.join(destinyPath, file) + extension shutil.copy(os.path.join(currentFolder, file), newFilePath) except: print('Something went wrong. Please, verify the function arguments and try again.') print('Done.') return None copy_files('C:\\delicious', 'C:\\Python_Projetos', '.zip')
true
26d42973cb952c3c2af0cddba3d4772c34b2d788
Liam-Hearty/ICS3U-Unit2-03-Python
/circumference_finder.py
493
4.625
5
#!/usr/bin/env python3 # Created by: Liam Hearty # Created on: September 2019 # This program will calculate the circumference of a determined circle radius. import constants def main(): # this function will calculate the circumference # input radius = int(input("Enter the radius of circle (mm): ")) # process circumference = constants.TAU*radius # output print("") print("circumference is {}mm".format(circumference)) if __name__ == "__main__": main()
true
94a97edaa66c9527fc133ec3c33386a5410968ba
biradarshiv/Python
/CorePython/24_String_Formatting.py
1,464
4.46875
4
""" The format() method allows you to format selected parts of a string. Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input? To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method: """ print("# First example") price = 49 txt = "The price is {} dollars" print(txt.format(price)) print("# Format the price to be displayed as a number with two decimals") price = 49 txt = "The price is {:.2f} dollars" print(txt.format(price)) print("# Multiple Values") quantity = 3 itemno = 567 price = 49 myorder = "I want {} pieces of item number {} for {:.2f} dollars." print(myorder.format(quantity, itemno, price)) print("# EOF") # You can use index numbers (a number inside the curly brackets {0}) # to be sure the values are placed in the correct placeholders quantity = 3 itemno = 567 price = 49 myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price)) age = 36 name = "John" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name)) print("# Named Indexes") # You can also use named indexes by entering a name inside the curly brackets {carname}, # but then you must use names when you pass the parameter values txt.format(carname = "Ford") myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang")) print("# EOF")
true
a36c60c380517b1e6b6d146669e9b93cf797fbcd
biradarshiv/Python
/CorePython/13_ClassObject.py
2,393
4.25
4
""" Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. """ print("# Create a class and access a property in it") class MyClass: x = 5 print(MyClass) p1 = MyClass() print(p1.x) print("# __init__() Function") print(""" All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:""") class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age) print("# Object Methods") # Objects can also contain methods. Methods in objects are functions that belong to the object. # Note: The self parameter is a reference to the current instance of the class, # and is used to access variables that belong to the class. class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() print("# The self Parameter") """The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:""" class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() print("# Delete Object Properties") class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) del p1.age # print(p1.age) # This will throw error, since this property of the object is deleted in the above line print("# Delete Objects") class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) del p1 # print(p1) # This will throw error, since this complete object is deleted in the above line print("# EOF")
true
2358ce9bd1a93f9692cff142908bde4f985fd4c5
sukiskumar/sukiskumar
/ex3.py
202
4.125
4
ch=input("enter a char:") if(ch=='A'or ch=='a'or ch=='E'or ch=='e'or ch=='I'or ch=='i'or ch=='O'or ch=='o'or ch=='U'or ch=='u'): print(ch,"its a vowel letter") else: print(ch,"its a consonent")
false
47846eb1a2b8b5db15f5f7262ae51e15973eb75b
oxfordni/python-for-everyone
/examples/lesson2/4_exercise_1.py
372
4.21875
4
# Determine the smallest number in an unordered list unordered_list = [1000, 393, 304, 40594, 235, 239, 2, 4, 5, 23095, 9235, 31] # We start by ordering the list ordered_list = sorted(unordered_list) # Then we retrieve the first element of the ordered list smallest_number = ordered_list[0] # And we print the result print(f"The smallest number is: {smallest_number}")
true
18ca47e10a0af9166e4366ca61b3a726bbc74454
callmefarad/Python_For_Newbies
/sesions/stringslice.py
756
4.53125
5
# slicing simply means returning a range of character # this is done by using indexing pattern # note when dealing with range the last number is exclusive. # i.e if we are to get the last letter of digit 10, we would have a # range of number tending to 11 where the 11th index is exclusive # declaring my variable my_string = "This is my string." # printing the whole value of the variable print(my_string[:]) # printing the word "my" from the value print("Am printing the word \"my\" from the variable using string slicing") print(my_string[8:10]) # we also use negative indexing during slicing # lets print the word "string" from the back using negative indexing print("printing the word \"string\" using negative indexing.") print(my_string[-7:-1])
true
f8ccced9d2f8bf8df346c5f5ff77a1fbc8d32954
callmefarad/Python_For_Newbies
/sesions/rangetype.py
367
4.125
4
# showing range type representation # declaring a variable name range_of_numbers range_of_numbers = range(40) # displaying the range of numbers print("Below shows the range of numbers") print(range_of_numbers) # displaying python representation of the output value print("Below show the python data type representation of the output") print(type(range_of_numbers))
true
b59e530c1b2e7d8275003cde9e1b8bce78d9b43f
callmefarad/Python_For_Newbies
/sesions/membershipin.py
536
4.3125
4
# a membership operator checks if sequence is present in an object # "in" is on of the membership operator # creating a variable named " my_list = ['orange', 'bean', 'banana', 'corn'] print("List of items: ", my_list) # creating a check variable check = "banana" # prints the result print(check in my_list) """" # creates a conditional statement if check in my_list: print(check.upper(), "is present in the list.") else: print(check, "is not present in the list.") print("************************************** ") """
true
fd0795fd1e3b86ce259b392b644d5ade274655f0
callmefarad/Python_For_Newbies
/sesions/func.py
1,652
4.15625
4
# # declaring a function # def dummy(): # print("this is a dummy print.") # # # callin the function # dummy() # # def add(): # user1 = float(input('Enter your firstnumber: ')) # user2 = float(input('Enter your secondnumber: ')) # sum = user1 + user2 # return sum # # # call the function # add() # x = 5 # def anything(): # global x # x = 6 # print(x * 2) # # anything() # print(x) # # def greet(name, message): # print(name + " " + message) # def greet(name, message): # return name + " " + message # # print(greet('ole', 'good morning')) # # def greet(name, message="goood morning"): # print( name + " " + message) # # # greet("osazie", "welcome") # def fruits(*fruitslist): # return fruitslist # # print(fruits('ola', 'sade', 'tolu')) # # using a lamdda function # square = lambda x, y: (x*x) - (y) # # print(square(4,4)) # root of an equation (b2 - 4ac)/(2a) # equation_root = lambda a,b,c : -b((b*b - 4*a*c)/(2*a)) # # a = float(input('Enter the value of a: ')) # b = float(input('Enter the value of b: ')) # c = float(input('Enter the value of c: ')) # # # call the lamda function # print(equation_root(a,b,c)) # a lambda function that performs the square of a number # square = lambda x: x * y # # user = float(input('number: ')) # print(square(user)) root = lambda a, b, c: ((a*a) + (b) -c) x = float(input('a: ')) y = float(input('b: ')) z = float(input('c: ')) # call the function print(root(x,y,z)) # a default function that performs the square of a number # def square(x): # result = x * x # return result # # u = float(input('number: ')) # print(square(u))
true
05700d145da30b014ab880e5af9be1a13d3a0a98
callmefarad/Python_For_Newbies
/sesions/passwordChecker.py
1,122
4.125
4
# a program that checks if a password is too weak, weak and very strong # defining the function def copywrite(): print("Copywrite: Ubani U. Friday") # main function special_characters = ['!', '^', '@', '#', '$', '%', '&', '*', '(', ')', '_', '+'] special_numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] upper_character = ['A','B','C','D','E','F','G','H','I','J','K','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] counter_character = 0 counter_number = 0 counter_upper = 0 list_holder = [] userinput = input("Enter your password: ") list_holder = list_holder + list(userinput) for i in range(len(userinput)): if list_holder[i] in special_characters: counter_character += 1 if list_holder[i] in special_numbers: counter_number += 1 if list_holder[i] in upper_character: counter_upper += 1 if len(userinput)<7: print("TOO WEAK, please include numbers and special characters") elif len(userinput)>=7 and counter_number>0 and counter_character>0 and counter_upper >0: print("VERY STRONG password.") else: print("The password is WEAK") copywrite()
true
67c8770308f34f234d91c330da73e5aefee2a58c
Ilis/dawson
/useless_trivia.py
585
4.125
4
# Useless trivia name = input("Hi! What's your name? ") age = input("How old are you? ") age = int(age) weight = int(input("What is your weight? ")) print() print("If Cammings write you a letter, he write", name.lower()) print("If mad Cammings write you a letter, he write", name.upper()) called = name * 5 print("Kid can call you like this:", called) seconds = age * 365 * 24 * 60 * 60 print("Your age in seconds is:", seconds) moon_weight = weight / 6 print("Your weight on the Moon is:", moon_weight) sun_weight = weight * 27.1 print("Your weight on the Sun is:", sun_weight)
true
d05ab90c27a5d8821c19b17cb48a2dafc78f35bc
GaboUCR/Mit-Introduction-to-python
/ps1/Ps1B.py
848
4.28125
4
total_cost = float(input("Enter the cost of your dream house ")) annual_salary = float(input("enter your annual salary ")) portion_saved= float(input("enter the percentage to be saved ")) semi_annual_raise = float(input("Enter the percentage of your raise")) current_savings = 0 annual_return = 0.04 total_months = 0 portion_down_payment = 0.25 months_to_get_raise = 0 while total_cost * portion_down_payment > current_savings : months_to_get_raise += 1 current_savings += current_savings*annual_return /12 current_savings += (annual_salary / 12 ) * portion_saved if (months_to_get_raise == 6 ): annual_salary = annual_salary + annual_salary*semi_annual_raise months_to_get_raise = 0 total_months += 1 print("you need to save for " , total_months , " months to be able to make a payment" )
true
8111dfc4110b25b75a6d8f4e3e583aa583a54d31
DoughyJoeyD/WorkLog2
/task.py
1,889
4.125
4
from datetime import datetime import os import time #handy script to clean the screen/make the program look nice def clearscreen(): os.system('cls' if os.name == 'nt' else 'clear') #how each task is constructed #name #date of task #time taken #extra notes class Task(): def __init__(self): pass #asks the user for a task name def get_task_name(self): clearscreen() name = input("Task Name: ") if name.upper != "BACK": self.name = name.upper() #asks the user for a task time def get_time(self): clearscreen() self.time = False while self.time == False: try: time = input('How long was the task?(Only Enter Min): ') self.time = str(int(time)) except ValueError: print('Thats not a number!') #asks the user for extra notes def get_remarks(self): clearscreen() extra = input("Additional Notes? ").upper() self.extra = extra #asks the user for a date in MM/DD/YYYY Format def get_date(self): clearscreen() self.date = False while self.date == False: try: date = input("Please enter the date of task(MM/DD/YYYY): ") self.date = datetime.strptime(date, '%m/%d/%Y') except ValueError: clearscreen() print('Oops, Please Enter In Month(08), Day(04), Year(1990) Format!') time.sleep(2) #A really clean way of printing each task all at once def taskprinter(self): print("---------------------") print('Task Name: ' + self.name) print('Task Date: ' + self.date.strftime('%m/%d/%Y')) print('Time Taken: ' + self.time + " Minutes") print('Extra: ' + self.extra) print("---------------------")
true
ae9a97b3fb40b8285182bb65d435f836de70ada6
SuryaNMenon/Python
/Functions/timeAndCalendar.py
543
4.21875
4
import calendar,time def localTime(): localtime = time.asctime(time.localtime(time.time())) print(f"Current local time is {localtime}") def displayCalendar(): c = calendar.month(int(input("Enter year: ")),int(input("Enter month: "))) print("The calendar is:\n",c) while(1): choice = int(input("Menu\n1)Show current local time\n2)Show calendar for a month\n3)Exit\nEnter your choice: ")) if choice ==1: localTime() elif choice == 2: displayCalendar() elif choice == 3: exit(1) else: print("Wrong choice")
true
8c2bbc0c0175bc8883d9fe65cbca3511dbefd81e
SuryaNMenon/Python
/Other Programs/leapYear.py
217
4.3125
4
#Program if user input year is leap year or not year = int(input('Enter the year')) if(year%4==0 or year%100==0 or year%400==0): print('Given year is a leap year') else: print('Given year is not a leap year')
true
5493d5308b986e4efd6bfed3687712872d76bc35
hyjae/udemy-data-wrangling
/DataCleaning/audit.py
2,698
4.21875
4
""" Observation of types - NoneType if the value is a string "NULL" or an empty string "" - list, if the value starts with "{" - int, if the value can be cast to int - float, if the value can be cast to float, but CANNOT be cast to int. For example, '3.23e+07' should be considered a float because it can be cast as float but int('3.23e+07') will throw a ValueError - 'str', for all other values The type() function returns a type object describing the argument given to the function. You can also use examples of objects to create type objects, e.g. type(1.1) for a float: see the test function below for examples. """ import codecs import csv import json import pprint CITIES = 'cities.csv' FIELDS = ["name", "timeZone_label", "utcOffset", "homepage", "governmentType_label", "isPartOf_label", "areaCode", "populationTotal", "elevation", "maximumElevation", "minimumElevation", "populationDensity", "wgs84_pos#lat", "wgs84_pos#long", "areaLand", "areaMetro", "areaUrban"] """ Note: A set is unordered collection with no duplicate elements. Curly braces or set function can be used to create sets. """ def check_type(value, isInt): if isInt: try: int(value) return True except ValueError: return False else: try: float(value) return True except ValueError: return False def audit_file(filename, fields): fieldtypes = {} for field in fields: fieldtypes[field] = set() with open(filename, 'r') as f: reader = csv.DictReader(f) """ for i in range(3): l = reader.next() """ for i, datum in enumerate(reader): if i == 2: break for datum in reader: for key, value in datum.items(): if key in fields: if value == 'NULL' or value == '': fieldtypes[key].add(type(None)) elif value[0] == '{': fieldtypes[key].add(type([])) elif check_type(value, True): fieldtypes[key].add(type(1)) elif check_type(value, False): fieldtypes[key].add(type(1.1)) else: fieldtypes[key].add(type('str')) f.close() return fieldtypes def test(): fieldtypes = audit_file(CITIES, FIELDS) pprint.pprint(fieldtypes) assert fieldtypes["areaLand"] == set([type(1.1), type([]), type(None)]) assert fieldtypes['areaMetro'] == set([type(1.1), type(None)]) if __name__ == "__main__": test()
true
4afad85b6bcbaf932ee7a4754308804db627d963
kalyanrohan/ASSIGNMENTS
/FIBONACCI.py
246
4.15625
4
#0,1,1,2,3,5,8 def fibonacci(n): if n <= 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) nterms = int(input("n= ")) print("Fibonacci sequence:") for i in range(nterms): print(fibonacci(i))
false
1df3bc87016ad046ffc4c7a27108e943ae84da27
kalyanrohan/ASSIGNMENTS
/level2excercise.py
1,187
4.6875
5
#LEVEL 2 """ 1.Using range(1,101), make a list containing only prime numbers. """ prime=[x for x in range(2,101) if x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0] print(prime) """ 2.Initialize a 2D list of 3*3 matrix. E.g.- 1 2 3 4 5 6 7 8 9 Check if the matrix is symmetric or not. """ """ 3. Sorting refers to arranging data in a particular format. Sort a list of integers in ascending order ( without using built-in sorted function ). One of the algorithm is selection sort. Use below explanation of selection sort to do this. INITIAL LIST : 2 3 1 45 15 First iteration : Compare every element after first element with first element and if it is larger then swap. In first iteration, 2 is larger than 1. So, swap it. 1 3 2 45 15 Second iteration : Compare every element after second element with second element and if it is larger then swap. In second iteration, 3 is larger than 2. So, swap it. 1 2 3 45 15 Third iteration : Nothing will swap as 3 is smaller than every element after it. 1 2 3 45 15 Fourth iteration : Compare every element after fourth element with fourth element and if it is larger then swap. In fourth iteration, 45 is larger than 15. So, swap it. 1 2 3 15 45 """
true
1ff75c4685f869eece4ada6af2fb00769e251097
JudgeVector/Projects
/SOLUTIONS/Text/CountVowels.py
636
4.1875
4
""" Count Vowels - Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. """ vowels = ['a','e','i','o','u'] vowel_count = [0,0,0,0,0] def count_vowels(s): for i in range(0, len(s)): if s[i] in vowels: for j in range(0, len(vowels)): if s[i] is vowels[j]: vowel_count[j] += 1 total = 0 for v in range(0, len(vowel_count)): total += vowel_count[v] print(vowels[v] + ' : ' + str(vowel_count[v])) return total print('Total number of vowels: ' + str(count_vowels(input('Enter a word or phrase to count the vowels: ').lower())))
true
53cf3eed32f2c405ee56e4b433e3180bc1aa1d77
kju2/euler
/problem033.py
1,362
4.15625
4
""" The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ from fractions import Fraction from operator import mul def main(): """ >>> main() 100 """ # not a curious fraction 30/50 or 77/77 curious_fractions = [] for numerator_tens in range(1, 10): for denominator_unit in range(1, 10): for cancler in range(1, 10): numerator = numerator_tens * 10 + cancler denominator = cancler * 10 + denominator_unit fraction1 = Fraction(numerator, denominator) fraction2 = Fraction(numerator_tens, denominator_unit) if fraction1 == fraction2 and numerator != denominator: curious_fractions.append(fraction1) print(reduce(mul, curious_fractions).denominator) if __name__ == "__main__": import doctest doctest.testmod()
true
a3940af34ce7d808facbdb0ac67cdbbd17d50a23
xxrom/617_merge_two_binary_trees
/main.py
2,534
4.125
4
# Definition for a binary tree node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __str__(self): return str(self.__dict__) class Solution: # print all values def printAll(self, root): if root.val != None: print(root.val) if root != None and root.left != None: self.printAll(root.left) if root != None and root.right != None: self.printAll(root.right) def mergeTrees(self, node0: Node, node1: Node) -> Node: # if one of the nodes exist if (node0 != None and node0.val != None) or (node1 != None and node1.val != None): # We use node0 as merged one (for answer), so init it if needed if node0 == None: node0 = Node(0) # Merge (add) value from node1 (another one tree) node0.val += node1.val if node1 != None and node1.val != None else 0 # Find out values from node1 childrens (like shortcuts) node1Left = node1.left if node1 != None and node1.left != None else None node1Right = node1.right if node1 != None and node1.right != None else None # If someone in the left/right exist, then merge deeper if node0.left != None or node1Left != None: node0.left = self.mergeTrees( node0.left, node1Left) if node0.right != None or node1Right != None: node0.right = self.mergeTrees( node0.right, node1Right) # merged tree - node0 (result) return node0 tree0 = Node(1, Node(3, Node(5)), Node(2)) tree1 = Node(2, Node(1, None, Node(4)), Node(3, None, Node(7))) my = Solution() merged = my.mergeTrees(tree0, tree1) my.printAll(merged) # 3 # 4 5 # 5 4 5 7 # with additional merged tree: # Runtime: 108 ms, faster than 5.41% of Python3 online submissions for Merge Two Binary Trees. # Memory Usage: 14.1 MB, less than 22.86% of Python3 online submissions for Merge Two Binary Trees. # without additional tree: # Runtime: 104 ms, faster than 9.26% of Python3 online submissions for Merge Two Binary Trees. # Memory Usage: 13.7 MB, less than 74.29% of Python3 online submissions for Merge Two Binary Trees. # Runtime: 96 ms, faster than 17.71% of Python3 online submissions for Merge Two Binary Trees. # Memory Usage: 13.8 MB, less than 68.57% of Python3 online submissions for Merge Two Binary Trees.
true
2d425e371bd59c5a0ad3e6807a239378c5e44a12
jiaoqiyuan/Tests
/Python/python-practice/chapter5-if/toppints.py
1,428
4.25
4
requested_topping = 'mushrooms' if requested_topping != 'anchovies': print("Hold the anchovies!") answer = 17 if answer != 42: print("That is not the correct answer. Please try again!") requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms.") if 'pepperoni' in requested_toppings: print("Adding pepperoni.") if 'extra cheese' in requested_toppings: print("Adding extra cheese.") print("\nFinished making you pizza!") requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Sorry, we are out of green peppers fight now.") else: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!") requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!") else: print("Are you sure you want a pizza?") avaliable_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in avaliable_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we don't have " + requested_topping + ".") print("\nFinished making your pizza!")
true
9fac6a0305889d4cdbe3bfa868aea21272314850
mmaoga/bootcamp
/helloworld.py
711
4.21875
4
print ("hello, world") print ("hi my name is Dennis Manyara") print("This is my first code") for _ in range(10): print("Hello, World") text = "Hello my world" print(text) text = "My name is Dennis Maoga Manyara" print(text) print("hello\n"*3) name = "Dennis M." print("Hello, World, This is your one and only",name) print ('Hi {2}, {1} and {0}'.format ('Alice','Bob','Carol')) print ('I love {1} more than {0}, how about you?'.format ('singing','coding')) number = 1+2*3/4*5/5 print (number) data = ("Alice", "Bob", "Carol") date = () format_string = "Hi %s %s and %s." print(format_string % data) from datetime import date today = date.today() print ("Hi", name ,"today's date is", today) x = 7 y = 0 print (x/y)
true
a0716d4c67188d6e9e25e3e2220fa754fad57444
NewmanJ1987/design_patterns_python
/creational/factory.py
1,487
4.25
4
# Factory pattern: Abstract away the creation of an object from the # client that is creating object. TWO_WHEEL_VEHICLE = 1 THREE_WHEEL_VEHICLE = 2 FOUR_WHEEL_VEHICLE = 3 class Vehicle(): def print_vechile(self): pass class TwoWheelVehicle(Vehicle): def __init__(self): super(TwoWheelVehicle, self).__init__() def print_vechile(self): print("Two Wheeler") class FourWheelVehicle(Vehicle): def __init__(self): super(FourWheelVehicle, self).__init__() def print_vechile(self): print("Four Wheeler") class ThreeWheelVehicle(Vehicle): def __init__(self): super(ThreeWheelVehicle, self).__init__() def print_vechile(self): print("Three Wheeler") class VehicleFactory(): @staticmethod def create_vehicle(vehicle_type): # For a new vehicle we just modify the factory that is responsible for the creation. if vehicle_type == TWO_WHEEL_VEHICLE: return TwoWheelVehicle() if vehicle_type == THREE_WHEEL_VEHICLE: return ThreeWheelVehicle() if vehicle_type == FOUR_WHEEL_VEHICLE: return FourWheelVehicle() class Client(): def __init__(self, vehicle_type): # If we add a new vehicle we don't have to modify the code of the client. Which is an advantage when using a creational. self.vehicle = VehicleFactory.create_vehicle(vehicle_type) client = Client(TWO_WHEEL_VEHICLE) client.vehicle.print_vechile()
false
303fbdd2815a32d580ccd80192cd28da946a2865
Tej-Singh-Rana/Code-War
/code3.py
263
4.15625
4
#!/bin/python3 #reverse !! name=input("Enter the word you want to reverse : ") print(name[::-1],end='') #to reverse infinite not adding value in parameters. print('\n') #print(name[4::-1],end='') #to reverse in max 4 index values. #print('\n')
true
0deae1c6773a018bef55d8e1bcbc5477eee7311c
yuuuhui/Basic-python-answers
/梁勇版_4.5rpy.py
964
4.34375
4
day = int(input("Enter today's day :")) daye = int(input("Enter the number of days elaspsed since today:")) dayf = day + daye dayc = dayf % 7 print(dayc) if day == 0: print("Today is Sunday") elif day == 1: print("Today is Monday") elif day == 2: print("Today is Tuesday") elif day == 3: print("Today is Wednesday") elif day == 4: print("Today is Thursday") elif day == 5: print("Today is Friday") elif day == 6: print("Today is Saturday") else: print("Wrong input") if dayc == 0: print("The future day is Sunday") elif dayc == 1: print("The future day is Monday") elif dayc == 2: print("The future day is Tuesday") elif dayc == 3: print("The future day is Wednesday") elif dayc == 4: print("The future day is Thursday") elif dayc == 5: print("The future day is Friday") elif dayc == 6: print("The future day is Saturday") else: print("no else")
false
8057729bfad807fc5b23ed68b71e5746af7b26ee
yuuuhui/Basic-python-answers
/梁勇版_4.28rpy.py
949
4.21875
4
x1,y1,w1,h1 = eval(input("Enter r1's x-,y- coordinates,width,and height:")) x2,y2,w2,h2 = eval(input("Enter r2's x-,y- coordinates,width,and height:")) hd12 = abs(x2 - x1) vd12 = abs(y2 - y1) if 0 <= hd12 <= w1 /2 and 0 <= vd12 <= h1 / 2: print("The coordinate of center of the 2nd rect is within the 1st rect") if x1 == x2 and y1 == y2 and w1 == w2 and h1 == h2: print("r2 overlaps completely with r1") elif ((x2 + w2 / 2) > (x1 + w1 / 2)) or \ ((x2 - w2 /2) < (x1 - w1 /2 )) or \ ((y2 + h2 /2) > (y1 + h1 /2)) or \ ((y2 - h2 /2) < (y1 - h1 /2)): print("r2 overlaps with r1") else: print("r2 is inside r1") else: print("The coordinate of center of the 2nd rect is outside the 1st rect") if hd12 <= (w1/2 + w2 /2) or vd12 <=(h1/2 + h2 /2 ): print("r2 overlaps with r1") else: print("r2 is completely outside of r1")
true
dfa4ad361b159743f8ecd2f3888e6e6e1420ed3d
yuuuhui/Basic-python-answers
/梁勇版_5.24py.py
640
4.125
4
loan = eval(input("Loan Amount")) year = int(input("Number of Years:")) rate = eval(input("Annual Interest Rate:")) monthly = (loan * rate / 12) / (1 - 1 / ((1 + rate / 12) ** (year * 12))) total = monthly * 12 * year print("Monthly Payment:{:.2f}".format(monthly)) print("Total Payment:{:.2f}".format(total)) print("Payment# \t Interest \t Principal \t Balance") count = 1 while count <= 12: interest = loan * (rate / 12) principal = monthly - interest loan -= principal print(count, "\t","\t","{:.2f}".format(interest), "\t\t","{:.2f}".format(principal),"\t","{:.2f}".format(loan)) count += 1
false
c51001c9f85d970cba0d7e06757e021919ec132e
joseluisvzg/EnvioClickChallenge
/Python/Exercise2.py
415
4.34375
4
#!/usr/bin/env python consec_vowel = { 'a': 'e', 'e': 'i', 'i': 'o', 'o': 'u', 'u': 'a' } def vowels_changer(text): new_text = [] for char in text.lower(): if char in consec_vowel: char = consec_vowel[char] new_text.append(char) new_text = ''.join(new_text) return new_text if __name__ == "__main__": text = input("Type a text: ") new_text = vowels_changer(text) print(f"New text: {new_text}")
false
e174013d66f9135fd27ed24b666eff412b3f49c3
Sarumathikitty/guvi
/codekata/Absolute_Beginner/check_odd_even.py
264
4.5
4
#program to check number whether its odd or even. number=float(input()) num=round(number) #check number whether it is zero if(num==0): print("Zero") #whether the number is not zero check its odd or even elif(num%2==0): print("Even") else: print("Odd")
true
a34a5cf032f82720848d4adaef67d135ad941e4c
pradyotpsahoo/P342_A1
/A1_Q2.py
500
4.46875
4
# find the factorial of a number provided by the user. # taking the input from the user. num = int(input("Enter the number : ")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print("Factorial does not exist for negative numbers. Enter the positive number.") elif num == 0: print("The factorial of 0 is 1") else: #loop iterate till num for i in range(1,num+1 ): factorial = factorial*i print("The factorial of",num,"is",factorial)
true
aa9b82d2376bccc0c2ee86a4458901fd1bb42707
SireeshaPandala/Python
/Python_Lesson5/Python_Lesson5/LinReg.py
936
4.15625
4
import numpy as np import matplotlib.pyplot as plt #for plotting the given points x=np.array([2.9,6.7,4.9,7.9,9.8,6.9,6.1,6.2,6,5.1,4.7,4.4,5.8]) #converts the given list into array y=np.array([4,7.4,5,7.2,7.9,6.1,6,5.8,5.2,4.2,4,4.4,5.2]) meanx=np.mean(x) #the meanvalue of x will be stored in meanx meany=np.mean(y) #the meanvalue of y will be stored in meany num=np.sum((x-meanx)*(y-meany)) #calculate the difference between the mean and given value den=np.sum(pow((x-meanx),2)) #squares the difference between given x and meanx m=num/den #slope calculation intercept=meany-(m*meanx) val=(m*x)+intercept #gives us the line equation plt.plot(x,y,"ro") #plots the given x,y values plt.plot(x,val) plt.show() #plots the points on the graph
true
0006e05bf9c4ce0377506756e72398b560e3cc21
swimbikerun96/Brian-P.-Hogan---Exercises-for-Programmers
/#25 Password Strength Indicator/Password Strength Indicator - Constraints.py
1,900
4.125
4
#Create lists to check the password entered against numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] special_characters = [' ','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\'',']','^','_','`','{','|','}','~'] alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] def passwordValidator(password): #Create a list to store password characters in mylist = [] #Check for Weak and Very Weak Passwords if len(password) < 8: if password.isnumeric() == True: return 1 elif password.isalpha() == True: return 2 else: return 3 #Check for Strong and Very Strong Passwords elif len(password) > 8: for character in password: if character.isdigit() == True: mylist.append("Numbers") elif character.isalpha() == True: mylist.append("Letters") elif character in special_characters: mylist.append("sc") if "sc" in mylist and "Letters" in mylist and "Numbers" in mylist: return 5 elif "Letters" in mylist and "Numbers" in mylist: return 4 else: return 6 #Dictionary to match up returned values from function to statements for the user strength_dict = { 1 : "is a very weak password.", 2 : "is a weak password.", 3 : "is complex, yet short. Consider revising.", 4 : "is a strong password.", 5 : "is a very strong password.", 6 : "is long, yet simple. Consider revising." } #While Loop to handle user input while True: pw = input("Please Enter a Password: ") verdict = passwordValidator(pw) output = f'"{pw}" {strength_dict[verdict]}' print(output)
false
7cb0fe658d8359c299ca1cca662c19c015d7441a
pvaliani/codeclan_karaoke
/tests/song_test.py
714
4.21875
4
import unittest from classes.song import Song class TestSong(unittest.TestCase): def setUp(self): self.song = Song("Beautiful Day", "U2") # - This test determines that a song exists by comparing the object self.song with attribute "name" to the value of "Beautiful Day by U2" # - self.song.name reads as self.song -> the song object from classes.song and .name is the attribute of the song as defined in the Song class # - Check that the song has a title def test_song_has_name(self): self.assertEqual(self.song.name, "Beautiful Day") # - Check that the song has an artist def test_song_has_artist(self): self.assertEqual(self.song.artist, "U2")
true
f25ecf69bcb1c5f168f74fd923d72b9a53248763
MomSchool2020/show-me-your-cool-stuff-LisaManisa
/Lesson3.py
583
4.15625
4
print("Hello World!") # if you have a line of text that you want to remove, #"comment it out" by adding in a hashtag. # print("Hello World!") # text in Python is always in quotation marks print("Lisa") print("Hello World. Lisa is cool") print("Lisa said, 'I love you'") print('Lisa said, "I love you"') # if you put anything in single quotes, it won't run. print (print("Hello World!")) print("Hello World!") print("I'm the smartest in the class!!") # use backslash for ignoring the next thing in the code. print('print("That\'s Mine!")') # \n means new line print("Hello\nWorld")
true
821f16b00b90c79867dfbfbf7f93d92d9ce3a23b
agray998/qa-python-assessment-example
/exampleAssessment/Code/example.py
503
4.5625
5
# <QUESTION 1> # Given a string, return the boolean True if it ends in "py", and False if not. Ignore Case. # <EXAMPLES> # endsDev("ilovepy") → True # endsDev("welovepy") → True # endsDev("welovepyforreal") → False # endsDev("pyiscool") → False # <HINT> # What was the name of the function we have seen which changes the case of a string? Use your CLI to access the Python documentation and get help(str). def endsPy(input): strng = input.lower() return strng.endswith('py', -2)
true
231b812ebd89cf804f350a03e3ca5d0b11023cb8
TonaGonzalez/CSE111
/02TA_Discount.py
1,162
4.15625
4
# Import the datatime module so that # it can be used in this program. from datetime import datetime # Call the now() method to get the current date and # time as a datetime object from the computer's clock. current = datetime.now() # Call the isoweekday() method to get the day # of the week from the current datetime object. weekday = current.isoweekday() subtotal = float(input("Please enter the subtotal: ")) tax = subtotal * .06 total = subtotal + tax if weekday == 2 or weekday == 3: if subtotal >= 50: discount = subtotal * .10 discount2 =subtotal - discount tax2 = discount2 * .06 total2 = discount2 + tax2 print(f"Discount amount is {discount:.2f}") print(f"Tax amount is {tax2:.2f}") print(f"Total is {total2:.2f}") else: difference = 50 - total print(f"Tax amount is {tax:.2f}") print(f"Total is {total:.2f}") print("TODAY'S PROMOTION!") print(f"If you buy ${difference:.2f} more, you'll get a 10% discount in your subtotal") else: print(f"Tax amount is {tax:.2f}") print(f"Total is {total:.2f}")
true
fb0055af02a4823c00e6baeaa1c44c3089dacd4a
hovell722/eng-54-python-practice-exercises
/exercise_102.py
610
4.3125
4
# # Create a little program that ask the user for the following details: # - Name # - height # - favourite color # - a secrete number # Capture these inputs # Print a tailored welcome message to the user # print other details gathered, except the secret of course # hint, think about casting your data type. name = input("What is you name? ") name = name.title() height = int(input("What is your height in cm's? ")) colour = input("What is your favourite colour? ") number = int(input("Give me a secret number: ")) print(f"Hello {name}, you are {height}cm's tall and your favourite colour is {colour}")
true
d2d41bc519f79737818c852306c97b988e89ace7
hovell722/eng-54-python-practice-exercises
/exercise_107.py
1,370
4.46875
4
# SIMPLEST - Restaurant Waiter Helper # User Stories #1 # AS a User I want to be able to see the menu in a formated way, so that I can order my meal. #2 # AS a User I want to be able to order 3 times, and have my responses added to a list so they aren't forgotten #3 # As a user, I want to have my order read back to me in formated way so I know what I ordered. # DOD # its own project on your laptop and Github # be git tracked # have 5 commits mininum! # has documentation # follows best practices # starter code menu = ['falafel', 'HuMMus', 'coUScous', 'Bacalhau a Bras'] food_order = [] menu[0] = menu[0].title() menu[1] = menu[1].title() menu[2] = menu[2].title() menu[3] = menu[3].title() print("Here is the menu") count = 0 for food in menu: count += 1 print(count, food) count = 0 while count < 3: count += 1 order = input("What food would you like to order? Give the number: ") if order == str(1): order = menu[0] elif order == str(2): order = menu[1] elif order == str(3): order = menu[2] elif order == str(4): order = menu[3] food_order.append(order) count = 0 print("You have ordered: ") for food in food_order: count += 1 print(count, food) # I need to print each item from the list # print(menu[0]) # before I print I need to make them all capitalized # print everything
true
12bfab7e083f2b0326e72ec60cd53c42be2dd280
monicajoa/holbertonschool-higher_level_programming
/0x0B-python-input_output/6-from_json_string.py
425
4.15625
4
#!/usr/bin/python3 """This module holds a function From JSON string to Object """ import json def from_json_string(my_str): """function that returns an object (Python data structure) represented by a JSON string Arguments: my_str {[str]} -- string to convert to object Returns: [object] -- (Python data structure) represented by a JSON string """ return json.loads(my_str)
true
eb8ac907b35bacba795aae007f4d3adb03a77e23
monicajoa/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
703
4.5
4
#!/usr/bin/python3 """ This module hold a function that prints a square with the character #. """ def print_square(size): """ This function prints square by the size Paramethers: size: length of the square Errors: TypeError: size must be an integer ValueError: size must be >= 0 Returns: Nothing """ if type(size) is not int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if (type(size) is float and size < 0): raise TypeError("size must be an integer") for x in range(size): for y in range(size): print('#', end="") print()
true
63dac65210c83675bf6c7b07e055231e7434a8ec
enkefalos/PythonCourse
/hw1_question3.py
1,184
4.28125
4
def compare_subjects_within_student(subj1_all_students :dict, subj2_all_students :dict): """ Compare the two subjects with their students and print out the "preferred" subject for each student. Single-subject students shouldn't be printed. Choice for the data structure of the function's arguments is up to you. """ for key, val in subj1_all_students.items(): if key != 'subject' and key in subj2_all_students: print(key, end = ' ') if max(val) > max(subj2_all_students[key]): print(subj1_all_students['subject']) continue print(subj2_all_students['subject']) if __name__ == '__main__': # Question 3 math_grades = { 'subject': 'Math', 'Zvi': (100, 98), 'Omri': (68, 93), 'Shira': (90, 90), 'Rony': (85, 88) } history_grades = { 'subject': 'History', 'Zvi': (69, 73), 'Omri': (88, 74), 'Shira': (92, 87), 'Rony': (92, 98) } print('Preffered subject per student') compare_subjects_within_student(math_grades, history_grades)
true
14f7a544807a575b1ee39c99bfbdad6c7efd90b1
tyteotin/codewars
/6_kyu/is_triangle_number.py
1,168
4.15625
4
""" Description: Description: A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example, 6 is a triangle number because you can arrange 6 objects into an equilateral triangle: 1 2 3 4 5 6 8 is not a triangle number because 8 objects do not form an equilateral triangle: 1 2 3 4 5 6 7 8 In other words, the nth triangle number is equal to the sum of the n natural numbers from 1 to n. Your task: Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any non-integers, including non-number types, are not triangle numbers). You are encouraged to develop an effective algorithm: test cases include really big numbers. Assumptions: You may assume that the given input, if it is a number, is always positive. Notes: 0 and 1 are triangle numbers. """ def is_triangle_number(number): if(str(number).isdigit() == False): return False elif(float(number).is_integer() == False): return False else: if(((8*number+1)**(1.0/2)).is_integer() == True): return True else: return False
true
d60efd85d0348706c2262820706a4234a775df1a
Sairahul-19/CSD-Excercise01
/04_is_rotating_prime.py
1,148
4.28125
4
import unittest question_04 = """ Rotating primes Given an integer n, return whether every rotation of n is prime. Example 1: Input: n = 199 Output: True Explanation: 199 is prime, 919 is prime, and 991 is prime. Example 2: Input: n = 19 Output: False Explanation: Although 19 is prime, 91 is not. """ # Implement the below function and run the program from itertools import permutations def is_rotating_prime(num): l=[] a=list(permutations(str(num),len(str(num)))) for i in a : l.append("".join(i)) for k in l: for j in range(2,int(k)): if (int(k)%j)==0: return False return True class TestIsRotatingPrime(unittest.TestCase): def test_1(self): self.assertEqual(is_rotating_prime(2), True) def test_2(self): self.assertEqual(is_rotating_prime(199), True) def test_3(self): self.assertEqual(is_rotating_prime(19), False) def test_4(self): self.assertEqual(is_rotating_prime(791), False) def test_5(self): self.assertEqual(is_rotating_prime(919), True) if __name__ == '__main__': unittest.main(verbosity=2)
true