blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7a26e4bc77d34fd19cf4350c78f4764492d32064
venkatadri123/Python_Programs
/core_python_programs/prog83.py
250
4.25
4
# Retrive only the first letter of each word in a list. words=['hyder','secunder','pune','goa','vellore','jammu'] lst=[] for ch in words: lst.append(ch[0]) print(lst) # To convert into List Comprehension. lst=[ch[0] for ch in words] print(lst)
true
b1c41d7bfbc80bdd15642bcb0f02291c7867779e
ProgrammingForDiscreteMath/20170830-bodhayan
/code.py
700
4.15625
4
# 1 # Replace if-else with try-except in the the example below: def element_of_list(L,i): """ Return the 4th element of ``L`` if it exists, ``None`` otherwise. """ try: return L[i] except IndexError: return None # 2 # Modify to use try-except to return the sum of all numbers in L, # ignoring other data-types def sum_of_numbers(L): """ Return the sum of all the numbers in L. """ s = 0 for l in L: try: s+= l except TypeError: pass return s # TEST # print sum_of_numbers([3, 1.9, 's']) == 4.9 # L1 = [1,2,3] # L2 = [1,2,3,4] # print fourth_element_of_list(L1) # print fourth_element_of_list(L2)
true
b6834d2bf0af216c26a7a2b92880ab566685caea
planetblix/learnpythonthehardway
/ex16.py
1,436
4.40625
4
#/bin/python from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Open the file..." #rw doesn't mean read and write, it just means read! #You could open the file twice, but not particularly safe, #As you could overwrite the file. target = open(filename, 'r+') #Other file modes: #'r' - open for read only #'r+' - open for read and write, cannot truncate #'rb - reading binary #'rb+ - reading or writing a binary file #'w' - open for write only #'w+' - open fo read and write, can truncate #'a' - open for append only #'a+' - open for reading and writing. #'U' - opens file for input with Universal newline input. #Based on C fopen(): http://www.manpagez.com/man/3/fopen/ #Nice examples here: http://www.tutorialspoint.com/python/python_files_io.htm print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1:") line2 = raw_input("line 2:") line3 = raw_input("line 3:") print "I'm going to write these to the file." #target.write(line1) #target.write("\n") #target.write(line2) #target.write("\n") #target.write(line3) #target.write("\n") target.write("%s\n" % line1) target.write("%s\n" % line2) target.write("%s\n" % line3) print target.read() print "And finally, we close it." target.close()
true
9522b6a465c1644ff8399a838eb3a7fb3b9cbcec
seriouspig/homework_week_01_day_01
/precourse_recap.py
566
4.15625
4
print("Guess the number I'm thinking from 1 to 10, What do you think it is?") guessing = True number_list = [1,2,3,4,5,6,7,8,9,10] import random selected_number = random.choice(number_list) while guessing == True: answer = int(input('Pick a number from 1 to 10: ')) if answer == selected_number: print("Great, you must be a psychic!") guessing = False break elif answer < selected_number: print("No, my number is higher, try again") elif answer > selected_number: print("No, my number is lower, try again")
true
961b6639cb292351bff3d4ded8c366ab0d860ed8
IshaqNiloy/Any-or-All
/main (1).py
980
4.25
4
def is_palindromic_integer(my_list): #Checking if all the integers are positive or not and initializing the variable is_all_positive = all(item >= 0 for item in my_list) #Initializing the variable is_palindrome = False if is_all_positive == True: for item in my_list: #Converting the integer into a string and reversing it item_str = str(item)[::-1] #Checking weather the string is a palindrome or not if str(item) == item_str: is_palindrome = True #Printing the result if is_all_positive == True and is_palindrome == True: print('True') else: print('False') if __name__ == '__main__': #Defining an empty list my_list = [] #taking input for the number of integers number_of_integers = input() #taking input for the list my_list = list(map(int, input().split())) #Calling the function is_palindromic_integer(my_list)
true
de3f02e8416760c40ab208ff7ee372313040fcd1
bishal-ghosh900/Python-Practice
/Practice 1/main30.py
992
4.1875
4
# Sieve of Eratosthenes import math; n = int(input()) def findPrimes(n): arr = [1 for i in range(n+1)] arr[0] = 0 arr[1] = 0 for i in range(2, int(math.sqrt(n)) + 1, 1): if arr[i] == 1: j = 2 while j * i <= n: arr[j*i] = 0 j += 1 for index, value in enumerate(arr): # enumerate will give tuples for every iteration which will contain index and value of that particular iteration coming from the list . And in this particular list the tuple is being unpacked in the index and the value variable # Its something like --> index, value = ("0", 1) # index, value = ("1", 2) and so on # "0", "1", "2" etc are the indexs of the list, and the next argument is the value of that particular index from the list in which we are performing enumerate() operation. if value == 1: print(index, sep=" ") else: continue findPrimes(n)
true
eaadca4eda12fc7af10c3a6f70437a760c14358f
bishal-ghosh900/Python-Practice
/Practice 1/main9.py
595
4.6875
5
# Logical operator true = True false = False if true and true: print("It is true") # and -> && else: print("It is false") # and -> && # Output --> It is true if true or false: print("It is true") # and -> || else: print("It is false") # and -> || # Output --> It is true if true and not true: print("It is true") # and -> && # not -> ! else: print("It is false") # and -> && # Output --> It is false if true or not true: print("It is true") # and -> && # not -> ! else: print("It is false") # and -> && # Output --> It is true
true
460ea4d25a2f8d69e8e009b70cdec588b8ca7b20
bishal-ghosh900/Python-Practice
/Practice 1/main42.py
782
4.28125
4
# set nums = [1, 2, 3, 4, 5] num_set1 = set(nums) print(num_set1) num_set2 = {4, 5, 6, 7, 8} # in set there is not any indexing , so we can't use expression like num_set1[0]. # # Basically set is used to do mathematics set operations #union print(num_set1 | num_set2) # {1, 2, 3, 4, 5, 6, 7, 8} # intersection print(num_set1 & num_set2) # {4, 5} # A - B --> Every element of A but not of B print(num_set1 - num_set2) # {1, 2, 3} # B - A --> Every element of B but not of A print(num_set2 - num_set1) # {8, 6, 7} # symmetric difference --> (A - B) U (B - A) --> Every thing present in A and B but not in both print(num_set1 ^ num_set2) # {1, 2, 3, 6, 7, 8} # like list we can also create set comprehension nums = { i * 2 for i in range(5)} print(nums) # {0, 2, 4, 6, 8}
true
789e675cb561a9c730b86b944a0a80d6c423f475
bishal-ghosh900/Python-Practice
/Practice 1/main50.py
804
4.75
5
# private members # In python there we can prefix any data member with __ (dunder sign) , then it will be private. In reality it don't get private, if we declare any data member with __ , that data member actually get a differet name from python , which is like => _classname__fieldname. So in the below implementation if we change "eyes" field member to "__eyes" , then python will change it to "_Animal__eyes" . We can't access "eyes" by using "a.eyes" (here think "a" is Animal object) as eyes is changed to "_Animal__eyes" , so if we want to access "eyes", then we have to access it by using "a._Animal__eyes" class Animal: def run(self): print("I can run") __eyes = 2 a = Animal() # print(a.eyes) => error -> Animal object has no attribute eyes print(a._Animal__eyes) # 2 a.run()
true
c35759cf6ddf382cd6ec14e90bd013707af13fd6
learninfo/pythonAnswers
/Task 5 - boolean.py
236
4.375
4
import turtle sides = int(input("number of sides")) while (sides < 3) or (sides > 8) or (sides == 7): sides = input("number of sides") for count in range(1, sides+1): turtle.forward(100) turtle.right(360/sides)
true
a8a5edf3c6cf3f5a6470016eb6c5802e18df4338
bharath-acchu/python
/calci.py
899
4.1875
4
def add(a,b): #function to add return (a+b) def sub(a,b): return (a-b) def mul(a,b): return (a*b) def divide(a,b): if(b==0): print("divide by zero is not allowed") return 0 else: return (a/b) print('\n\t\t\t SIMPLE CALCULATOR\n') while 1: print('which operation you want to ?\n') print('1.addition\n2.subtraction\n3.multiplication\n4.division\n') ch=int(input('ENTER YOUR CHOICE\n')) a=float(input("Enter first number\n")) b=float(input("Enter second number\n")) if ch is 1: #is also used as equality operator print("ans=",add(a,b)) elif(ch==2): print("ans=",sub(a,b)) elif(ch==3): print("ans=",mul(a,b)) elif(ch==4): print("ans=",divide(a,b)) else:print("improper choice\n")
true
49629b071964130f6fb9034e96480f7b5a179e51
aakhriModak/assignment-1-aakhriModak
/01_is_triangle.py
2,117
4.59375
5
""" Given three sides of a triangle, return True if it a triangle can be formed else return False. Example 1 Input side_1 = 1, side_2 = 2, side_3 = 3 Output False Example 2 Input side_1 = 3, side_2 = 4, side_3 = 5 Output True Hint - Accordingly to Triangle inequality theorem, the sum of any two sides of a triangle must be greater than measure of the third side """ import unittest # Implement the below function and run this file # Return the output, No need read input or print the ouput def is_triangle(side_1, side_2, side_3): # write your code here if side_1>0 and side_2>0 and side_3>0: if side_1+side_2>side_3 and side_2+side_3>side_1 and side_1+side_3>side_2: return True else: return False else: return False # DO NOT TOUCH THE BELOW CODE class TestIsTriangle(unittest.TestCase): def test_01(self): self.assertEqual(is_triangle(1, 2, 3), False) def test_02(self): self.assertEqual(is_triangle(2, 3, 1), False) def test_03(self): self.assertEqual(is_triangle(3, 1, 2), False) def test_04(self): self.assertEqual(is_triangle(3, 4, 5), True) def test_05(self): self.assertEqual(is_triangle(4, 5, 3), True) def test_06(self): self.assertEqual(is_triangle(5, 3, 4), True) def test_07(self): self.assertEqual(is_triangle(1, 2, 5), False) def test_08(self): self.assertEqual(is_triangle(2, 5, 1), False) def test_09(self): self.assertEqual(is_triangle(5, 1, 2), False) def test_10(self): self.assertEqual(is_triangle(0, 1, 1), False) def test_11(self): self.assertEqual(is_triangle(1, 0, 1), False) def test_12(self): self.assertEqual(is_triangle(1, 1, 0), False) def test_13(self): self.assertEqual(is_triangle(-1, 1, 2), False) def test_14(self): self.assertEqual(is_triangle(1, -1, 2), False) def test_15(self): self.assertEqual(is_triangle(1, 1, -2), False) if __name__ == '__main__': unittest.main(verbosity=2)
true
5097aa5c089e31d239b06bbd76e99942694cbdd7
CBehan121/Todo-list
/Python_imperative/todo.py
2,572
4.1875
4
Input = "start" wordString = "" #intializing my list while(Input != "end"): # Start a while loop that ends when a certain inout is given Input = input("\nChoose between [add], [delete], [show list], [end] or [show top]\n\n") if Input == "add": # Check if the user wishes to add a new event/task to the list checker = input("\nWould you Task or Event?\n") # Take the task/event input if checker.lower() == "task": words = input("Please enter a Date.\n") + " " words += input("Please enter a Start time.\n") + " " words += input("Please enter a Duration.\n") + " " words += input("Please enter a list of members. \n") wordString = wordString + words + "!" # Add the new task/event to the list. I use a ! to seperate each item. elif checker.lower() == "event": words = input("Please enter a Date, Start time and Location\n") + " " words += input("Please enter a Start time. \n") + " " words += input("Please enter a loaction. \n") wordString = wordString + words + "!" # Add the new task/event to the list. I use a ! to seperate each item. else: print("you failed to enter a correct type.") elif Input == "show top": if wordString != "": # Enure there is something in your list already i = 0 while wordString[i] != "!": # iterates until i hit a ! which means ive reached the end of an item i += 1 print("\n\n" + wordString[:i] + "\n") # print the first item in the list else: print("\n\nYour list is empty.\n") elif Input == "delete": if wordString != "": #the try is put in place incase the string is empty. i = 0 while wordString[i] != "!": # iterate until i reach the end of the first task/event i += 1 wordString = wordString[i + 1:] #make my list equal from the end of the first item onwards else: print("\n\nYour list is already empty.\n") elif Input == "show list": if wordString != "": fullList = "" # create a new instance of the list so i can append \n inbetween each entry. i = 0 # Normal counter j = 0 # holds the position when it finds a ! for letter in wordString: if letter == "!": fullList = fullList + wordString[j:i] + "\n" # appending each item to the new list seperated by \n j = i + 1 # this needs a + 1 so it ignores the actual ! i = i + 1 print("\n\n" + fullList) else: print("\n\nYour list is empty\n") elif Input == "end": print("exiting program") else: print("\nYour input wasnt correct please try again\n") # This is just in place to catch any incorrect inputs you may enter.
true
813e9e90d06cb05c93b27a825ac14e5e96abcc9b
bparker12/code_wars_practice
/squre_every_digit.py
520
4.3125
4
# Welcome. In this kata, you are asked to square every digit of a number. # For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. # Note: The function accepts an integer and returns an integer def square_digits(num): dig = [int(x) **2 for x in str(num)] dig = int("".join([str(x) for x in dig])) print(dig) square_digits(9119) # more efficient def square_digits1(num): print(int(''.join(str(int(d)**2) for d in str(num)))) square_digits1(8118)
true
f9b9cc936f7d1596a666d0b0586e05972e94cefa
jamiekiim/ICS4U1c-2018-19
/Working/practice_point.py
831
4.375
4
class Point(): def __init__(self, px, py): """ Create an instance of a Point :param px: x coordinate value :param py: y coordinate value """ self.x = px self.y = py def get_distance(self, other_point): """ Compute the distance between the current obejct and another Point object :param other_point: Point object to find the distance to :return: float """ distance = math.sqrt((other_point.x - self.x)**2 + (other_point.y - self.y)**2) return distance def main(): """ Program demonstrating the creation of Point instances and calling class methods. """ p1 = Point(5, 10) p2 = Point(3, 4) dist = p1.get_distance(p2) print("The distance between the points is" + str(dist)) main()
true
318a80ce77b542abc821fa8ff2983b0760da2838
aaronstaclara/testcodes
/palindrome checker.py
538
4.25
4
#this code will check if the input code is a palindrome print('This is a palindrome checker!') print('') txt=input('Input word to check: ') def palindrome_check(txt): i=0 j=len(txt)-1 counter=0 n=int(len(txt)/2) for iter in range(1,n+1): if txt[i]==txt[j]: counter=counter+1 i=i+iter j=j-iter if counter==n: disp="Yes! It is a palindrome!" else: disp='No! It is not a palindrome!' return print(disp) palindrome_check(txt)
true
f0754dfa5777cd2e69afa26e2b73b216d0ff5313
sb1994/python_basics
/vanilla_python/lists.py
346
4.375
4
#creating lists #string list friends = ["John","Paul","Mick","Dylan","Jim","Sara"] print(friends) #accessing the index print(friends[2]) #will take the selected element and everyhing after that print(friends[2:]) #can select a range for the index print(friends[2:4]) #can change the value at specified index friends[0] = "Toby" print(friends)
true
1deb78c1b1af35d46bf3fef07643a25ba7a1c5f1
naveen882/mysample-programs
/classandstaticmethod.py
2,569
4.75
5
""" Suppose we have a class called Math then nobody will want to create object of class Math and then invoke methods like ceil and floor and fabs on it.( >> Math.floor(3.14)) So we make them static. One would use @classmethod when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method. While using static you would want the behaviour to remain unchanged across subclasses http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner/31503491#31503491 Example: """ class Hero: @staticmethod def say_hello(): print("Helllo...") @classmethod def say_class_hello(cls): if(cls.__name__=="HeroSon"): print("Hi Kido") elif(cls.__name__=="HeroDaughter"): print("Hi Princess") class HeroSon(Hero): def say_son_hello(self): print("test hello") class HeroDaughter(Hero): def say_daughter_hello(self): print("test hello daughter") testson = HeroSon() testson.say_class_hello() testson.say_hello() testdaughter = HeroDaughter() testdaughter.say_class_hello() testdaughter.say_hello() print "============================================================================" """ static methods are best used when you want to call the class functions without creating the class object """ class A(object): @staticmethod def r1(): print "In r1" print A.r1() #In r1 a=A() a.r1() #In r1 class A(object): def r1(self): print "In r1" """ print A.r1() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method r1() must be called with A instance as first argument (got nothing instead) """ print "============================================================================" class dynamo(): @staticmethod def all_return_same(): print "static method" @classmethod def all_return_different(cls): print cls if cls.__name__ == 'A': print "1" elif cls.__name__ == 'B': print "2" else: print "3" class A(dynamo): pass class B(dynamo): pass d=dynamo() d.all_return_same() d.all_return_different() dynamo().all_return_same() dynamo().all_return_different() print "======" a=A() a.all_return_same() a.all_return_different() A.all_return_same() A.all_return_different() print "======" b=B() b.all_return_same() b.all_return_different() B.all_return_same() B.all_return_different() print "============================================================================"
true
fc8bde15b9c00120cb4d5b19920a58e288100686
CHemaxi/python
/003-python-modules/008-python-regexp.py
2,984
4.34375
4
""" MARKDOWN --- Title: python iterators and generators MetaDescription: python regular, expressions, code, tutorials Author: Hemaxi ContentName: python-regular-expressions --- MARKDOWN """ """ MARKDOWN # PYTHON REGULAR EXPRESSIONS BASICS * Regular Expressions are string patterns to search in other strings * PYTHON Regular Expressions, functionality is provided by the "re" MODULE * The "re" Module provides all the functions required to enable PYTHONs regular expressions * Regular expressions is all about matching a "pattern" in a "string" * **search()** function, returns true or false for the string found / not found * **findall()** function, returns a TUPLE of all occurrences of the pattern * **sub()** function, This is used to replace parts of strings, with a pattern * **split()** function, seperates a string by space or any dilimeter. MARKDOWN """ # MARKDOWN ``` ####################### # 1) search Function ####################### import re # Create a test string with repeating letters words test_string = "The Test string 123 121212 learnpython LEARNPYTHON a1b2c3" #Search for pattern: learnpython (in SMALL LETTERS) match = re.search(r'learnpython',test_string) if match: print("The word 'learnpython' is found in the string:", "\n", test_string) else: print("The word 'learnpython' is NOT found in the string:", "\n", test_string) # Search for more complicated patterns, search for 12*, where * # is wildcard character, match everything else after the pattern "12" match = re.search(r'12*',test_string) if match: print("The word '12*' is found in the string:", "\n", test_string) else: print("The word '12*' is NOT found in the string:", "\n", test_string) ######################## # 2) findall Function ######################## import re # Prints all the WORDS with a SMALL "t" in the test-string # The options are: # word with a "t" in between \w+t\w+, # OR indicated by the PIPE symbol | # word with a "t" as the last character \w+t, # OR indicated by the PIPE symbol | # word with a "t" as the first character t\w+, # Create a test string with repeating letters words test_string = "The Test string 123 121212 learnpython LEARNPYTHON a1b2c3" all_t = re.findall(r'\w+t\w+|\w+t|t\w+',test_string) # The re.findall returns a TUPLE and we print all the elements looping # through the tuple for lpr in all_t: print(lpr) ######################## # 3) sub Function ######################## import re # This is used to replace parts of strings, with a pattern string = "Learnpython good python examples" # Replace "good" with "great" new_string = re.sub("good", "great", string) print(string) print(new_string) ######################## # 4) split Function ######################## # The split Function splits a string by spaces import re words2list = re.split(r's','Learnpython good python examples') print(words2list) # Split a Comma Seperated String csv2list = re.split(r',','1,AAA,2000') print(csv2list) # MARKDOWN ```
true
bcd7c3ee14dd3af063a6fea74089b02bade44a1c
hussein343455/Code-wars
/kyu 6/Uncollapse Digits.py
729
4.125
4
# ask # You will be given a string of English digits "stuck" together, like this: # "zeronineoneoneeighttwoseventhreesixfourtwofive" # Your task is to split the string into separate digits: # "zero nine one one eight two seven three six four two five" # Examples # "three" --> "three" # "eightsix" --> "eight six" # "fivefourseven" --> "five four seven" # "ninethreesixthree" --> "nine three six three" # "fivethreefivesixthreenineonesevenoneeight" --> "five three def uncollapse(digits): x=["zero","one","two","three","four","five","six","seven","eight","nine"] for ind,i in enumerate(x): digits=digits.replace(i,str(ind)) return " ".join([x[int(i)] for i in digits])
true
64e73cb395d25b53a166a6e491e70a7834c96aee
sajjadm624/Bongo_Python_Code_Test_Solutions
/Bongo_Python_Code_Test_Q_3.py
2,330
4.1875
4
# Data structure to store a Binary Tree node class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right # Function to check if given node is present in binary tree or not def isNodePresent(root, node): # base case 1 if root is None: return False # base case 2 # if node is found, return true if root == node: return True # return true if node is found in the left subtree or right subtree return isNodePresent(root.left, node) or isNodePresent(root.right, node) def preLCA(root, lca, x, y): # case 1: return false if tree is empty if root is None: return False, lca # case 2: return true if either x or y is found # with lca set to the current node if root == x or root == y: return True, root # check if x or y exists in the left subtree left, lca = preLCA(root.left, lca, x, y) # check if x or y exists in the right subtree right, lca = preLCA(root.right, lca, x, y) # if x is found in one subtree and y is found in other subtree, # update lca to current node if left and right: lca = root # return true if x or y is found in either left or right subtree return (left or right), lca # Function to find lowest common ancestor of nodes x and y def LCA(root, x, y): # lca stores lowest common ancestor lca = None # call LCA procedure only if both x and y are present in the tree if isNodePresent(root, y) and isNodePresent(root, x): lca = preLCA(root, lca, x, y)[1] # if LCA exists, print it if lca: print("LCA is ", lca.data) else: print("LCA do not exist") if __name__ == '__main__': """ Construct below tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(8) root.right.left.right = Node(9) LCA(root, root.right.left, root.right.right) LCA(root, root.right, root.right.right)
true
92156b23818ebacfa3138e3e451e0ed11c0dd343
brianspiering/project-euler
/python/problem_025.py
1,139
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "1000-digit Fibonacci number", Problem 25 http://projecteuler.net/problem=25 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? """ num_digits = 1000 # 3 | 1000 def fib(): "A Fibonacci sequence generator." a, b = 0, 1 while True: a, b = b, a+b yield a def find_fib_term(num_digits): "Find the 1st fib term that has the given number of digits." f = fib() current_fib = f.next() counter = 1 while len(str(current_fib)) < num_digits: current_fib = f.next() counter += 1 return counter if __name__ == "__main__": print("The first term in the Fibonacci sequence to contain {} digits "\ "is the {}th term." .format(num_digits, find_fib_term(num_digits)))
true
5448d28db97a609cafd01e68c875affe1f97723c
brianspiering/project-euler
/python/problem_004.py
992
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "Largest palindrome product", aka Problem 4 http://projecteuler.net/problem=4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ low, high = 100, 999 # 10, 99 | 100, 999 def find_largest_palindrome(low, high): """(slightly) clever brute force method""" largest_palindrome = 0 for x in xrange(high,low-1,-1): for y in xrange(high,low-1,-1): if is_palindrome(x*y) and (x*y > largest_palindrome): largest_palindrome = x*y return largest_palindrome def is_palindrome(n): return str(n) == str(n)[::-1] if __name__ == "__main__": print("The largest palindrome made from the product of " + "two {0}-digit numbers is {1}." .format(len(str(low)), find_largest_palindrome(low, high)))
true
bd009da4e937a9cfc1c5f2e7940ca056c1969ae5
brianspiering/project-euler
/python/problem_024.py
1,489
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "Lexicographic permutations", Problem 24 http://projecteuler.net/problem=24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from __future__ import print_function import itertools # {range_argument: {place_number, place_name}} perm_picker = { 3: (6, 'sixth'), 10: (1000000, "millionth")} range_argument = 10 # 3 = demo; 10 def find_permutation(range_argument, place): "Find the specific (place) lexicographic permutation for give range argument." perm_tuple = list(itertools.permutations(xrange(range_argument)))[place-1] perm_string = "".join([str(n) for n in perm_tuple]) return perm_string if __name__ == "__main__": digits = range(range_argument) print("The {} lexicographic permutation of the digits ".format(perm_picker[range_argument][1], end="")) for digit in digits[:-2]: print("{}".format(digit), end=", ") print("{}".format(digits[-2]), end=", and ") print("{}".format(digits[-1]), end=" ") print("is {}.".format(find_permutation(range_argument, perm_picker[range_argument][0])))
true
5e2ae02f6553cbe7c31995ba76abf564c596d346
serenechen/Py103
/ex6.py
767
4.28125
4
# Assign a string to x x = "There are %d types of people." % 10 # Assign a string to binary binary = "binary" # Assign a string to do_not do_not = "don't" # Assign a string to y y = "Those who knows %s and those who %s." % (binary, do_not) # Print x print x # Print y print y # Print a string + value of x print "I said: %r." % x # Print a string + value of y print "I also said: '%s'." % y # Assign False to hilarious hilarious = False # Assign a string to joke_evaluation joke_evaluation = "Isn't that joke so funny?! %r" # Print a string + the value of hilarious print joke_evaluation % hilarious # Assign a string to w w = "This is the left side of..." # Assign a string to e e = "a string with a right side." # print a string concating w and e print w , e
true
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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