blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
650b2156b592b55355fcd441cdf6a29ba8760226
syurskyi/Python_Topics
/050_iterations_comprehension_generations/006_nested_comprehensions/examples/006_nested_comprehensions.py
1,954
4.75
5
# Nested Comprehensions # Just as with list comprehensions, we can nest generator expressions too: # A multiplication table: # Using a list comprehension approach first: # The equivalent generator expression would be: # We can iterate through mult_list: # But you'll notice that our rows are themselves generators! # o fully materialize the table we need to iterate through the row generators too: start = 1 stop = 10 mult_list = [ [i * j for j in range(start, stop+1)] for i in range(start, stop+1)] mult_list start = 1 stop = 10 mult_list = ( (i * j for j in range(start, stop+1)) for i in range(start, stop+1)) mult_list table = list(mult_list) table table_rows = [list(gen) for gen in table] table_rows # Nested Comprehensions # Of course, we can mix list comprehensions and generators. # In this modification, we'll make the rows list comprehensions, and retain the generator expression in the outer # comprehension: # Notice what is happening here, the table itself is lazy evaluated, i.e. the rows are not yielded until they # are requested - but once a row is requested, the list comprehension that defines the row will be entirely # evaluated at that point: start = 1 stop = 10 mult_list = ( [i * j for j in range(start, stop+1)] for i in range(start, stop+1)) for item in mult_list: print(item) # Let's try Pascal's triangle again: # Here's how we did it using a list comprehension: from math import factorial def combo(n, k): return factorial(n) // (factorial(k) * factorial(n-k)) size = 10 # global variable pascal = [ [combo(n, k) for k in range(n+1)] for n in range(size+1) ] # Let's try Pascal's triangle again: # # If we want to materialize the triangle into a list we'll need to do so ourselves: size = 10 # global variable pascal = ( (combo(n, k) for k in range(n+1)) for n in range(size+1) ) [list(row) for row in pascal]
true
f0deed5e91dc4476292f10ac0e544bd0a8290bb1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/746 Min Cost Climbing Stairs.py
1,291
4.125
4
#!/usr/bin/python3 """ On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. Note: cost will have a length in the range [2, 1000]. Every cost[i] will be an integer in the range [0, 999]. """ ____ t___ _______ L.. c_ Solution: ___ minCostClimbingStairs cost: L.. i.. __ i.. """ dp let F[i] be the cost to reach i-th stair F[i] = min F[i-2] + cost[i-2] F[i-1] + cost[i-1] """ n l..(cost) F [f__('inf') ___ _ __ r..(n+1)] F[0] 0 F[1] 0 ___ i __ r..(2, n+1 F[i] m..( F[i-2] + cost[i-2], F[i-1] + cost[i-1] ) r.. F[-1] __ _______ __ _______ ... Solution().minCostClimbingStairs([10, 15, 20]) __ 15
true
69fb9eab9782d4b53bbd781db80061561795fe8e
syurskyi/Python_Topics
/045_functions/013_switch_simulation/003.py
922
4.125
4
def add(x, to=1): return x + to def divide(x, by=2): return x / by def square(x): return x ** 2 def invalid_op(x): raise Exception("Invalid operation") def perform_operation(x, chosen_operation, operation_args=None): # If operation_args wasn't provided (i.e. it is None), set it to be an empty dictionary operation_args = operation_args or {} ops = { "add": add, "divide": divide, "square": square } chosen_operation_function = ops.get(chosen_operation, invalid_op) return chosen_operation_function(x, **operation_args) def example_usage(): x = 1 x = perform_operation(x, "add", {"to": 4}) # Adds 4 print(x) x = perform_operation(x, "add") # Adds 1 since that's the default for 'add' x = perform_operation(x, "divide", {"by": 2}) # Divides by 2 x = perform_operation(x, "square") # Squares the number example_usage()
true
be6d3b624bf38e6ed7cf8c93a26d4c6cb6cd7269
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+12 How to check if a point belongs to Circle.py
286
4.3125
4
_______ math x float(input("Insert point x: ")) y float(input("Insert point y: ")) r float(input("Insert the radius: ")) hypotenuse math.sqrt(pow(x,2) + pow(y,2)) __ hypotenuse < r: print("The point belongs to circle.") ____: print("The point does not belong to circle.")
false
0aa08a662cb93ae1b78a565535806c5f649c40c2
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/triangle_types_solution.py
645
4.125
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to check a triangle is equilateral, isosceles or scalene. # Note : # An equilateral triangle is a triangle in which all three sides are equal. # A scalene triangle is a triangle that has three unequal sides. # An isosceles triangle is a triangle with (at least) two equal sides. print("Input lengths of the triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) if x == y == z: print("Equilateral triangle") elif x != y != z: print("Scalene triangle") else: print("isosceles triangle")
true
9668ed9b59dffd211b71d671e99bff049ca83215
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/232 Implement Queue using Stacks.py
1,349
4.28125
4
""" Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). """ __author__ 'Daniel' c_ Queue: ___ - in_stk # list out_stk # list ___ push x """ :type x: int :rtype: None """ in_stk.a..(x) ___ pop """ :rtype: None """ __ n.. out_stk: w.... in_stk: out_stk.a..(in_stk.pop out_stk.p.. ) ___ peek """ :rtype: int """ __ n.. out_stk: w.... in_stk: out_stk.a..(in_stk.pop r.. out_stk[-1] ___ empty """ :rtype: bool """ r.. n.. out_stk a.. n.. in_stk
true
99e0d1b96397498ae343b4eae4e4b23307e59dbe
syurskyi/Python_Topics
/020_sequences/examples/ITVDN Python Essential 2016/12-mutable_sequences_methods.py
365
4.25
4
""" Примеры других общих для изменяемых последовательностей методов. """ sequence = list(range(10)) print(sequence) # Неполное копирование copy = sequence.copy() # copy = sequence[:] print(copy) # Разворот в обратном порядке sequence.reverse() print(sequence)
false
46b95cecb37be01d2c4ced998e143f9f08a7b9b2
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-13-convert-dict-to-namedtuple-json.py
2,029
4.1875
4
""" TASK DESCRIPTION: Write a function to convert the given blog dict to a namedtuple. Write a second function to convert the resulting namedtuple to json. Here you probably need to use 2 of the _ methods of namedtuple :) """ ____ c.. _______ n.. ____ c.. _______ O.. ____ d__ _______ d__ _______ j__ # Q: What is the difference between tuple and list? blog d.. name='PyBites', founders=('Julian', 'Bob'), started=d__ y.._2016, m.._12, d.._19), tags= 'Python', 'Code Challenges', 'Learn by Doing' , location='Spain/Australia', site='https://pybit.es') """ INITIAL CONSIDERATIONS: How could resulting JSON look like? Question is how to serialize datetime? j = { "name": "PyBites", "founders": ["Julian", "Bob"], "started": { "year": "2016", "month": "12", "day": "19" }, "tags": ["Python", "Code Challenges", "Learn by Doing"], "location": "Spain/Australia", "site": "https://pybit.es" } """ ### --------- My solution ------------- # define namedtuple here Blog n..('Blog', 'name founders started tags location site') ___ dict2nt(dict_ b Blog(dict_.g.. 'name'), dict_.g.. 'founders'), dict_.g.. 'started'), dict_.g.. 'tags'), dict_.g.. 'location'), dict_.g.. 'site' r.. b ___ nt2json(nt j__.d.. ) b ? ? # Q: How to serialize datetime object? # https://code-maven.com/serialize-datetime-object-as-json-in-python # https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable/36142844#36142844 print(j__.d..O..(b._asdict, default=s.., indent=4 ### ---------- PyBites original solution --------------- # define namedtuple here pybBlog n..('pybBlog', blog.keys # https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters ___ pyb_dict2nt(dict_ r.. pybBlog($$? ___ pyb_nt2json(nt nt ?._replace(started=s..(?.started r.. j__.d..?._asdict
true
1af8cd8a831f0b63b8c77d2ff35f4ec3e6a1b3f8
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 60 - MergeSortLists.py
1,158
4.15625
4
# Merge Sorted Lists # Question: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # Solutions: class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param two ListNodes # @return a ListNode def mergeTwoLists(self, l1, l2): dummy = ListNode(0) pointer = dummy while l1 !=None and l2 !=None: if l1.val<l2.val: pointer.next = l1 l1 = l1.next else: pointer.next = l2 l2 = l2.next pointer = pointer.next if l1 == None: pointer.next = l2 else: pointer.next = l1 return dummy.next def printll(self, node): while node: print ( node.val ) node = node.next if __name__ == '__main__': ll1, ll1.next, ll1.next.next = ListNode(2), ListNode(3), ListNode(5) ll2, ll2.next, ll2.next.next = ListNode(4), ListNode(7), ListNode(15) Solution().printll( Solution().mergeTwoLists(ll1,ll2) )
true
56ff56c9d7977a59184e97c87a15187edbd1a63f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/520 Detect Capital.py
1,228
4.375
4
#!/usr/bin/python3 """ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital if it has more than one letter, like "Google". Otherwise, we define that this word doesn't use capitals in a right way. Example 1: Input: "USA" Output: True Example 2: Input: "FlaG" Output: False Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. """ c_ Solution: ___ detectCapitalUse word: s..) __ b.. """ Two passes is easy How to do it in one pass """ __ n.. word: r.. T.. head_upper word[0].isupper() # except for the head has_lower F.. has_upper F.. ___ w __ word 1| __ w.isupper has_upper T.. __ has_lower o. n.. head_upper: r.. F.. ____ has_lower T.. __ has_upper: r.. F.. r.. T..
true
0e260d563115adc1074d6e6135c4d62085b1f48f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+13 How to create quadratic Equation.py
331
4.34375
4
____ math _______ sqrt x float(input("Insert x = ")) y float(input("Insert y = ")) z float(input("Insert z = ")) a y*y-4*x*z __ a>0: x1 (-y + sqrt(a))/(2*x) x2 (-y - sqrt(a))/(2*x) print("x1 = %.2f; x2 = %.2f" % (x1,x2)) ____ a__0: x1 -y/(2*x) print("x1 = %.2f" % x1) ____: print("No roots exist")
false
d30652b267569247f9d3c6a1f20ad03f3f902250
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTesting-master/Proj4/ListsAndTuples/listAndTuples.py
2,218
4.375
4
______ ___ ______ timeit # https://www.youtube.com/watch?v=NI26dqhs2Rk # Tuple is a smaller faster alternative to a list # List contains a sequence of data surrounded by brackets # Tuple contains a squence of data surrounded by parenthesis """ Lists can have data added, removed, or changed Tuples cannot change. Tuples can be made quickly. """ # List example prime_numbers _ [2, 3, 5, 7, 11, 13, 17] # Tuple example perfect_squares _ (1, 4, 9, 16, 25, 36) # Display lengths print("# Primes = ", le.(prime_numbers)) print("# Squares = ", le.(perfect_squares)) # Iterate over both sequences ___ p __ prime_numbers: print("Prime: ", p) ___ n __ perfect_squares: print("Square: ", n) print("") print("List Methods") print(dir(prime_numbers)) print(80*"-") print("Tuple methods") print(dir(perfect_squares)) print() print(dir(___)) print(help(___.getsizeof)) print() list_eg _ [1, 2, 3, "a", "b", "c", T.., 3.14159] tuple_eg _ (1, 2, 3, "a", "b", "c", T.., 3.14159) print("List size = ", ___.getsizeof(list_eg)) print("Tuple size = ", ___.getsizeof(tuple_eg)) print() list_test _ timeit.timeit(stmt_"[1, 2, 3, 4, 5]", number_1000000) tuple_test _ timeit.timeit(stmt_"(1, 2, 3, 4, 5)", number_1000000) print("List time: ", list_test) print("Tuple time: ", tuple_test) print() ## How to make tuples empty_tuple _ () test0 _ ("a") test1 _ ("a",) # To make a tuple with just one element you need to have a comma at the end test2 _ ("a", "b") test3 _ ("a", "b", "c") print(empty_tuple) print(test0) print(test1) print(test2) print(test3) print() # How to make tuples part 2 test1 _ 1, test2 _ 1, 2 test3 _ 1, 2, 3 print(test1) print(test2) print(test3) print() # (age, country, knows_python) survey _ (27, "Vietnam", T..) age _ survey[0] country _ survey[1] knows_python _ survey[2] print("Age =", age) print("Country =", country) print("Knows Python?", knows_python) print() survey2 _ (21, "Switzerland", F..) age, country, knows_python _ survey2 print("Age =", age) print("Country =", country) print("Knows Python?", knows_python) print() # Assigns string to variable country country _ ("Australia") # Here country is a tuple, and it doesnt unpack contents into variable country _ ("Australia",)
true
c035fcefec027a5b8e1c619b49d09c7c96cbc330
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-169-simple-length-converter.py
1,245
4.34375
4
''' Your task is to complete the convert() function. It's purpose is to convert centimeters to inches and vice versa. As simple as that sounds, there are some caveats: convert(): The function will take value and fmt parameters: value: must be an int or a float otherwise raise a TypeError fmt: string containing either "cm" or "in" anything else raises a ValueError. returns a float rounded to 4 decimal places. Assume that if the value is being converted into centimeters that the value is in inches and centimeters if it's being converted to inches. That's it! ''' ___ convert(value: f__, fmt: s..) __ f__: """Converts the value to the designated format. :param value: The value to be converted must be numeric or raise a TypeError :param fmt: String indicating format to convert to :return: Float rounded to 4 decimal places after conversion """ __ t..(value) __ i.. o. t..(value) __ f__: __ fmt.l.. __ "cm" o. fmt.l.. __ "in": __ fmt.l.. __ "cm": result value*2.54 r.. r..(result,4) ____ result value*0.393700787 r.. r..(result, 4) ____ r.. V... ____ r.. T.. print(convert(60.5, "CM"
true
4e4ffc46df598ca4b6990664d765f2ee36ca9c63
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.1. Listing 8.1. Create a shallow copy of the list.py
1,169
4.375
4
# -*- coding: utf-8 -*- x = [1, 2, 3, 4, 5] # Создали список # Создаем копию списка y = list(x) # или с помощью среза: y = x[:] # или вызовом метода copy(): y = x.copy() print(y) # [1, 2, 3, 4, 5] print(x is y) # Оператор показывает, что это разные объекты # False y[1] = 100 # Изменяем второй элемент print(x, y) # Изменился только список в перемеой y # ([1, 2, 3, 4, 5], [1, 100, 3, 4, 5]) x = [1, [2, 3, 4, 5]] # Создали вложенный список y = list(x) # Якобы сделали копию списка print(x is y) # Разные объекты # False y[1][1] = 100 # Изменяем элемент print(x, y) # Изменение затронуло переменную x!!! # ([1, [2, 100, 4, 5]], [1, [2, 100, 4, 5]])
false
0e1f60a4dd71d99753e8a19d3f767d8d2815615d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/768 Max Chunks To Make Sorted II.py
1,673
4.40625
4
#!/usr/bin/python3 """ This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8. Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array. What is the most number of chunks we could have made? Example 1: Input: arr = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. Example 2: Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. Note: arr will have length in range [1, 2000]. arr[i] will be an integer in range [0, 10**8]. """ ____ t___ _______ L.. ____ c.. _______ d.., d.. c_ Solution: ___ maxChunksToSorted arr: L.. i.. __ i.. """ not necessarily distinct sort and assign index For the smae element, the right ones should get larget assigned index """ A s..(arr) hm d..(d..) ___ i, e __ e..(A hm[e].a..(i) proxy # list ___ e __ arr: proxy.a..(hm[e].popleft ret 0 cur_max_idx 0 ___ i, e __ e..(proxy cur_max_idx m..(cur_max_idx, e) __ cur_max_idx __ i: ret += 1 r.. ret
true
17c9922315777a98beb9a4799bad497699ecd265
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/299/base_converter.py
859
4.5
4
# ___ convert number i.. base i.. 2 __ s.. # """Converts an integer into any base between 2 and 36 inclusive # # Args: # number (int): Integer to convert # base (int, optional): The base to convert the integer to. Defaults to 2. # # Raises: # Exception (ValueError): If base is less than 2 or greater than 36 # # Returns: # str: The returned value as a string # """ # __ (1 < ? < 37) a.. isi.. ? i.. # base_num "" # w.... ?>0 # dig i.. ?%? # __ ?<10 # b.. +_ s.. ? # ____ # b.. +_ c.. o.. 'A' +d.. - 10 #Using uppercase letters # ? //= ? # # b.. b.. ||-1 #To reverse the string # r.. ? # ____ n.. isi.. ? i.. # r.. T.. # ____ # r.. V... # # #print(convert(128, 5))
false
2a941e251d78633d70caf05e60efa864cc49aba9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/701 Insert into a Binary Search Tree.py
1,190
4.375
4
#!/usr/bin/python3 """ Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. For example, Given the tree: 4 / \ 2 7 / \ 1 3 And the value to insert: 5 You can return this binary search tree: 4 / \ 2 7 / \ / 1 3 5 This tree is also valid: 5 / \ 2 7 / \ 1 3 \ 4 """ # Definition for a binary tree node. c_ TreeNode: ___ - , x val x left N.. right N.. c_ Solution: ___ insertIntoBST root: TreeNode, val: i.. __ TreeNode: __ n.. root: r.. TreeNode(val) __ root.val < val: root.right insertIntoBST(root.right, val) ____ root.val > val: root.left insertIntoBST(root.left, val) ____ r.. r.. root
true
f50b7d8beae1763ff2665416301bec37eff8fc53
syurskyi/Python_Topics
/050_iterations_comprehension_generations/009_permutations/examples/009_permutations.py
1,745
4.46875
4
# Permutations # In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence # or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. # These differ from combinations, which are selections of some members of a set where order is disregarded. # We can create permutations of length n from an iterable of length m (n <= m) using the permutation function: # As you can see all the permutations are, by default, the same length as the original iterable. # We can create permutations of smaller length by specifying the r value: # The important thing to note is that elements are not 'repeated' in the permutation. # But the uniqueness of an element is not based on its value, but rather on its position in the original iterable. # This means that the following will yield what looks like the same permutations when considering the values of # the iterable: l1 = 'abc' list(itertools.permutations(l1)) list(itertools.permutations(l1, 2)) list(itertools.permutations('aaa')) list(itertools.permutations('aba', 2)) # Combinations # Combinations refer to the combination of n things taken k at a time without repetition. To refer to combinations in # which repetition is allowed, the terms k-selection,[1] k-multiset,[2] or k-combination with repetition are often used. # itertools offers both flavors - with and without replacement. # Let's look at a simple example with replacement first: # As you can see (4, 3) is not included in the result since, as a combination, it is the same as (3, 4) - # order is not important. list(itertools.combinations([1, 2, 3, 4], 2)) list(itertools.combinations_with_replacement([1, 2, 3, 4], 2))
true
c3cac517a34075d13cc9839c5aafffab20eefd1d
syurskyi/Python_Topics
/045_functions/007_lambda/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 67 sum_even_values.py
566
4.21875
4
# Sum Even Values Solution # # I define a function called sum_even_values which accepts any number of arguments, thanks to *args # I grab the even numbers using the generator expression (arg for arg in args if arg % 2 == 0) # (could also use a list comp) # I pass the even numbers I extracted into sum() and return the value # The default start value of sum() # is 0, so I don't have to do anything special to get it to return 0 if there are no even numbers! def sum_even_values(*args): return sum(arg for arg in args if arg % 2 == 0)
true
e68fa28abb8eb130145171dbbaadced13f473c6d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/953 Verifying an Alien Dictionary.py
1,996
4.21875
4
#!/usr/bin/python3 """ In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. Example 3: Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). Note: 1 <= words.length <= 100 1 <= words[i].length <= 20 order.length == 26 All characters in words[i] and order are english lowercase letters. """ ____ t___ _______ L.. c_ Solution: ___ isAlienSorted words: L..[s..], order: s..) __ b.. h # dict ___ i, c __ e..(order h[c] i ___ i __ r..(1, l.. ? __ cmp(words[i], words[i-1], h) __ -1: r.. F.. r.. T.. ___ cmp w1, w2, h ___ c1, c2 __ z..(w1, w2 __ h[c1] < h[c2]: r.. -1 ____ h[c1] > h[c2]: r.. 1 __ l..(w1) __ l..(w2 r.. 0 ____ l..(w1) > l..(w2 r.. 1 ____ r.. -1 __ _______ __ _______ ... Solution().isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz") __ T..
true
c7fde44dbdbdd8fbf0a8f75bc98819f46a6d2dd2
Nunziatellanicolepalarymzai/Python-104
/mean.py
883
4.375
4
# Python program to print # mean of elements # list of elements to calculate mean import csv with open('./height-weight.csv', newline='') as f: reader = csv.reader(f) #csv.reader method,reads and returns the current row and then moves to the next file_data = list(reader) #list(reader) adds the data to the list file_data.pop(0) #to remove the title from the data print(file_data) # sorting data to get the height of people. new_data=[] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(float(n_num)) #Then create a empty list named new_data . #Then use a for loop on file_data to get the elements inside the nested lists #and append them to the new_data list. # #getting the mean n = len(new_data) total =0 for x in new_data: total += x mean = total / n # print("Mean / Average is: " + str(mean))
true
34b74af222fda40f35d744e2909cde08df0f3092
ravis3517/i-neuron-assigment-and-project-
/i neuron_python_prog_ Assignment_3.py
1,845
4.34375
4
#!/usr/bin/env python # coding: utf-8 # 1. Write a Python Program to Check if a Number is Positive, Negative or Zero # In[25]: num = float(input("Enter a number: ")) if num >0: print("positive") elif num <0 : print("negative") else: print(" number is zero") # 2. Write a Python Program to Check if a Number is Odd or Even? # In[26]: num=int(input("enter the number:\n")) if (num %2==0): print("The number is even") else: print("the number is odd") # 3.Write a Python Program to Check Leap Year? # A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400 # In[27]: # To enter year by user year=int(input("Enter the year:\n")) # Leap Year Check if year % 4 == 0 and year % 100 != 0: print(year, "is a Leap Year") elif year % 100 == 0: print(year, "is not a Leap Year") elif year % 400 ==0: print(year, "is a Leap Year") else: print(year, "is not a Leap Year") # Write a Python Program to Check Prime Number? # In[28]: #test all divisors from 2 through n-1 (Skip 1 and n since prime number is divided by 1 and n ) num=10 for i in range(2,num): ## it will test till n-1 i.e till 9 if num % i == 0: print( num , " is Not prime") break else : print( num ," is a prime") # Write a Python Program to Print all Prime Numbers in an Interval of 1-10000? # In[29]: # Python program to print all # prime number in an interval # number should be greater than 1 first_number = 1 last_number = 10000 for i in range(first_number ,last_number +1): if i>1: for j in range(2,i): if i%j==0: break else: print(i)
true
07540d509c99f96db7fcc7f7362a36f5dc52d36d
bowie2k3/cos205
/COS-205_assignment4b_AJ.py
683
4.5
4
# Write a program that counts the number of words in a text file. # the program should print out [...] the number of words in the file. # Your program should prompt the user for the file name, which # should be stored at the same location as the program. # It should consider anything that is separated by white space or # new line on either side of a contiguous group of characters or # character as a word. def main(): fname = input("Please enter the filename: ") infile = open(fname, "r") data = infile.read() stripnl = data.replace("\n", " ") words = stripnl.split(" ") count = len(words) print("The number of words in the file is: ", count) main()
true
b6d35f31562d97ec2fe4c6d9a1d349d23a45e7ea
jmmalnar/python_projects
/primes.py
1,896
4.40625
4
import unittest # Find all the prime numbers less than a given integer def is_prime(num): """ Iterate from 2 up to the (number-1). Assume the number is prime, and work through all lower numbers. If the number is divisible by ANY of the lower numbers, then it's not prime """ prime_status = True # 1, by definition, is not a prime number, so lets account for that directly if num == 1: prime_status = False return prime_status for i in range(2, num): mod = num % i if mod == 0: prime_status = False break return prime_status def find_primes(num): primes = [] for n in range(1, num): prime_status = is_prime(n) if prime_status: primes.append(n) return primes ######## # TEST # ######## class IsPrimesTests(unittest.TestCase): def test_19_should_be_prime(self): """Verify that inputting a prime number into the is_prime method returns true""" self.assertEqual(is_prime(19), True) def test_20_should_not_be_primer(self): """Verify that inputting a non-prime number into the is_prime method returns false""" self.assertEqual(is_prime(20), False) def test_1_should_not_be_prime(self): """Verify that inputting 1 into the is_prime method returns false""" self.assertEqual(is_prime(1), False) class FindPrimesTests(unittest.TestCase): def test_primes_to_20(self): """Verify that all of the correct primes less than 20 are returned""" primes = find_primes(20) self.assertEqual(primes, [2, 3, 5, 7, 11, 13, 17, 19]) def test_1_should_not_be_prime(self): """Verify that nothing is returned when you try and find all primes under 1""" primes = find_primes(1) self.assertEqual(primes, []) if __name__ == '__main__': unittest.main()
true
69d63e236fd5585208ec5bebab45137c260c3562
lmhavrin/python-crash-course
/chapter-seven/deli.py
536
4.4375
4
# Exercise: 7-8 Deli # A for loop is useful for looping through a list # A while loop is useful for looping through a list AND MODIFYING IT sandwich_orders = ["turkey", "roast beef", "chicken", "BLT", "ham"] finished_sandwiches = [] while sandwich_orders: making_sandwich = sandwich_orders.pop() print("I made your " + making_sandwich + " sandwich.") finished_sandwiches.append(making_sandwich) print("\n Here are the list of sandwiches finished: ") for sandwich in finished_sandwiches: print("-" + sandwich.title())
true
637260eab712b7cca3c5f0f9e058fcd3639ffa96
bqr407/PyIQ
/bubble.py
1,671
4.15625
4
class Bubble(): """Class for bubble objects""" def __init__(self, id, x, y, x2, y2, value): """each bubble object has these values associated with it""" self.x = x self.y = y self.x2 = x2 self.y2 = y2 self.id = id self.value = value def getX(self): """returns x1 of tkinter shape""" return self.x def getY(self): """returns y1 of tkinter shape""" return self.y def getX2(self): """returns x2 pos of tkinter shape""" return self.x2 def getY2(self): """returns y2 of tkinter shape""" return self.y2 def getID(self): """returns unique object identifier""" return self.id def getValue(self): """returns value of the bubble""" return self.value class Choice(): """Class for choice objects""" def __init__(self, id, x, y, x2, y2, value): """each choice object has these values associated with it""" self.x = x self.y = y self.x2 = x2 self.y2 = y2 self.id = id self.value = value def getX(self): """returns x1 of tkinter shape""" return self.x def getY(self): """returns y1 of tkinter shape""" return self.y def getX2(self): """returns x2 pos of tkinter shape""" return self.x2 def getY2(self): """returns y2 of tkinter shape""" return self.y2 def getID(self): """returns unique object identifier""" return self.id def getValue(self): """returns answer the object represents""" return self.value
true
a72b8412d9b2ca109436ac39d7dc3dcc021a8d75
jsvn91/example_python
/eg/getting_max_from_str_eg.py
350
4.15625
4
# Q.24. In one line, show us how you’ll get the max alphabetical character from a string. # # For this, we’ll simply use the max function. # print (max('flyiNg')) # ‘y’ # # The following are the ASCII values for all the letters of this string- # # f- 102 # # l- 108 # # because y is greater amongst all y- 121 # # i- 105 # # N- 78 # # g- 103
true
5935356da274001c362f979a7405c61f71cdef0b
Zhaokun1997/2020T1
/comp9321/labs/week2/activity_2.py
1,596
4.4375
4
import sqlite3 import pandas as pd from pandas.io import sql def read_csv(csv_file): """ :param csv_file: the path of csv file :return: a dataframe out of the csv file """ return pd.read_csv(csv_file) def write_in_sqlite(data_frame, database_file, table_name): """ :param data_frame: the dataframe which must be written into the database :param database_file: where the database is stored :param table_name: the name of the table """ cnx = sqlite3.connect(database_file) # make a connection sql.to_sql(data_frame, name=table_name, con=cnx, index=True) def read_from_sqlite(database_file, table_name): """ :param database_file: where the database is stored :param table_name: the name of the table :return: a dataframe """ cnx = sqlite3.connect(database_file) return sql.read_sql('select * from ' + table_name, cnx) if __name__ == '__main__': table_name = "Demographic_Statistics" database_file = 'Demographic_Statistics.db' # name of sqlite db file that will be created csv_file = 'Demographic_Statistics_By_Zip_Code.csv' # read data from csv file print("Reading csv file...") loaded_df = read_csv(csv_file) print("Obtain data from csv file successfully...") # write data (read from csv file) to the sqlite database print("Creating database...") write_in_sqlite(loaded_df, database_file, table_name) print("Write data to database successfully...") # make a query print("Querying the database") queried_df = read_from_sqlite(database_file, table_name)
true
b5ef32acae6f59590e4cd373b2368eb4414bf12f
Sharonbosire4/hacker-rank
/Python/Algorithms/Warmup/Staircase/python_staircase/__main__.py
392
4.125
4
from __future__ import print_function import sys def staircase(height): lines = [] for n in range(height): string = '' for i in range(height): string += '#' if i >= n else ' ' lines.append(string) return reversed(lines) def main(): T = int(input()) for line in staircase(T): print(line) if __name__ == '__main__': main()
false
dc903ba5999763753228f8d9c2942718ddd3fe69
magicmitra/obsidian
/discrete.py
1,190
4.46875
4
#---------------------------------------------------------------------------------- # This is a function that will calculate the interest rate in a discrete manner. # Wirh this, interest is compounded k times a year and the bank will only add # interest to the pricipal k times a year. # The balance will then be returned. # Author: Erv #----------------------------------------------------------------------------------- from decimal import * constant_one = 1 # Formula : B(t) = P(1 + (r/k)) ** kt # B = balance # P = principal # r = interest rate # k = times compounded # t = time in years def discrete_calculate(): # prompt the user for values principal = float(input("Enter the principal amount: $")) time = int(input("Enter the time in years: ")) rate = float(input("Enter the interest rate in percentage form (Ex. 5.2): ")) compound = int (input("How many times a year is the interest compounded? ")) # calculate the balance rate = rate * 0.01 exponent = compound * time fraction = rate / compound meta_balance = (fraction + constant_one) ** exponent balance = principal * meta_balance balance = round(balance, 2) return "balance will be $" + str(balance)
true
097a63c09d55dc17208b953b948229ccc960c751
Onyiee/DeitelExercisesInPython
/circle_area.py
486
4.4375
4
# 6.20 (Circle Area) Write an application that prompts the user for the radius of a circle and uses # a method called circleArea to calculate the area of the circle. def circle_area(r): pi = 3.142 area_of_circle = pi * r * r return area_of_circle if __name__ == '__main__': try: r = int(input("Enter the radius of the circle: ")) area = circle_area(r) print(area) except ValueError: print(" You need to enter a value for radius")
true
bccd0d8074473316cc7eb69671929cf14ea5c1ac
Onyiee/DeitelExercisesInPython
/Modified_guess_number.py
1,472
4.1875
4
# 6.31 (Guess the Number Modification) Modify the program of Exercise 6.30 to count the number of guesses # the player makes. If the number is 10 or fewer, display Either you know the secret # or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret! # If the player makes more than 10 guesses, display You should be able to do better! Why should it # take no more than 10 guesses? Well, with each “good guess,” the player should be able to eliminate # half of the numbers, then half of the remaining numbers, and so on. from random import randint count = 1 def ten_or_less_message(count): if count == 10: return "Aha! You know the secret!" random_message = randint(1, 2) if random_message == 1: return "You got lucky!" if random_message == 2: return "You know the secret" def greater_than_ten_message(): return "You should be able to do better!" def modified_guess_game(guessed_number): global count random_number = randint(1, 10) guessed_number = int(guessed_number) if guessed_number == random_number and count <= 10: print(ten_or_less_message(count)) if guessed_number == random_number and count > 10: print(greater_than_ten_message()) count += 1 if guessed_number != random_number: modified_guess_game(input("Guess a number between 1 and 10: ")) print(modified_guess_game(input("Guess a number between 1 and 10: ")))
true
3b26b40c9619c6b0eee0a36096688aeb57819f10
Subharanjan-Sahoo/Practice-Questions
/Problem_34.py
810
4.15625
4
''' Single File Programming Question Your little brother has a math assignment to find whether the given number is a power of 2. If it is a power of 2 then he has to find the sum of the digits. If it is not a power of 2, then he has to find the next number which is a power of 2. He asks for your help to validate his work. But you are already busy playing video games. Develop a program so that your brother can validate his work by himself. Example 1 Input 64 Output Yes 10 Example 2 Input 133 Output NO ''' def math(input1): if (int(input1) & (int(input1) - 1)) == 0 :#% 2 == 0: sumyes = 0 print('Yes') for i in range(len(input1)): sumyes = int(input1[i]) + sumyes print(sumyes) else: print('NO') input1 = input() math(input1)
true
0bbb5802a3cfb9cd06a9a458bc77403689dad0ca
Subharanjan-Sahoo/Practice-Questions
/Problem_33.py
1,040
4.375
4
''' Write a program to calculate and return the sum of distances between the adjacent numbers in an array of positive integers Note: You are expected to write code in the find TotalDistance function only which will receive the first parameter as the number of items in the array and second parameter as the array itself. You are not required to take input from the console Example Finding the total distance between adjacent items of a list of 5 numbers Input input1: 5 input2: 10 11 7 12 14 Output 12 Explanation The first parameter (5) is the size of the array. Next is an array of integers. The total of distances is 12 as per the calculation below 11-7-4 7-12-5 12-14-2 Total distance 1+4+5+2= 12 ''' def findTotalDistance(input1): input2 = list(map(int,input().strip().split(" ")))[:input1] sum = 0 for i in range(input1): for j in range(input1): if i+1 == j: sum = (abs(input2[i] - input2[j])) + sum return sum input1 = int(input()) print(findTotalDistance(input1))
true
97c1bac183bf1c744eb4d1f05b6e0253b1455f10
Subharanjan-Sahoo/Practice-Questions
/Problem_13.py
733
4.21875
4
''' Write a function to find all the words in a string which are palindrome Note: A string is said to be a palindrome if the reverse of the string is the same as string. For example, "abba" is a palindrome, but "abbe" is not a palindrome. Input Specification: input1: string input2: Length of the String Output Specification: Retum the number of palindromes in the given string Example 1: inputt: this is level 71 input2: 16 Output 1 ''' def palondrom(input1): input2 =list(input("input the string: ").strip().split(" "))[:input1] count = 0 for i in input2: if i == i[::-1]: count = count + 1 print(count) input1 =int(input("Enter the number of Word: ")) palondrom(input1)
true
d30504a329fd5bcb59a284b5e28b89b6d21107e3
lada8sztole/Bulochka-s-makom
/1_5_1.py
479
4.1875
4
# Task 1 # # Make a program that has some sentence (a string) on input and returns a dict containing # all unique words as keys and the number of occurrences as values. # a = 'Apple was sweet as apple' # b = a.split() a = input('enter the string ') def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print(word_count(a))
true
cdc0c71ee2fd47586fca5c145f2c38905919cff5
lada8sztole/Bulochka-s-makom
/1_6_3.py
613
4.25
4
# Task 3 # # Words combination # # Create a program that reads an input string and then creates and prints 5 random strings from characters of the input string. # # For example, the program obtained the word ‘hello’, so it should print 5 random strings(words) # that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ … # # Tips: Use random module to get random char from string) import random from itertools import permutations a = input('sentence ') b = list(permutations(a)) i = 0 while i<5: print(''.join(b[random.randint(0, len(b))])) i+=1
true
5438b1928dc780927363d3d7622ca0d00247a5c2
malay190/Assignment_Solutions
/assignment9/ass9_5.py
599
4.28125
4
# Q.5- Create a class Expenditure and initialize it with expenditure,savings.Make the following methods. # 1. Display expenditure and savings # 2. Calculate total salary # 3. Display salary class expenditure: def __init__(self,expenditure,savings): self.expenditure=expenditure self.savings=savings def total_salary(self): print("your expenditure is ",self.expenditure) print("your saving is",self.savings) salary=self.expenditure+self.savings print("your salary is",salary) a=expenditure(int(input("enter your expenditure:")),int(input("enter your savings:"))) a.total_salary()
true
d4c987322a7e4c334bfb78920c52009101a1ba13
malay190/Assignment_Solutions
/assignment6/ass6_4.py
291
4.15625
4
#Q.4- From a list containing ints, strings and floats, make three lists to store them separately l=[1,'a',2,3,3.2,5,8.2] li=[] lf=[] ls=[] for x in l: if type(x)==int: li.append(x) elif type(x)==float: lf.append(x) elif type(x)==str: ls.append(x) print(li) print(lf) print(ls)
false
72a8086b765c8036b7f30853e440550a020d7602
bradger68/daily_coding_problems
/dailycodingprob66.py
1,182
4.375
4
"""Assume you have access to a function toss_biased() which returns 0 or 1 with a probability that's not 50-50 (but also not 0-100 or 100-0). You do not know the bias of the coin. Write a function to simulate an unbiased coin toss. """ import random unknown_ratio_heads = random.randint(1,100) unknown_ratio_tails = 100-unknown_ratio_heads def coin_toss(tosses): heads_count = 0 tails_count = 0 weighted_probabilities = unknown_ratio_heads * ['Heads'] + unknown_ratio_tails * ['Tails'] for x in range(tosses): toss = random.choice(weighted_probabilities) if toss == 'Heads': heads_count += 1 else: tails_count += 1 ratio_tails = (tails_count / tosses) * 100 ratio_heads = (heads_count / tosses) * 100 print(str(heads_count) + " of the " + str(tosses) + " tosses were heads. That is " + str(ratio_heads) + " percent.") print(str(tails_count) + " of the " + str(tosses) + " tosses were tails. That is " + str(ratio_tails) + " percent.") print("The unknown probability of getting heads was " + str(unknown_ratio_heads) +". How close were you?") coin_toss(10000)
true
68c281e253778c4c3640a5c67d2e7948ca8e150a
farahhhag/Python-Projects
/Grade & Attendance Calculator (+Data Validation).py
2,363
4.21875
4
data_valid = False while data_valid == False: grade1 = input("Enter the first grade: ") try: grade1 = float(grade1) except: print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.") continue if grade1 <0 or grade1 > 10: print("Grade should be in between 0 to 10") continue else: data_valid = True data_valid = False while data_valid == False: grade2 = input("Enter the second grade: ") try: grade2 = float(grade2) except: print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.") continue if grade2 <0 or grade2 > 10: print("Grade should be in between 0 to 10") continue else: data_valid = True data_valid = False while data_valid == False: total_class = input("Enter the number of total class: ") try: total_class = int(total_class) except: print("Invalid input. Only numbers are accepted.") continue if total_class <= 0: print("The number of total class can't be less than 0") continue else: data_valid = True data_valid = False while data_valid == False: absences = input("Enter the number of total absences: ") try: absences = int(absences) except: print("Invalid input. Only numbers are accepted.") continue if absences <=0 or absences > total_class: print("The number of absences can't be less than 0 or greater than the number of total classes") continue else: data_valid = True avg_grade = (grade1 + grade2) / 2 attendance = (total_class - absences) / total_class print("Average Grade:", round(avg_grade, 2)) print("Attendance Rate:", str(round((attendance * 100),2))+"%") if (avg_grade >= 6.0 and attendance >= 0.8): print("The student has been approved") elif(avg_grade < 6.0 and attendance < 0.8): print("The student has failed because the attendance rate is lower than 80% and the average grade is lower than 6.0") elif(attendance >= 0.8): print("The student has failed because the average grade is lower than 6.0") else: print("The student has failed because the attendance rate is lower than 80%")
true
6e85b53b38083b361d3d6d3a43b2b6fbc9d82ba9
farahhhag/Python-Projects
/Age Comparison.py
226
4.21875
4
my_age = 26 your_age = int( input("Please type your age: ") ) if(my_age > your_age): print("I'm older than you") elif(my_age == your_age): print("We are the same age") else: print("You're older than me")
false
c68084826badc09dd3f037098bfcfbccb712ee15
kayazdan/exercises
/chapter-5.2/ex-5-15.py
2,923
4.40625
4
# Programming Exercise 5-15 # # Program to find the average of five scores and output the scores and average with letter grade equivalents. # This program prompts a user for five numerical scores, # calculates their average, and assigns letter grades to each, # and outputs the list and average as a table on the screen. # define the main function # define local variables for average and five scores # Get five scores from the user # find the average by passing the scores to a function that returns the average # display grade and average information in tabular form # as score, numeric grade, letter grade, separated by tabs # display a line of underscores under this header # print data for all five scores, using the score, # with the result of a function to determine letter grade # display a line of underscores under this table of data # display the average and the letter grade for the average # Define a function to return the average of 5 grades. # This function accepts five values as parameters, # computes the average, # and returns the average. # define a local float variable to hold the average # calculate the average # return the average # Define a function to return a numeric grade from a number. # This function accepts a grade as a parameter, # Uses logical tests to assign it a letter grade, # and returns the letter grade. # if score is 90 or more, return A # 80 or more, return B # 70 or more, return C # 60 or more, return D # anything else, return F # Call the main function to start the program def main(): average = 0 score1 = 0 score2 = 0 score3 = 0 score4 = 0 score5 = 0 score1 = int(input("Score one: ")) score2 = int(input("Score two: ")) score3 = int(input("Score three: ")) score4 = int(input("Score four: ")) score5 = int(input("Score five: ")) find_average(score1, score2, score3, score4, score5) average = find_average(score1, score2, score3, score4, score5) get_letter_grade(average) letter_grade = get_letter_grade(average) print(" ") print("Average Grade: ", '\t', "Letter Grade: ") print("__________________________________________") print(average, '\t', " ", letter_grade) def find_average(score1, score2, score3, score4, score5): average = 0.0 all_score = score1 + score2 + score3 + score4 + score5 average = all_score/5 return average def get_letter_grade(average): if average >= 90: return "A" elif average >= 80: return "B" elif average >= 70: return "C" elif average >= 60: return "D" else: return "F" main()
true
ed61c43c7ab9b7ea26b890a00a08d2ed52ba3e47
kayazdan/exercises
/chapter-3/exercise-3-1.py
1,209
4.65625
5
# Programming Exercise 3-1 # # Program to display the name of a week day from its number. # This program prompts a user for the number (1 to 7) # and uses it to choose the name of a weekday # to display on the screen. # Variables to hold the day of the week and the name of the day. # Be sure to initialize the day of the week to an int and the name as a string. # Get the number for the day of the week. # be sure to format the input as an int nmb_day = input("What number of the day is it?: ") int_nmb_day = int(nmb_day) # Determine the value to assign to the day of the week. # use a set of if ... elif ... etc. statements to test the day of the week value. if int_nmb_day == 1: print("Monday") elif int_nmb_day == 2: print("Tuesday") elif int_nmb_day == 3: print("Wednesday") elif int_nmb_day == 4: print("Thursday") elif int_nmb_day == 5: print("Friday") elif int_nmb_day == 6: print("Saturday") elif int_nmb_day == 7: print("Sunday") else: print("Out of range") # use the final else to display an error message if the number is out of range. # display the name of the day on the screen.
true
ebd7d39e55aa5a0200a680629a31442a9795ba72
suman9868/Python-Code
/class.py
863
4.125
4
""" this is simple program in python for oops implementation submitted by : suman kumar date : 1 january 2017 time : 9 pm """ class Employee: emp_count = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.emp_count = Employee.emp_count + 1 def count_emp(self): #print "total employee ", Employee.emp_count print "total employee %d " %Employee.emp_count # both line works def emp_details(self): print "name ", self.name print "salary ", self.salary emp1 = Employee("raju",10000) emp2 = Employee("kaju",20000) emp3 = Employee("maju",30000) emp1.name = "sumti" #del emp1.salary #delete salary attribute of emp1 print Employee.emp_count emp1.count_emp() emp2.count_emp() #print emp1.name emp1.emp_details() emp2.emp_details()
false
77f27e01be7161901f28d68801d67c3d1e1e8c83
Nikola011s/portfolio
/work_with_menus.py
2,539
4.6875
5
#User enters n, and then n elements of the list #After entering elements of the list, show him options #1) Print the entire list #2) Add a new one to the list #3) Average odd from the whole list #4) The product of all elements that is divisible by 3 or by 4 #5) The largest element in the list #6) The sum of those that is higher than the average of the whole list # User choose an option and based on that option you print n = int(input("Enter list lenth: ")) list_elements = [] for i in range(n): number = int(input("Enter number:")) list_elements.append(number) print(list_elements) while True: print(""" 1) Print the entire list 2) Add a new one to the list 3) Average odd from the whole list 4) The product of all elements that is divisible by 3 or by 4 5) The largest element in the list 6) The sum of those that is higher than the average of the whole list 0) Exit program """) option = int(input("Choose an option:")) if option == 0: print("End of the line") exit(1) elif option == 1: print(list_elements) elif option == 2: number = int(input("Enter new element to the list: ")) list_elements.append(number) elif option == 3: sum = 0 counter = 0 lenth_list = len(list_elements) for i in range(lenth_list): if list_elements[i] % 2 != 0: sum = sum + list_elements[i] counter = counter + 1 if counter != 0: average = sum / counter print(" Average odd from the whole list is {average}") else: print("No odd elements") elif option == 4: product = 1 for i in range(n): if list_elements[i] % 3 == 0 or list_elements[i] % 4 == 0: product = product * list_elements[i] print("Product is {product}") elif option == 5: maximum = list_elemens[0] for number in list_elements: if number > maximum: maximum = number print(maximum) elif option == 6: sum_higher = 0 sum = 0 for number in list_elements: sum += number average = sum / len(list_elements) for number in list_elements: if number > average: sum_higher += number print(sum_higher)
true
ba564bd38231baac9bec825f4eaac669c00ff6a5
desingh9/PythonForBeginnersIntoCoding
/Day6_Only_Answers/Answer_Q2_If_Else.py
353
4.21875
4
#1.) Write a program to check whether a entered character is lowercase ( a to z ) or uppercase ( A to Z ). chr=(input("Enter Charactor:")) #A=chr(65,90) #for i in range(65,90) if (ord(chr) >=65) and (ord(chr)<=90): print("its a CAPITAL Letter") elif (ord(chr>=97) and ord(chr<=122)): print ("its a Small charector") else: print("errrrr404")
true
dea948a20c0c3e4ad252eb28988f2ae935e79046
desingh9/PythonForBeginnersIntoCoding
/Q4Mix_A1.py
776
4.28125
4
#1) Write a program to find All the missing numbers in a given integer array ? arr = [1, 2,5,,9,3,11,15] occurranceOfDigit=[] # finding max no so that , will create list will index till max no . max=arr[0] for no in arr: if no>max: max=no # adding all zeros [0] at all indexes till the maximum no in array for no in range(0,max+1): occurranceOfDigit.append(0) # original array print(arr) # marking index in occurrance array to 1 for all no in original array. marking indexes that are present in original array for no in arr: occurranceOfDigit[no]=1 print("Missing elements are: ") i=1 # accesing all indexes where values are zero. i.e no. are not present in array while i<=max: if occurranceOfDigit[i]==0: print(i,end=" ") i+=1
true
152920d0c317bb528f19c39d56dfead8bc0d9952
EvertonAlvesGomes/Curso-Python
/listas.py
1,525
4.5625
5
### listas.py ## Estudando listas em Python moto = ['Rodas','Motor','Relação','Freios'] # lista inicial moto.append('Embreagem') # adicona elemento ao final da lista moto.insert(2, 'Transmissão') # insere o elemento 'Transmissão' na posição 2, # sem substituir o elemento atual dessa posição. # O elementos subsequentes serão deslocados para a direita moto.remove('Motor') # remove o elemento, deslocando para a esquerda os elementos seguintes # Alternativa: del moto[1] -> remove o elemento da posição 1 # Alternativa 2: moto.pop(1) -> remove o elemento da posição 1 # Observação: o método pop geralmente é utilizado para remover o último elemento da lista. moto.pop() # remove o último elemento # --------------- print(moto) # ---------- valores = [8,2,4,10,1,3,6] valores.sort() # organiza em ordem crescente valores.sort(reverse=True) # organiza em ordem decrescente print(valores) print(f'A lista valores tem {len(valores)} elementos.') # Uma maneira elegante de declarar uma lista é pelo construtor list(), # uma vez que list é objeto da classe de mesmo nome. # Exemplo: lista = list() # cria uma lista vazia # Atribuição de listas em Python: # a = [2, 4, 5, 9] # b = a # as listas b, a são interligadas. Qualquer alteração em uma das listas altera a outra # b = a[:] # o conteúdo de a é copiado para b, sem estabeler uma relação entre elas.
false
be06a70e1eef93540bb5837ae43220ae29d7d7fa
veetarag/Data-Structures-and-Algorithms-in-Python
/Interview Questions/Rotate Image.py
592
4.125
4
def rotate(matrix): l = len(matrix) for row in matrix: print(row) print() # Transpose the Matrix for i in range(l): for j in range(i, l): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for row in matrix: print(row) print() # Row Reverse for i in range(l): for j in range(l//2): matrix[i][l-j-1], matrix[i][j] = matrix[i][j], matrix[i][l-j-1] for row in matrix: print(row) return matrix # Rotate the image 90 degree clockwise rotate([ [1,2,3], [4,5,6], [7,8,9] ])
true
219d0100864e2e8b1777cb935a9b5e61ca52ef8a
osalpekar/RSA-Encrypter
/rsa.py
620
4.15625
4
''' Main function instantiates the Receiver class Calls encrypt and decrypt on user-inputted message ''' from receiver import Receiver def main(): message = raw_input("Enter a message you would like to encrypt/decrypt: ") receiver = Receiver() encrypted_message = receiver.encrypt(message) decrypted_message = receiver.decrypt(encrypted_message) print "Your original message was: " + message print "Your encrypted message is: " + ''.join([str(num) for num in encrypted_message]) print "Your decrpyted message is: " + decrypted_message return if __name__ == "__main__": main()
true
8858083bbd2a1ff2bd63cdde91462bc1efbeb4c7
HenriqueSilva29/infosatc-lp-avaliativo-06
/atividade 1.py
624
4.1875
4
#O método abs () retorna o valor absoluto do número fornecido. # Exemplo : # integer = -20 #print('Absolute value of -20 is:', abs(integer)) numero=0 lista = [2,4,6,8] def rotacionar(lista, numero): numero=int(input("Algum número positivo ou negativo :")) if numero >= 0: for i in range(numero): ultimoNumero = lista.pop(-1) lista.insert(0, ultimoNumero) else: for i in range(abs(numero)): primeiroNumero = lista.pop(0) lista.append(primeiroNumero) return rotacionar(lista, numero) print (lista)
false
69da6775487c8b27702302afdc60c7ceef53f148
NoroffNIS/Code-2019-Week-5
/16 - Documenting_Practical.py
2,826
4.1875
4
class Car: def __init__(self): self.type = "" self.model = "" self.wheels = 4 self.doors = 3 self.seets = 5 def print_model(self): print("This car is a {model}: {type}, Wow!".format(model=self.model,type= self.type)) def print_space(self): print("The car has {0} doors and {1} seets".format(self.doors, self.seets)) def __str__(self): return """ This car is a {s.model}: {s.type}, Wow! The car has {s.doors} doors and {s.seets} seets""".format(s=self) class BMW(Car): def __init__(self, **arg): Car.__init__(self) self.model = "BMW" self.type = "{} Series".format(arg.get("type")) self.doors = arg.get("doors") self.fuel = arg.get("fuel") class Mercedes(Car): def __init__(self, **arg): Car.__init__(self) self.model = "Mercedes" self.type = "{} Class".format(arg.get("type")) self.doors = arg.get("doors") self.fuel = arg.get("fuel") class Fuel: def __init__(self, **arg): self.liters = arg.get("liters") self.type = arg.get("type") def __str__(self): return """It uses {s.liters}L of {s.type}¢.""".format(s=self) class CarFactory: def __init__(self, **kwargs): self.car = kwargs.get("type")(type=kwargs.get("car_type"),doors=kwargs.get("doors"),fuel=Fuel(liters=kwargs.get("liters"),type=kwargs.get("fuel_type"))) def get_car(self): """Returns a Mercedes""" return self.car class CarStore: inventory = [] def __init__(self, **kwargs): self._car_factory = CarFactory(type=kwargs.get("type"), car_type=kwargs.get("car_type"),doors=kwargs.get("doors"),liters=kwargs.get("liters"),fuel_type=kwargs.get("fuel_type")) self.inventory.append(self._car_factory.get_car()) def show_car(self, car=None): if not car: car = self._car_factory.get_car() print(car) print(car.fuel) def show_inventory(self): for i in self.inventory: self.show_car(i) def __str__(self): return "".join([str(i) for i in self.inventory]) store = CarStore(type=Mercedes, car_type= "E", doors=2, liters = 2,fuel_type = "Disel") store2 = CarStore(type=Mercedes, car_type= "C", doors=4, liters = 2,fuel_type = "Disel") store3 = CarStore(type=BMW, car_type="1", doors= 3, liters= 2.5, fuel_type = "Gasoline") store.show_inventory() print("\n","-"*100) class Lada(Car): def __init__(self, **arg): Car.__init__(self) self.model = "Lada" self.type = "{}".format(arg.get("type")) self.doors = arg.get("doors") self.fuel = arg.get("fuel") store = CarStore(type=Lada, car_type="VAZ-2107",doors=2,liters=1.2,fuel_type="Octane Gasoline") store.show_inventory()
false
bd42b81d7d008bab809a365e99c4d410876b453c
rocky-recon/mycode
/farm_challange.py
704
4.5
4
#!/usr/bin/env python3 # Old Macdonald had a farm. Farm. farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}] # Write a for loop that returns all the animals from the NE Farm! #for s in farms: # print(farms[1]) yuck= ["carrots","celery", "apples", "bananas", "oranges"] num= input(""" Choose a farm by number: 0. NE Farm 1. W Farm 2. SE Farm >""") for critters in farms[num].get("agriculture"): if critters not in yuck: print(critters)
false
c758366a22e1ab6095ada44d366394395b6797bf
MieMieSheep/Learn-Python-By-Example
/python3/2 - 数据类型与变量/1.py
1,684
4.375
4
#encoding:utf-8 #!/user/bin/python ''' 前面两行#encoding:utf-8 #!/user/bin/python 的作用: 第一行:#encoding:utf-8 用于声明当前文件编码,防止程序乱码出现 第二行: #!/user/bin/python 用于声明python文件 养成良好编码习惯,敲代码时习惯添加这两行注释。 ''' ''' 变量:仅仅使用字面意义上的常量很快就会引发烦恼—— 我们需要一种既可以储存信息 又可以对它们进行操作的方法。 这是为什么要引入 变量 。 变量就是我们想要的东西——它们的值可以变化, 即你可以使用变量存储任何东西。变量只是你的计算机中存储信息的一部分内存。 与字面意义上的常量不同,你需要一些能够访问这些变量的方法,因此你给变量名字。 ''' #数据类型 int num1 = 50 #这里的num1就是一个变量名 可以自己更换变量名 num2 = 60 #去除前面的注释即可 解除封印~~ 查看代码效果 #print('num1 = ',num1) #print('num2 = ',num2) #print(num1+num2) #str类型的数据(字符类型) name = "Jaydenchan" str1 = "My name is " #去除前面的注释即可 解除封印~~ 查看代码效果 #print(str1 + name) # 字符串中 可用 + 号作为连接符 可以理解为把两串字符串成一串 #布尔类型数据 ''' 布尔类型数据可以理解为一个开关 True即为 开 False即为 关 详细的用法后面会解答 ''' a = True b = False #字典,列表,元组 我们会后面再讲 #现在,我们只介绍一些简单的数据类型 '''自己尝试修改程序,看看有没有什么新发现'''
false
db6b22e0d6c051b508dbdff4cab4babcbd867c6e
ua-ants/webacad_python
/lesson01_old/hw/script3.py
485
4.15625
4
while True: print('To quit program enter "q"') val1 = input('Enter a first number: ') if val1 == 'q': break val2 = input('Enter a second number: ') if val2 == 'q': break try: val1 = int(val1) val2 = int(val2) except ValueError: print('one of entered value is not integer') continue if val1 > val2: print(val1-val2) elif val1 < val2: print(val1+val2) else: print(val1)
true
265a3d593c820ebc354bcd04b15da5489ba51f6d
ua-ants/webacad_python
/lesson02_old/hw/script3.py
336
4.3125
4
# given array: arr = [1, 3, 'a', 5, 5, 3, 'a', 5, 3, 'str01', 6, 3, 'str01', 1] # task 3. Удалить в массиве первый и последний элементы. def remove_last_and_first(arr): del arr[0] del arr[-1] return arr print("Array before: ", arr) print("Array after: ", remove_last_and_first(arr))
false
23b0bf7288672ad81c27e25daec3a6afe4ca707f
ThallesTorres/Curso_Em_Video_Python
/Curso_Em_Video_Python/ex096.py
654
4.25
4
# Ex: 096 - Faça um programa que tenha uma função chamada área(), que receba # as dimensões de um terreno retangular(largura e comprimento) e mostre a # área do terreno. def area(a, b): print("\n--Dados finais:") print(f"Área de um terreno {a}x{b} é de {a * b}m².") print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 096 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') print("--Preencha:") l = float(input("Largura (m): ")) c = float(input("Comprimento (m): ")) area(l, c) print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Obrigado pelo uso! --Desenvolvido por Thalles Torres -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
false
1814f6fbdbf5a3c28a73efa51323d42a0a3e2fe9
ThallesTorres/Curso_Em_Video_Python
/Curso_Em_Video_Python/ex095.py
2,045
4.1875
4
# Ex: 095 - Aprimore o DESAFIO 093 para que ele funcione com vários jogadores, # incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 095 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') jogadores = list() resp = 's' while resp == 's': jogador = dict() print("--Preencha o formulário abaixo: ") jogador['Nome'] = input("Nome: ").title().strip() jogador['Partidas'] = int(input("Partidas jogadas: ")) if jogador['Partidas'] > 0: gols = list() total_gols = 0 for partida in range(0, jogador['Partidas']): x = int(input(f"Gols na {partida + 1}ª partida: ")) gols.append(x) total_gols += x jogador['Gols'] = gols jogador['Total_Gols'] = total_gols jogadores.append(jogador) del(jogador) while True: resp = input("\nDeseja adicionar mais um jogador? [S/N] ").lower() if resp == 's' or resp == 'n': print() break print("--Valor Inválido") print(f"--Dados finais \n {'n°':<5}{'Nome':<10}{'Partidas':<10}{'Gols':<10}{'Total':<10}") for num, v in enumerate(jogadores): print(f" {num:<5}{v['Nome']:<10}{v['Partidas']:<10}{str(v['Gols']):<10}{v['Total_Gols']:<10}") while True: resp = int(input("\nMostrar algum jogador? [999 para sair] ")) if resp == 999: break if resp not in range(0, len(jogadores)): print("--Valor Inválido") else: print(f"\n--O jogador {jogadores[resp]['Nome']} jogou {jogadores[resp]['Partidas']} partidas.\n") print(''.join(f'=> Na {cont+1}° partida, fez {gols} gols.\n' for cont, gols in enumerate(jogadores[resp]['Gols']))) print(f"--Dando um total de {jogadores[resp]['Total_Gols']} gols.") print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Obrigado pelo uso! --Desenvolvido por Thalles Torres -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
false
84d6bfe4e4fe89f4a08d2e8ca73631d950c86fcf
KarthickM89/basicPython
/loops.py
236
4.28125
4
#for i in [0, 1, 2, 3, 4, 5]: # print(i) #for i in range(6): # print(i) # Defining names names = ["karthick", "kaviya", "kavinilaa"] name1 = "kannan" # Looping and Printing for name in names: print(name) for n in name1: print(n)
false
96b4061196c3dc36646c9f3b88a004890db47edf
KostaSav/Tic-Tac-Toe
/console.py
1,231
4.1875
4
########## Imports ########## import config # Initialize the Game Board and print it in console board = [ [" ", "|", " ", "|", " "], ["-", "+", "-", "+", "-"], [" ", "|", " ", "|", " "], ["-", "+", "-", "+", "-"], [" ", "|", " ", "|", " "], ] ## Print the Game Board in console def print_board(): for line in board: for char in line: print(char, end="") print() ## Reset the board to empty def reset_board(): for line in board: for i in range(len(line)): if line[i] == "X" or line[i] == "O": line[i] = " " ## Draw the played piece on the board def place_piece(pos, first_player_turn, piece): if first_player_turn: config.player1_positions.add(pos) else: config.player2_positions.add(pos) if pos == 1: board[0][0] = piece elif pos == 2: board[0][2] = piece elif pos == 3: board[0][4] = piece elif pos == 4: board[2][0] = piece elif pos == 5: board[2][2] = piece elif pos == 6: board[2][4] = piece elif pos == 7: board[4][0] = piece elif pos == 8: board[4][2] = piece elif pos == 9: board[4][4] = piece
true
c03e3f76b690c87b8939f726faeac5c0d6107b93
Anwar91-TechKnow/PythonPratice-Set2
/Swipe two numbers.py
1,648
4.4375
4
# ANWAR SHAIKH # Python program set2/001 # Title: Swipe two Numbers '''This is python progaramm where i am doing swapping of two number using two approches. 1. with hardcorded values 2. Values taken from user also in this i have added how to use temporary variable as well as without delcaring temporary varibale. ============================================================ ''' # Please commentout the rest approches and use only one approch at the time of execution. import time #1. with hardcorded values num1=55 num2=30 print("Value of num1 before swapping : ",num1) print("Value of num2 before swapping : ",num2) time.sleep(2) #now here created temporary varibale to store value of numbers. a = num1 #it will store value in variable called a num1=num2 #here num2 will replace with num1 value num2=a #here num2 value swapped with num1 which #swapping is done print("Value of num1 After swapping : ",num1) print("Value of num2 after swapping : ",num2) time.sleep(3) #second example: #2. Values taken from user #we can take input from user also num_one=input("Enter first number : ") num_two=input("Enter Second number : ") time.sleep(3) b = num_one num_one=num_two num_two=b print("Value of first number After swapping : ",num_one) print("Value of second number swapping : ",num_two) time.sleep(3) #without delcaring temporary variable. num1=20 num2=5 print("Value of num1 before swapping : ",num1) print("Value of num2 before swapping : ",num2) time.sleep(3) num1,num2=num2,num1 #swapping is done print("Value of num1 After swapping : ",num1) print("Value of num2 after swapping : ",num2) time.sleep(3)
true
e1c4f9c2034a1fa3f8f4535e68f394af0e6f2d7d
paulo-sk/python-crash-course-2019
/c6_dictionaries/loop_dictionaries.py
943
4.3125
4
""" vc pode dar loop em dicionarios de 3 formas: loop nas keys: loop nos values: loop nos key , values: """ favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } # loop nas keys; for name in favorite_languages.keys(): print(name.title()) # loop nos values: for languages in favorite_languages.values(): print(languages.title()) # loop key, values: for name,language in favorite_languages.items(): print(f"Name:{name},language:{language}") # loop de forma ordenada (essa esta em ordem alfabetica) for name in sorted(favorite_languages.keys()): print(name.title()) # verificando e imprimindo valores nao repetidos com metodo set() # perceba que no dicionario, o valor python aparece 2 vezes, com o set so vai mostrar valores unicos print("\nLiguagens de programaçao mencionadas:") for language in set(favorite_languages.values()): print(language)
false
a5dcfbb508c112b3184f4c65c0425573b4c2c043
paulo-sk/python-crash-course-2019
/c10_files_and_exceptions/exceptions/division_calculator.py
805
4.28125
4
# programa tenta fazer o que vc quer, se nao de, ele manda uma mensagem de erro mais amigavel # e o programa continua rodando try: print(5/0) except ZeroDivisionError: print("You can't divide by zero.") print("\n-------------------------------------------------------") # outro exemplo print("\nGive me 2 numbers, and i'll divide them:") print("Enter 'q' to quit.\n") while True: first_number = input("Enter the first number> ") if first_number == 'q': break second_number = input("Enter the second number> ") if second_number == 'q': break # try-except-else block try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by zero!") else: print(f"answer: {answer}")
false
87d19ef751bdb5bd5e305d8a18c634ebf08c39a8
VladSquared/SoftUni---Programming-Basics-with-Python
/01. Problem.py
805
4.125
4
email = input() while True: cmd = input() if cmd == "Complete": break elif "Make Upper" in cmd: email = email.upper() print(email) elif "Make Lower" in cmd: email = email.lower() print(email) elif "GetDomain" in cmd: count = int(cmd.split()[1]) print(email[-count:]) elif "GetUsername" in cmd: if not "@" in email: print(f"The email {email} doesn't contain the @ symbol.") continue at_char = int(email.index("@")) print(email[:at_char]) elif "Replace" in cmd: char = cmd.split()[1] email = email.replace(char, "-") print(email) elif "Encrypt" in cmd: for char in email: print(ord(char), end=" ")
false
cb49784d1f95205fb3152e9e3ff05f2bc585ff17
rakeshsingh/my-euler
/euler/utils.py
1,623
4.25
4
#!/usr/bin/python import math from math import gcd def my_gcd(a, b): ''' returns: str gcd for two given numbers ''' if a == b or b == 0: return a elif a > b: return gcd(a-b, b) else: return gcd(b-a, a) def lcm(a, b): '''''' return a * b // gcd(a, b) def get_prime_factors(n): ''' returns a list of prime factors of a number ''' factors = [] for i in get_next_prime(1): if n % i == 0: factors.append(i) if i > n: return factors def is_prime(n): ''' Check whether a number is prime or not ''' if n > 1: if n == 2: return True if n % 2 == 0: return False for current in range(3, int(math.sqrt(n) + 1), 2): if n % current == 0: return False return True else: return False def get_next_prime(n): while True: n = n+1 if is_prime(n): return n def get_primes(n): while True: if is_prime(n): yield n n = n+1 def fibonacci_generator(): """Fibonacci numbers generator""" a, b = 1, 1 while True: yield a a, b = b, a + b def fibonacci(n): """ Fibonacci numbers returns: int """ counter = 0 for fib in fibonacci_generator(): if counter == n: return fib counter = counter + 1 def hello(): print('Hello World !') if __name__ == '__main__': for i in fibonacci_generator(): print(i) if i > 150: break
false
981c2e7984813e752f26a37f85ca2bec74470b40
mon0theist/Automate-The-Boring-Stuff
/Chapter 04/commaCode2.py
1,183
4.375
4
# Ch 4 Practice Project - Comma Code # second attempt # # Say you have a list value like this: # spam = ['apples', 'bananas', 'tofu', 'cats'] # # Write a function that takes a list value as an argument and returns a string # with all the items separated by a comma and a space, with and inserted before # the last item. For example, passing the previous spam list to the function # would return 'apples, bananas, tofu, and cats'. But your function should be # able to work with any list value passed to it. # # Couldn't figure this out on my own, had to look at the solution from my last attempt, # which I'm also pretty sure I didn't figure out on my own, pretty sure I # copy+pasted from somewhere # # I can read it and understand why it works, but writing it from scratch is a whole # different thing :'( def commaList(listValue): counter = 0 newString = '' while counter < len(listValue)-1: newString += str(listValue[counter]) + ', ' counter += 1 print(newString + 'and ' + str(listValue[counter])) # print for testing return newString + 'and ' + str(listValue[counter]) spamList = ['apples', 'bananas', 'tofu', 'cats'] commaList(spamList)
true
3c2f7e0a16640fdb7e72795f10824fcce5370199
mon0theist/Automate-The-Boring-Stuff
/Chapter 07/strongPassword.py
1,249
4.375
4
#! /usr/bin/python3 # ATBS Chapter 7 Practice Project # Strong Password Detection # Write a function that uses regular expressions to make sure the password # string it is passed is strong. # A strong password has: # at least 8 chars - .{8,} # both uppercase and lowercase chars - [a-zA-Z] # test that BOTH exist, not just simply re.IGNORECASE # at least one digit - \d+ # You may need to test the string against multiple regex patterns to validate its strength. # NOTES # Order shouldn't matter, & operator? # Test: if regex search/findall != None # seperate Regex for reach requirement? import re def pwStrength(pw): if eightChars.search(pw) and oneUpper.search(pw) and oneLower.search(pw) and oneDigit.search(pw) != None: print('Your password meets the requirements.') else: print('Your password does not meet the requirements.') eightChars = re.compile(r'.{8,}') # tests for 8 or more chars oneUpper = re.compile(r'[A-Z]+') # test for 1+ upper oneLower = re.compile(r'[a-z]+') # test for 1+ lower oneDigit = re.compile(r'\d+') # test for 1+ digit # Wanted to combine all into single Regex if possible but can't figure it out password = input('Please enter the password you want to test: ') pwStrength(password)
true
f950540f7fd7e20c033f7b562a41156f5c43a1f2
ZYSLLZYSLL/Python
/代码/code/day06/Demo07_列表常用操作_修改_复制.py
1,104
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/1/11 15:35 # @Author : ZY # @File : Demo07_列表常用操作_修改_复制.py # @Project : code # 修改指定位置的数据 # a = [1, [1, 2, 3], 1.23, 'abc'] # a[1] = '周宇' # print(a) # 逆置:reverse() # a = [1, [1, 2, 3], 1.23, 'abc'] # a.reverse() # print(a) # # print(a[::-1]) # 排序 sort() 默认升序 # a = [1, 3, 5, 8, 0, 3] # a.sort() # print(a) # 降序 # a = [1, 3, 5, 8, 0, 3] # a.sort(reverse = True) # print(a) # copy() 复制,浅复制 # a = [1, [1, 2, 3], 1.23, 'abc'] # b = a.copy() # print(b) # print(id(a[1])) # print(id(b[1])) # print(id(a[0])) # print(id(b[0])) # 二维数组 # a = [1, [1, 2, 3], 1.23, 'abc'] # print(a[1][2]) # 深复制: # from copy import deepcopy # a = [1, [1, 2, 3], 1.23, 'abc'] # b = deepcopy(a) # print(id(a[1])) # print(id(b[1])) # print(id(a[0])) # print(id(b[0])) a = [1, [1, 2, 3], 1.23, 'abc'] b = a.copy() b[1] = a[1].copy() print(id(a[1])) print(id(b[1])) print(id(a)) print(id(b)) ''' 浅复制:对于可变类型没有完全复制 深复制:全部复制 '''
false
cf1e3aa630ec34233b352168bd4b0818565883cb
sofianguy/skills-dictionaries
/test-find-common-items.py
1,040
4.5
4
def find_common_items(list1, list2): """Produce the set of common items in two lists. Given two lists, return a list of the common items shared between the lists. IMPORTANT: you may not not 'if ___ in ___' or the method 'index'. For example: >>> sorted(find_common_items([1, 2, 3, 4], [1, 2])) [1, 2] If an item appears more than once in both lists, return it each time: >>> sorted(find_common_items([1, 2, 3, 4], [1, 1, 2, 2])) [1, 1, 2, 2] (And the order of which has the multiples shouldn't matter, either): >>> sorted(find_common_items([1, 1, 2, 2], [1, 2, 3, 4])) [1, 1, 2, 2] """ common_items_list = [] for item1 in list1: for item2 in list2: if item1 == item2: common_items_list.append(item1) #add item1 to new list return common_items_list print find_common_items([1, 2, 3, 4], [1, 2]) print find_common_items([1, 2, 3, 4], [1, 1, 2, 2]) print find_common_items([1, 1, 2, 2], [1, 2, 3, 4])
true
bf2a05fff10cf1fa6a2d0e5591da851b22069a78
adamny14/LoadTest
/test/as2/p4.py
219
4.125
4
#------------------------------ # Adam Hussain # print a square of stars for n #------------------------------ n = input("Enter number n: "); counter = 1; while counter <= n: print("*"*counter); counter = counter +1;
false
d00c727795694f3d0386699e15afeb5cb4484f89
VictoriaAlvess/LP-Python
/exercicio5.py
565
4.40625
4
''' 5) Escreva um programa que receba três números quaisquer e apresente: a) a soma dos quadrados dos três números; b) o quadrado da soma dos três números.''' import math print("Digite o primeiro número: ") num1 = float(input()) print("Digite o segundo número: ") num2 = float(input()) print("Digite o terceiro número: ") num3 = float(input()) somaA = math.pow(num1,2)+ math.pow(num2,2)+ math.pow(num3, 2) print("A soma dos quadrados dos três números é: ", somaA) somaB = math.pow(somaA,2) print("O quadrado da soma dos três números é: ", somaB)
false
d77e3f0c1b69178d36d43f767e4e12aed8a821da
Laishuxin/python
/2.thread/3.协程/6.create_generator_send启动.py
742
4.3125
4
# 生成器是特殊的迭代器 # 生成器可以让一个函数暂停,想执行的时候执行 def fibonacci(length): """创建一个financci的生成器""" a, b = 0, 1 current_num = 0 while current_num < length: # 函数中由yield 则这个不是简单的函数,而是一个生成器模板 print("111") ret = yield a print("222") print(">>>>ret>>>>", ret) a, b = b, a+b # print(a, end=",") current_num += 1 obj = fibonacci(10) ret = next(obj) print(ret) ret = next(obj) print(ret) # 第一次最好不用send启动 # ret = obj.send("hhhhh") # send里面的参数当作结论传递给 yield的返回值 # print(ret)
false
fbb4ce33a955eec2036211a7421950f027330a0b
l3ouu4n9/LeetCode
/algorithms/7. Reverse Integer.py
860
4.125
4
''' Given a 32-bit signed integer, reverse digits of an integer. E.g. Input: 123 Output: 321 Input: -123 Output: -321 Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' import sys class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ s = str(x) if(s[0] == '-'): s = '-' + s[1::][::-1] else: s = s[::-1] while(len(s) > 1 and s[0] == '0'): s = s[1::] if(int(s) >= 2 ** 31 or int(s) < (-2) ** 31): return 0 else: return int(s)
true
4f85b8be417d4253520781c0f99e31af282d60b7
sjtrimble/pythonCardGame
/cardgame.py
2,811
4.21875
4
# basic card game for Coding Dojo Python OOP module # San Jose, CA # 2016-12-06 import random # to be used below in the Deck class function # Creating Card Class class Card(object): def __init__(self, value, suit): self.value = value self.suit = suit def show(self): print self.value + " " + self.suit # Creating Deck Class class Deck(object): def __init__(self): self.cards = [] self.get_cards() # running the get_card method defined below to initiate with a full set of cards as your deck def get_cards(self): suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs'] values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] for suit in suits: # iterating through the suits for value in values: # iterating through each value newcard = Card(value, suit) # creating a newcard variable with the class Card and passing the iterations from the for loop self.cards.append(newcard) # adding the newly created card of Card class and adding it to the cards variable within the deck class object/instance def show(self): for card in self.cards: card.show() # calling the Card class' show method (see above in Card class section) - this is okay because the item it's iterating through it of the Card class def shuffle(self): random.shuffle(self.cards) # using random.shuffle method - import random above needs to be set before using def deal(self): return self.cards.pop() # returning the removed last value (a card of class Card) of the cards variable # Creating Player Class class Player(object): def __init__(self, name): self.hand = [] self.name = name def draw_cards(self, number, deck): # also need to pass through the deck here so that the player can have cards deal to them from that deck of class Deck if number < len(deck.cards):# to ensure that the amount of cards dealt do not exceed how many cards remain in a deck for i in range (number): # iterating through the cards in the deck self.hand.append(deck.deal()) # appending it to the player's hand variable set above print "Sorry, the deck is out of cards" def show(self): for card in self.hand: card.show() # calling the Card class' show method (see above in Card class section) - this is okay because the item it's iterating through it of the Card class # Sample Order of Process mydeck = Deck() # create a new deck with Deck class mydeck.shuffle() # shuffle the deck player1 = Player('Bob') # create a new player player1.draw_cards(5, mydeck) # draw 5 card from the mydeck deck created player1.show() # show the player's hand of cards that has been drawn
true
6e2fd2cc56821e6aeb9ac0beb5173a9d57c03f67
ericd9799/PythonPractice
/year100.py
421
4.125
4
#! /usr/bin/python3 import datetime now = datetime.datetime.now() year = now.year name = input("Please enter your name: ") age = int(input("Please enter your age: ")) yearsToHundred = 100 - age turnHundred = int(year) + yearsToHundred message = name + " will turn 100 in the year "+ str(turnHundred) print(message) repeat = int(input("Please enter integer to repeat message: ")) print(repeat * (message + "\n"))
true
1b6d711b5078871fca2de4fcf0a12fc0989f96e4
ericd9799/PythonPractice
/modCheck.py
497
4.125
4
#! /usr/bin/python3 modCheck = int(input("Please enter an integer: ")) if (modCheck % 4) == 0: print(str(modCheck) + " is a multiple of 4") elif (modCheck % 2) == 0: print(str(modCheck) + " is even") elif (modCheck % 2) != 0: print(str(modCheck) + " is odd") num, check = input("Enter 2 numbers:").split() num = int(num) check = int(check) if num % check == 0: print(str(check) + " divides evenly into " + str(num)) else: print(str(check) + " does not divide evenly into " + str(num))
true
68097abbf240ee911dfd9cf5d8b1cc60dedb6bf8
EraSilv/day2
/day5_6_7/practice.py
2,677
4.3125
4
# calculation_to_seconds = 24 * 60 * 60 calculation_to_hours = 24 # print(calculation_to_seconds) name_of_unit = "hours" #VERSION 1: # print(f"20 days are {20 * 24 * 60 * 60} seconds") # print(f"35 days are {35 * 24 * 60 * 60} seconds") # print(f"50 days are {50 * 24 * 60 * 60} seconds") # print(f"110 days are {110 * 24 * 60 * 60} seconds") #VERSION2: # print(f"20 days are {20 * calculation_to_seconds} {name_of_unit}") # print(f"35 days are {35 * calculation_to_seconds} {name_of_unit}") # print(f"50 days are {50 * calculation_to_seconds} {name_of_unit}") # print(f"110 days are {110 * calculation_to_seconds} {name_of_unit}") #VERSION3: # print(f"30 days are {30 * calculation_to_seconds} {name_of_unit}") # print(f"90 days are {90 * calculation_to_seconds} {name_of_unit}") # print(f"180 days are {180 * calculation_to_seconds} {name_of_unit}") # print(f"365 days are {365 * calculation_to_seconds} {name_of_unit}") ######------------------------------------------------------------------------------------------------------------------------- def days_to_units(num_of_days): #----------- line 52------ exchanged-------- # print(num_of_days > 0) #for true false # if num_of_days > 0: # print(f"{num_of_days} days are {num_of_days * calculation_to_hours} {name_of_unit}") return(f"{num_of_days} days are {num_of_days * calculation_to_hours} {name_of_unit}") # elif num_of_days == 0: # return('u entered a 0, please enter a valid positive number!') # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # days_to_units(31 , 'Awesome!') # days_to_units(35 , 'Looks Good!') # days_to_units(13) # days_to_units(90) # days_to_units(365) # user_input = input('Hey user, enter a number of days and i will convert it to hours!:\n') # if user_input.isdigit(): # user_input_number = int(user_input) # calculated_value = days_to_units(user_input_number) # print(calculated_value) # else: # print('Ur input is not a valid number. Dont ruin my programm!') # --------------------------------------------------------------------------------- def validate_and_execute(): if user_input.isdigit(): user_input_number = int(user_input) if user_input_number > 0: calculated_value = days_to_units(user_input_number) print(calculated_value) elif num_of_days == 0: print('u entered a 0, please enter a valid positive number!') else: print('Ur input is not a valid number. Dont ruin my programm!') user_input = input('Hey user, enter a number of days and i will convert it to hours!:\n') validate_and_execute()
false
4e8737d284c7cf01dea8dd82917e1fc787216219
EraSilv/day2
/day5_6_7/day7.py
879
4.125
4
# password = (input('Enter ur password:')) # if len(password) >= 8 and 8 > 0: # print('Correct! ') # print('Next----->:') # else: # print('Password must be more than 8!:') # print('Try again!') # print('Create a new account ') # login = input('login:') # email = input('Your e-mail:') # print('Choose correct password.') # password = (input('Enter ur password:')) # if len(password) >= 8 and 8 > 0: # print('Correct! ') # print('Next----->:') # else: # print('Password must be more than 8!:') # print('Try again!') # print('-----------------ENTER-------------------') # log = input('login or e-mail: ') # pas = input('password: ') # if login==log and password==pas: # print(' Entrance is successfully competed! ') # else: # print('password or login is incorrect! ') # print('Try after a few minutes! ')
true
76f09844a2ee8abc1ebb5d7be2432a9f7b568a93
Aayushi-Mittal/Udayan-Coding-BootCamp
/session3/Programs-s3.py
648
4.3125
4
""" a = int(input("Enter your value of a: ") ) b = int(input("Enter your value of b: ") ) print("Adding a and b") print(a+b) print("Subtract a and b") print(a-b) print("Multiply a and b") print(a*b) print("Divide a and b") print(a/b) print("Remainder left after dividing a and b") print(a%b) # Program 2 name=input("Enter your name") print("Hello "+name) # Program 3 c = int(input("Enter your value of c: ") ) print(c%10) """ # Program 4 signal=input("Enter the color of the signal : ") if(signal=="red") : print("STOP!") elif(signal=="yellow") : print("WAIT!") elif(signal=="green") : print("GO!") else : print("invalid choice")
false
3253b6843f4edd1047c567edc5a1d1973ead4b00
watson1227/Python-Beginner-Tutorials-YouTube-
/Funtions In Python.py
567
4.21875
4
# Functions In Python # Like in mathematics, where a function takes an argument and produces a result, it # does so in Python as well # The general form of a Python function is: # def function_name(arguments): # {lines telling the function what to do to produce the result} # return result # lets consider producing a function that returns x^2 + y^2 def squared(x, y): result = x**2 + y**2 return result print(squared(10, 2)) # A new function def born (country): return print("I am from " + country) born("greensboro")
true
de12c3cb06a024c01510f0cf70e76721a80d506e
ytlty/coding_problems
/fibonacci_modified.py
1,049
4.125
4
''' A series is defined in the following manner: Given the nth and (n+1)th terms, the (n+2)th can be computed by the following relation Tn+2 = (Tn+1)2 + Tn So, if the first two terms of the series are 0 and 1: the third term = 12 + 0 = 1 fourth term = 12 + 1 = 2 fifth term = 22 + 1 = 5 ... And so on. Given three integers A, B and N, such that the first two terms of the series (1st and 2nd terms) are A and B respectively, compute the Nth term of the series. Input Format You are given three space separated integers A, B and N on one line. Input Constraints 0 <= A,B <= 2 3 <= N <= 20 Output Format One integer. This integer is the Nth term of the given series when the first two terms are A and B respectively. Note Some output may even exceed the range of 64 bit integer. ''' import sys from math import pow a,b,n = tuple(map(int, input().split())) #print(a,b,n) nums = [] nums.append(a) nums.append(b) n_2 = a n_1 = b res = 0 for x in range(2, n): res = n_1*n_1 + n_2 n_2 = n_1 n_1 = res print(res)
true
f69783e7a620ca692a6b6213f16ef06b491b35e5
lily-liu-17/ICS3U-Assignment-7-Python-Concatenates
/concatenates.py
883
4.3125
4
#!/usr/bin/env python3 # Created by: Lily Liu # Created on: Oct 2021 # This program concatenates def concatenate(first_things, second_things): # this function concatenate two lists concatenated_list = [] # process for element in first_things: concatenated_list.append(element) for element in second_things: concatenated_list.append(element) return concatenated_list def main(): concatenated_list = [] # input user_first_things = input("Enter the things to put in first list (no spaces): ") user_second_things = input("Enter the things to put in second list (no spaces): ") # output print("") concatenated_list = concatenate(user_first_things, user_second_things) print("The concatenated list is {0} ".format(concatenated_list)) print("") print("Done.") if __name__ == "__main__": main()
true
2015152c0424d7b45235cefa678ea2cb90523132
ChiselD/guess-my-number
/app.py
401
4.125
4
import random secret_number = random.randint(1,101) guess = int(input("Guess what number I'm thinking of (between 1 and 100): ")) while guess != secret_number: if guess > secret_number: guess = int(input("Too high! Guess again: ")) if guess < secret_number: guess = int(input("Too low! Guess again: ")) if guess == secret_number: print(f"You guessed it! I was thinking of {secret_number}.")
true
ae9e8ccfee70ada5d6f60a9e8a16f3c2204078ca
OmarSamehMahmoud/Python_Projects
/Pyramids/pyramids.py
381
4.15625
4
height = input("Please enter pyramid Hieght: ") height = int(height) row = 0 while row < height: NumOfSpace = height - row - 1 NumOfStars = ((row + 1) * 2) - 1 string = "" #Step 1: Get the spaces i = 0 while i < NumOfSpace: string = string + " " i += 1 #step 2: Get the stars i = 0 while i < NumOfStars: string = string + "*" i +=1 print(string) row += 1
true
b746c7e3d271187b42765b9bf9e748e79ba29eca
fortunesd/PYTHON-TUTORIAL
/loops.py
792
4.40625
4
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a set, or a string). students = ['fortunes', 'abdul', 'obinaka', 'amos', 'ibrahim', 'zaniab'] # simple for loop for student in students: print(f'i am: {student}') #break for student in students: if student == 'odinaka': break print(f'the student is: {student}') #continue for student in students: if student == 'odinaka': continue print(f'the people included: {students}') #range for person in range(len(student)): print(f'number: {person}') # custom range for n in range(0, 12): print(f'number: {n}') # while loops excute a set of statements as long as a condition is true. count = 0 while count < 10: print(f'count: {count}') count += 1
true
6d3f673aad4128477625d3823e3cf8688fc89f2f
CollinNatterstad/RandomPasswordGenerator
/PasswordGenerator.py
814
4.15625
4
def main(): #importing necessary libraries. import random, string #getting user criteria for password length password_length = int(input("How many characters would you like your password to have? ")) #creating an empty list to store the password inside. password = [] #establishing what characters are allowed to be chosen. password_characters = string.ascii_lowercase + string.ascii_uppercase + string.digits #for loop to iterate over the password_length choosing a character at random from the pool of choices in password_characters. for x in range (password_length): password.append(random.choice(password_characters)) #printing the password to the terminal. print("".join(password)) if __name__ == "__main__": main()
true
2b33a5ed96a8a8c320432581d71f2c46b2a3998a
laufzeitfehlernet/Learning_Python
/math/collatz.py
305
4.21875
4
### To calculate the Collatz conjecture start = int(input("Enter a integer to start the madness: ")) loop = 1 print(start) while start > 1: if (start % 2) == 0: start = int(start / 2) else: start = start * 3 + 1 loop+=1 print(start) print("It was in total", loop, "loops it it ends!")
true
dfa330f673a2b85151b1a06ca63c3c78214c722e
joq0033/ass_3_python
/with_design_pattern/abstract_factory.py
2,239
4.25
4
from abc import ABC, abstractmethod from PickleMaker import * from shelve import * class AbstractSerializerFactory(ABC): """ The Abstract Factory interface declares a set of methods that return different abstract products. These products are called a family and are related by a high-level theme or concept. Products of one family are usually able to collaborate among themselves. A family of products may have several variants, but the products of one variant are incompatible with products of another. """ @abstractmethod def create_serializer(self): pass class ConcretePickleFactory(AbstractSerializerFactory): """ Concrete Factories produce a family of products that belong to a single variant. The factory guarantees that resulting products are compatible. Note that signatures of the Concrete Factory's methods return an abstract product, while inside the method a concrete product is instantiated. """ def create_serializer(self): return MyPickle('DocTestPickle.py', 'test') class ConcreteShelfFactory(AbstractSerializerFactory): """ Concrete Factories produce a family of products that belong to a single variant. The factory guarantees that resulting products are compatible. Note that signatures of the Concrete Factory's methods return an abstract product, while inside the method a concrete product is instantiated. """ def create_serializer(self): return Shelf('source_file') def test_serializers(factory): """ The client code works with factories and products only through abstract types: AbstractFactory and AbstractProduct. This lets you pass any factory or product subclass to the client code without breaking it. """ serialize = factory.create_serializer() serialize.make_data() serialize.unmake_data() if __name__ == "__main__": """ The client code can work with any concrete factory class. """ print("Client: Testing client code with the first factory type: MyPickle") test_serializers(ConcretePickleFactory())
true
1af1818dfe2bfb1bab321c87786ab356f7cff2d4
rahulrsr/pythonStringManipulation
/reverse_sentence.py
241
4.25
4
def reverse_sentence(statement): stm=statement.split() rev_stm=stm[::-1] rev_stm=' '.join(rev_stm) return rev_stm if __name__ == '__main__': m=input("Enter the sentence to be reversed: ") print(reverse_sentence(m))
true
590419d3a0fa5cbf2b1d907359a22a0aa7fe92b5
kopelek/pycalc
/pycalc/stack.py
837
4.1875
4
#!/usr/bin/python3 class Stack(object): """ Implementation of the stack structure. """ def __init__(self): self._items = [] def clean(self): """ Removes all items. """ self._items = [] def push(self, item): """ Adds given item at the top of the stack. """ self._items.append(item) def pop(self): """ Returns with removing from the stack the first item from the top of the stack. """ return self._items.pop() def peek(self): """ Returns the first item from the top of the stack. """ return self._items[len(self._items) - 1] def is_empty(self): """ Returns True if stack is empty, False otherwise. """ return self._items == []
true
289d459d9e0dda101f443edaa9bf65d2985b4949
YaraBader/python-applecation
/Ryans+Notes+Coding+Exercise+16+Calculate+a+Factorial.py
604
4.1875
4
''' Create a Factorial To solve this problem: 1. Create a function that will find the factorial for a value using a recursive function. Factorials are calculated as such 3! = 3 * 2 * 1 2. Expected Output Factorial of 4 = 24 Factorial at its recursive form is: X! = X * (X-1)! ''' # define the factorial function def factorial(n): # Sets to 1 if asked for 1 # This is the exit condition if n==1: return 1 else: # factorial in recursive form for >= 2 result = n * factorial(n-1) return result # prints factorial of 4 print ("Factorial of 4 =", factorial(4))
true
84e848c7b3f7cd20142ce6326a8a5131b1ecacad
YaraBader/python-applecation
/Ryans+Notes+Coding+Exercise+8+Print+a+Christmas+Tree.py
1,956
4.34375
4
''' To solve this problem: Don't use the input function in this code 1. Assign a value of 5 to the variable tree_height 2. Print a tree like you saw in the video with 4 rows and a stump on the bottom TIP 1 You should use a while loop and 3 for loops. TIP 2 I know that this is the number of spaces and hashes for the tree 4 - 1 3 - 3 2 - 5 1 - 7 0 - 9 Spaces before stump = Spaces before top TIP 3 You will need to do the following in your program : 1. Decrement spaces by one each time through the loop 2. Increment the hashes by 2 each time through the loop 3. Save spaces to the stump by calculating tree height - 1 4. Decrement from tree height until it equals 0 5. Print spaces and then hashes for each row 6. Print stump spaces and then 1 hash Here is the sample program How tall is the tree : 5      #    ###    ##### ####### #########      # ''' # Sets 5 for tree_height (as an integer) height = int(5) # spaces starts as height - 1 spaces = stumpspaces = height -1 # hashes start as 1 hashes = 1 # This loop goes until the height limit is reached # height will be decreased by 1 each iteration of the loop while height >= 1: # Prints a space for the number of spaces before the hashes # This starts at height-1, just like the stump, and decreases 1 per iteration # end="" does not print a new line for i in range(spaces): print(" ", end="") # Prints the hashes # which starts at 1 and increases by 2 per iteration for j in range(hashes): print('#', end="") # prints a new line after each iteration of the spaces and hashes print() # spaces decreases 1 per iteration spaces -= 1 # hashes increase 2 per iteration hashes += 2 # This is what makes it go down to the next level height -= 1 # Prints the spaces before the hash stump # which is height-1 for i in range(stumpspaces): print(' ', end="") # Prints the hash stump print("#")
true
e3c8b5241b67c829edc0b1ff4da04dd6e764a89a
jdurbin/sandbox
/python/basics/scripts/lists.py
738
4.15625
4
#!/usr/bin/env python import numpy as np a = [1,2,3,4] print a print a[2:5] # omitted in a slice assumed to have extreme value print a[:3] # a[:] is just a, the entire list print "a[:-1]",a[:-1] print "a[:-2]",a[:-2] #numpy matrix: # Note that [,] are lists, but (,) are tuples. # Lists are mutable, tuples are not. # tuple is a hashtable so you can use it as a dictionary(??) mat = np.zeros((3,3)) print "MAT:\n",mat # slices are always views, not copies. mat2=np.array([[1,2,3],[4,5,6],[7,8,9]]) print "MAT2:\n",mat2 print "MAT2[0:2]\n",mat2[0:2] print "MAT2[,0:2]\n",mat2[:,0:2] print "MAT2[0:1,0:2]:\n",mat2[0:1,0:2] print "mat sqrt:\n",np.sqrt(mat2) mat3 = np.array([2,2,2]) print "mat2 dot mat3:\n",mat2.dot(mat3)
false
20d2c16838f90918e89bfcf67d7c1f9210d6d39a
vaishu8747/Practise-Ass1
/1.py
231
4.34375
4
def longestWordLength(string): length=0 for word in string.split(): if(len(word)>length): length=len(word) return length string="I am an intern at geeksforgeeks" print(longestWordLength(string))
true
7462b7bb66c8da8ec90645eb00a654c316707b28
matheus-hoy/jogoForca
/jogo_da_forca.py
1,154
4.1875
4
print('Bem Vindo ao JOGO DA FORCA XD') print('Você tem 6 chances') print() palavra_secreta = 'perfume' digitado = [] chances = 6 while True: if chances <= 0: print('YOU LOSE') break letra = input('Digite uma letra: ') if len(letra) > 1: print('Digite apenas uma letra Malandro') continue digitado.append(letra) if letra in palavra_secreta: print(f'Boa, a letra "{letra}" faz parte da Palavra secreta.') else: print(f'Putz, a letra "{letra}" não faz parte da Palavra secreta.') digitado.pop() secreto_temporario = '' for letra_secreta in palavra_secreta: if letra_secreta in digitado: secreto_temporario += letra_secreta else: secreto_temporario+= '*' if secreto_temporario == palavra_secreta: print('PARABÉNS, VOCÊ CONSEGUIU... IHAAAAA') break else: print(f'A palavra secreta está assim: {secreto_temporario}') if letra not in palavra_secreta: chances -= 1 print(f' Voce ainda pode tentar: {chances}x') print()
false
894abe59b869794b4a35903f04a750b1f9ee5788
brianbrake/Python
/ComputePay.py
834
4.3125
4
# Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay # Award time-and-a-half for the hourly rate for all hours worked above 40 hours # Put the logic to do the computation of time-and-a-half in a function called computepay() # Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75) def computepay (hrs,rate): try: hrs=float(raw_input("Enter Hours: ")) rate=float(raw_input("Enter Rate: ")) if hrs <= 40: gross = hrs * rate else: overtime = float (hrs-40) gross = (rate*40)+(overtime*1.5*rate) return gross except: print "Please type numerical data only. Restart & try again: " quit() print computepay('hrs', 'rate')
true
74c1a177115b9dd2e3b519e0581e1605814ef499
oschre7741/my-first-python-programs
/geometry.py
1,285
4.1875
4
# This program contains functions that evaluate formulas used in geometry. # # Olivia Schreiner # August 30, 2017 import math def triangle_area(b,h): a = (1/2) * b * h return a def circle_area(r): a = math.pi * r**2 return a def parallelogram_area(b,h): a = b * h return a def trapezoid_area(c,b,h): a = ((c + b) / 2) * h return a def rect_prism_volume(w,h,l): v = w * h * l return v def cone_volume(r,h): v = math.pi * r**2 * (h / 3) return v def sphere_volume(r): v = (4/3) * math.pi * r**3 return v def rect_prism_sa(w,h,l): a = 2 * (w * l + h * l + h * w) return a def sphere_sa(r): a = 4 * math.pi * r**2 return a def hypotenuse(w,x,y,z): d = math.sqrt(((y - w)**2) + ((z - x)**2)) return d def herons_formula(b,c,d): s = (b + c + d)/2 a = math.sqrt(s * (s - b) * (s - c) * (s- d)) return a #function calls print(triangle_area(4,9)) print(circle_area(5)) print(circle_area(12)) print(parallelogram_area(2,2)) print(trapezoid_area(1,2,3)) print(rect_prism_volume(1,2,3)) print(cone_volume(2,3)) print(sphere_volume(2)) print(rect_prism_sa(2,2,2)) print(sphere_sa(2)) print(hypotenuse(1,2,3,4)) print(herons_formula(3,5,7))
false
6168ffa995d236e3882954d9057582a5c130763a
ghinks/epl-py-data-wrangler
/src/parsers/reader/reader.py
2,129
4.15625
4
import re import datetime class Reader: fileName = "" def __init__(self, fileName): self.fileName = fileName def convertTeamName(self, name): """convert string to upper case and strip spaces Take the given team name remove whitespace and convert to uppercase """ try: upper = name.upper() converted = re.sub(r"\s+", "", upper) return converted except Exception as e: print(f"an exception when trying to convert ${name} to upper case has taken place ${e}") raise def convertStrDate(self, strDate): """given dd/mm/yyyy or yyyy-mm-dd create a python Date Take the string format of 'dd/mm/yyyy' or 'yyyyy-mm-dd' and convert that into a form that may be used to create a python date """ if not isinstance(strDate, str): return strDate try: compiled = re.compile(r"(\d\d)\/(\d\d)\/(\d{2,4})") match = compiled.match(strDate) if match: day = match.groups()[0] month = match.groups()[1] year = match.groups()[2] # there are two types of year format that can be given # the first is a 2 digit year. If this year is > 80 # then it was before year 2000 # if it is < 80 it is after year 2000 if len(year) == 2 and 80 < (int(year)) < 100: year = (int(year)) + 1900 elif len(year) == 2 and (int(year)) < 80: year = 2000 + int(year) return datetime.date(int(year), int(month), int(day)) compiled = re.compile(r"(\d\d\d\d)\-(\d\d)\-(\d\d)(.*)") match = compiled.match(strDate) year = match.groups()[0] month = match.groups()[1] day = match.groups()[2] return datetime.date(int(year), int(month), int(day)) except (ValueError, AttributeError, TypeError): print("error handling date ", strDate) raise
true
3e0567d81aa20bf04a43d2959ae3fff8b71501ec
biam05/FPRO_MIEIC
/exercicios/RE05 Functions/sumNumbers.py
955
4.34375
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 24 11:47:09 2018 @author: biam05 """ # # DESCRIPTION of exercise 2: # # Write a Python function sum_numbers(n) that returns the sum of all positive # integers up to and including n. # # For example: sum_numbers(10) returns the value 55 (1+2+3+. . . +10) # # Do NOT alter the function prototype given # # PASTE your code inside the function block below, paying atention to the right indentation # # Don't forget that your program should use the return keyword in the last instruction # to return the appropriate value # def sum_numbers(n): """ returns the sum of all positive integers up to and including n """ #### MY CODE STARTS HERE ###################################### if n >= 0: result = n for i in range(n): result += i else: result = 0 return result #### MY CODE ENDS HERE ########################################
true