blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7956966c7aa9ffed8da7d23e75d98ae1867c376a
vlad-bezden/py.checkio
/electronic_station/similar_triangles.py
2,498
4.28125
4
"""Similar Triangles https://py.checkio.org/en/mission/similar-triangles/ This is a mission to check the similarity of two triangles. You are given two lists as coordinates of vertices of each triangle. You have to return a bool. (The triangles are similar or not) Example: similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]) is True similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 3), (5, 0)]) is False similar_triangles([(1, 0), (1, 2), (2, 0)], [(3, 0), (5, 4), (5, 0)]) is True Input: Two lists as coordinates of vertices of each triangle. Coordinates is three tuples of two integers. Output: True or False. Precondition: -10 ≤ x(, y) coordinate ≤ 10 """ from __future__ import annotations from math import dist from typing import List, Tuple from dataclasses import dataclass from itertools import combinations Coords = List[Tuple[int, int]] @dataclass class Triangle: a: float b: float c: float def __init__(self, coord: Coords): """Calculate degrees between a and b sides""" self.a, self.b, self.c = sorted( dist(c1, c2) for c1, c2 in combinations(coord, 2) ) def is_similar(self, other: Triangle) -> bool: """Check if triangles are similar.""" return ( round(self.a / other.a, 2) == round(self.b / other.b, 2) == round(self.c / other.c, 2) ) def similar_triangles(coords_1: Coords, coords_2: Coords) -> bool: return Triangle(coords_1).is_similar(Triangle(coords_2)) if __name__ == "__main__": assert ( similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]) is True ), "basic" assert ( similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 3), (5, 0)]) is False ), "different #1" assert ( similar_triangles([(0, 0), (1, 2), (2, 0)], [(2, 0), (4, 4), (6, 0)]) is True ), "scaling" assert ( similar_triangles([(0, 0), (0, 3), (2, 0)], [(3, 0), (5, 3), (5, 0)]) is True ), "reflection" assert ( similar_triangles([(1, 0), (1, 2), (2, 0)], [(3, 0), (5, 4), (5, 0)]) is True ), "scaling and reflection" assert ( similar_triangles([(1, 0), (1, 3), (2, 0)], [(3, 0), (5, 5), (5, 0)]) is False ), "different #2" assert ( similar_triangles([(2, -2), (1, 3), (-1, 4)], [(-10, 10), (-1, -8), (-4, 7)]) is True ) print("PASSED!!!")
true
d880c75abc5b1980a6e0bd5b2435c647963a08d1
vlad-bezden/py.checkio
/oreilly/median_of_three.py
1,986
4.125
4
"""Median of Three https://py.checkio.org/en/mission/median-of-three/ Given an List of ints, create and return a new List whose first two elements are the same as in items, after which each element equals the median of the three elements in the original list ending in that position. Input: List of ints. Output: List of ints. Output: median_three_sorted([1, 2, 3, 4, 5, 6, 7]) => 0.000359 median_three_zip([1, 2, 3, 4, 5, 6, 7]) => 0.000379 median_three_sorted([1]) => 0.000080 median_three_zip([1]) => 0.000119 median_three_sorted([]) => 0.000060 median_three_zip([]) => 0.000105 Conclusion: Using sorted works faster when there are less items in the list. With more items both sorted and zip have almost the same time. """ from statistics import median from typing import Callable, List, Sequence from dataclasses import dataclass from timeit import repeat @dataclass class Test: data: List[int] expected: List[int] TESTS = [ Test([1, 2, 3, 4, 5, 6, 7], [1, 2, 2, 3, 4, 5, 6]), Test([1], [1]), Test([], []), ] def median_three_sorted(items: List[int]) -> List[int]: return [ v if i < 2 else sorted(items[i - 2 : i + 1])[1] for i, v in enumerate(items) ] def median_three_zip(items: List[int]) -> List[int]: return items[:2] + [*map(median, zip(items, items[1:], items[2:]))] def validate(funcs: Sequence[Callable[[List[int]], List[int]]]) -> None: for test in TESTS: for f in funcs: result = f(test.data) assert result == test.expected, f"{f.__name__}({test}), {result = }" print("PASSED!!!") if __name__ == "__main__": funcs = [median_three_sorted, median_three_zip] validate(funcs) for test in TESTS: for f in funcs: t = repeat(stmt=f"f({test.data})", repeat=3, number=100, globals=globals()) print(f"{f.__name__}({test.data}) => {min(t):.6f}") print()
true
d8803c10cf12c5afb6898dd2c5cce4e7be0adeed
vlad-bezden/py.checkio
/oreilly/chunk.py
1,083
4.4375
4
"""Chunk. https://py.checkio.org/en/mission/chunk/ You have a lot of work to do, so you might want to split it into smaller pieces. This way you'll know which piece you'll do on Monday, which will be for Tuesday and so on. Split a list into smaller lists of the same size (chunks). The last chunk can be smaller than the default chunk-size. If the list is empty, then you shouldn't have any chunks at all. Input: Two arguments. A List and chunk size. Output: An List with chunked List. Precondition: chunk-size > 0 """ from typing import List def chunking_by(items: List[int], size: int) -> List[List[int]]: return [items[s : s + size] for s in range(0, len(items), size)] if __name__ == "__main__": assert list(chunking_by([5, 4, 7, 3, 4, 5, 4], 3)) == [[5, 4, 7], [3, 4, 5], [4]] assert list(chunking_by([3, 4, 5], 1)) == [[3], [4], [5]] assert list(chunking_by([5, 4], 7)) == [[5, 4]] assert list(chunking_by([], 3)) == [] assert list(chunking_by([4, 4, 4, 4], 4)) == [[4, 4, 4, 4]] print("PASSED!!!")
true
a1241876f32a8cbcfa522b6393ae8ba20837549b
vlad-bezden/py.checkio
/elementary/split_list.py
885
4.375
4
"""Split List https://py.checkio.org/en/mission/split-list/ You have to split a given array into two arrays. If it has an odd amount of elements, then the first array should have more elements. If it has no elements, then two empty arrays should be returned. example Input: Array. Output: Array or two arrays. Example: split_list([1, 2, 3, 4, 5, 6]) == [[1, 2, 3], [4, 5, 6]] split_list([1, 2, 3]) == [[1, 2], [3]] """ def split_list(items: list) -> list: i = (len(items) + 1) // 2 return [items[:i], items[i:]] if __name__ == "__main__": assert split_list([1, 2, 3, 4, 5, 6]) == [[1, 2, 3], [4, 5, 6]] assert split_list([1, 2, 3]) == [[1, 2], [3]] assert split_list([1, 2, 3, 4, 5]) == [[1, 2, 3], [4, 5]] assert split_list([1]) == [[1], []] assert split_list([]) == [[], []] print("PASSED!!!")
true
93b69fd2a07e076c8d968d862e19bb1831aa6aab
vlad-bezden/py.checkio
/mine/skew-symmetric_matrix.py
2,305
4.1875
4
"""Skew-symmetric Matrix https://py.checkio.org/en/mission/skew-symmetric-matrix/ In mathematics, particularly in linear algebra, a skew-symmetric matrix (also known as an antisymmetric or antimetric) is a square matrix A which is transposed and negative. This means that it satisfies the equation A = −AT. If the entry in the i-th row and j-th column is aij, i.e. A = (aij) then the symmetric condition becomes aij = −aji. You should determine whether the specified square matrix is skew-symmetric or not. Input: A square matrix as a list of lists with integers. Output: If the matrix is skew-symmetric or not as a boolean. Example: checkio([ [ 0, 1, 2], [-1, 0, 1], [-2, -1, 0]]) == True checkio([ [ 0, 1, 2], [-1, 1, 1], [-2, -1, 0]]) == False checkio([ [ 0, 1, 2], [-1, 0, 1], [-3, -1, 0]]) == False Precondition: 0 < N < 5 Output: checkio_product 0.0713 checkio_product 0.0430 checkio_product 0.0354 checkio_zip 0.0296 checkio_zip 0.0299 checkio_zip 0.0291 checkio_allclose 0.7690 checkio_allclose 0.7574 checkio_allclose 0.7623 """ from timeit import timeit from itertools import product from numpy import allclose, array def using_product(matrix): return not any( matrix[i][j] + matrix[j][i] for i, j in product(range(len(matrix)), repeat=2) ) def using_zip(matrix): return matrix == [[-x for x in row] for row in zip(*matrix)] def using_allclose(matrix): return allclose(matrix, -array(matrix).T) def using_classic(matrix): n = len(matrix) return not any(matrix[i][j] + matrix[j][i] for i in range(n) for j in range(i, n)) if __name__ == "__main__": tests = [ ([[0, 1, 2], [-1, 0, 1], [-2, -1, 0]], True), ([[0, 1, 2], [-1, 1, 1], [-2, -1, 0]], False), ([[0, 1, 2], [-1, 0, 1], [-3, -1, 0]], False), ] for func in [using_product, using_zip, using_allclose, using_classic]: for data, result in tests: assert func(data) is result t = timeit(stmt=f"func({data})", number=10_000, globals=globals()) print(f"{func.__name__} {t:.4f}") print("PASSED!")
true
b1dee53024fb0e1420d3d3443eb26f6f2c949bf1
linkel/MITx-6.00.1x-2018
/Week 1 and 2/alphacount2.py
1,218
4.125
4
s = 'kpreasymrrs' longest = s[0] longestholder = s[0] #go through the numbers of the range from the second letter to the end for i in (range(1, len(s))): #if this letter is bigger or equal to the last letter in longest variable then add it on (meaning alphabetical order) if s[i] >= longest[-1]: longest = longest + s[i] #if this letter is smaller, meaning not in order, and so far longest is longer than my holder, then save longest into the holder and restart longest at my pointer elif s[i] < longest[-1] and (len(longestholder) < len(longest)): longestholder = longest longest = s[i] #if the letter is not in alpha order and longest ain't the longer one between it and holder then just start over elif s[i] < longest[-1]: longest = s[i] #this last check is necessary for the case where we find the longest and it ends with the last letter, so it doesn't hit my elif check if len(longestholder) < len(longest): longestholder = longest print("Longest substring in alphabetical order is: " + longestholder) #holy dingdongs man. Took me a full hour, and I had to look up that python can compare letters by their ascii value and get a bool. pretty convenient
true
fc17ad2770c01b01220527948074999663a5cb0e
amir-mersad/ICS3U-Unit5-01-Python
/function.py
885
4.46875
4
#!/usr/bin/env python3 # Created by: Amir Mersad # Created on: November 2019 # This program converts temperature in degrees Celsius # to temperature degrees Fahrenheit def celsius_to_fahrenheit(): # This program converts temperature in degrees Celsius # to temperature degrees Fahrenheit # Input celsius_degree = input("Please enter the temperature in degrees Celsius: ") # Process try: # The numbers need to be float because we cannot # multiply float by an int celsius_degree = float(celsius_degree) fahrenheit_degree = 1.8 * celsius_degree + 32.0 # Output print("\nThe temperature in degrees fahrenheit is", fahrenheit_degree) except(Exception): print("Wrong input!!!") def main(): # This function calls other functions celsius_to_fahrenheit() if __name__ == "__main__": main()
true
a642a315921776c3d5920bd3e9f649a888462773
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/list_test.py
2,003
4.46875
4
"""class list([iterable])""" # https://www.programiz.com/python-programming/methods/built-in/list """Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range. The list() constructor creates a list in Python. Python list() constructor takes a single argument: iterable (Optional) - an object that could be a sequence (string, tuples) or collection (set, dictionary) or iterator object. If no parameters are passed, it creates an empty list. If iterable is passed as parameter, it creates a list of elements in the iterable.""" class PowTwo: def __init__(self, max): self.max = max def __iter__(self): self.num = 0 return self def __next__(self): if (self.num >= self.max): raise StopIteration result = 2 ** self.num self.num += 1 return result # Example 1: Create list from sequence: string, tuple and list # empty list print(f"list(): {list()}") # vowel string vowelString = 'aeiou' print(f"vowelString: {vowelString}") print(f"list(vowelString): {list(vowelString)}\n") # vowel tuple vowelTuple = ('a', 'e', 'i', 'o', 'u') print(f"vowelTuple: {vowelTuple}") print(f"list(vowelTuple): {list(vowelTuple)}\n") # vowel list vowelList = ['a', 'e', 'i', 'o', 'u'] print(f"vowelList: {vowelList}") print(f"list(vowelList): {list(vowelList)}\n") # Example 2: Create list from collection: set and dictionary # vowel set vowelSet = {'a', 'e', 'i', 'o', 'u'} print(f"vowelSet: {vowelSet}") print(f"list(vowelSet): {list(vowelSet)}\n") # vowel dictionary vowelDictionary = {'a': 1, 'e': 2, 'i': 3, 'o':4, 'u':5} print(f"vowelDictionary: {vowelDictionary}") # Note: Keys in the dictionary are used as elements of the returned list. print(f"list(vowelDictionary): {list(vowelDictionary)}\n") # Example 3: Create list from custom iterator object powTwo = PowTwo(5) powTwoIter = iter(powTwo) print(f"list(powTwoIter): {list(powTwoIter)}")
true
3ec93bc3e2bbb8ec2f59a612ac2ad112aa1f4930
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.8. Generator expressions/example.py
230
4.25
4
# A generator expression is a compact generator notation in parentheses. # A generator expression yields a new generator object. a = (x**2 for x in range(6)) print(f"a: {a}") print(f"type(a): {type(a)}") for i in a: print(i)
true
d866a29053b2e57c7dacf0d44ebaa0078138305a
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/a-b/all__test.py
1,808
4.25
4
"""all(iterable)""" # https://www.programiz.com/python-programming/methods/built-in/all """Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:""" def all_func(iterable): for element in iterable: if not element: return False return True def main(): list = [1, 2, 3, 4, 5] empty_list = [] list_2 = [0, 1, 2, 3] list_3 = [3 < 2, True] print(f"all_func(list): {all_func(list)}") print(f"all(list): {all(list)}\n") print(f"all_func(empty_list): {all_func(empty_list)}") print(f"all(empty_list): {all(empty_list)}\n") # 0 == False print(f"all_func(list_2): {all_func(list_2)}") print(f"all(list_2): {all(list_2)}\n") print(f"all_func(list_3): {all_func(list_3)}") print(f"all(list_3): {all(list_3)}\n") # How all() works for strings? s = "This is good" print(f"s: {s}") print(f"all(s): {all(s)}\n") # 0 is False # '0' is True s = '000' print(f"s: {s}") print(f"all(s): {all(s)}\n") s = '' print(f"s: {s}") print(f"all(s): {all(s)}\n") # How all() works with Python dictionaries? """In case of dictionaries, if all keys (not values) are true or the dictionary is empty, all() returns True. Else, it returns false for all other cases..""" d = {0: 'False', 1: 'False'} print(f"d: {d}") print(f"all(d): {all(d)}\n") d = {1: 'True', 2: 'True'} print(f"d: {d}") print(f"all(d): {all(d)}\n") d = {1: 'True', False: 0} print(f"d: {d}") print(f"all(d): {all(d)}\n") d = {} print(f"d: {d}") print(f"all(d): {all(d)}\n") # 0 is False # '0' is True d = {'0': 'True'} print(f"d: {d}") print(f"all(d): {all(d)}\n") if __name__ == "__main__": main()
true
5315e68a06067a3ab9a99178ab86ce613dc163fb
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/divmod__test.py
816
4.21875
4
"""divmod(a, b)""" # https://www.programiz.com/python-programming/methods/built-in/divmod """Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).""" def main(): print(f"divmod(17, 5): {divmod(17, 5)}") print(f"divmod(17.3, 5): {divmod(17.3, 5)}") print(f"divmod(7.5, 2.5): {divmod(7.5, 2.5)}") if __name__ == "__main__": main()
true
f312b493d986a88f5f05e4ef2c0db055aa8a8c8d
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/min_test.py
2,432
4.25
4
"""min(iterable, *[, key, default]) min(arg1, arg2, *args[, key])""" # https://www.programiz.com/python-programming/methods/built-in/min """Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned. There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised. If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc). """ try: print(f"min([]): {min([])}") except ValueError as e: print(repr(e)) print(f"min([], default='empty sequance'): {min([], default='empty sequance')}\n") # Example 1: Find minimum among the given numbers # using min(arg1, arg2, *args) print(f'Minimum is: {min(1, 3, 2, 5, 4)}') # using min(iterable) num = [3, 2, 8, 5, 10, 6] print(f'Minimum is: {min(num)}\n') # Example 2: Find number whose sum of digits is smallest using key function def sum_of_digits(num: int) -> int: sum = 0 while num > 0: temp = divmod(num, 10) sum += temp[1] num = temp[0] return sum # using min(arg1, arg2, *args, key) print(f'Minimum is: {min(100, 321, 267, 59, 40, key=sum_of_digits)}') # using min(iterable, key) num = [15, 300, 2700, 821, 52, 10, 6] print(f'Minimum is: {min(num, key=sum_of_digits)}\n') """Here, each element in the passed argument (list or argument) is passed to the same function sumDigit(). Based on the return value of the sumDigit(), i.e. sum of the digits, the smallest is returned.""" # Example 3: Find list with minimum length using key function num = [15, 300, 2700, 821] num1 = [12, 2] num2 = [34, 567, 78] # using min(iterable, *iterables, key) print(f'Minimum is: {min(num, num1, num2, key=len)}') """In this program, each iterable num, num1 and num2 is passed to the built-in method len(). Based on the result, i.e. length of each list, the list with minimum length is returned."""
true
bf573e2b7eafe79adde1e52d40e21d5d393b043e
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.4. Displays for lists, sets and dictionaries/example.py
218
4.125
4
# The comprehension consists of a single expression followed by at least one for clause # and zero or more for or if clauses. a = [x**2 for x in range(11) if x % 2 == 0] print(f"a: {a}") print(f"type(a): {type(a)}")
true
e5de070bfe40a82008d8d9e6ed6986c618dc7043
corridda/Studies
/Articles/Python/pythonetc/year_2018/october/python_etc_oct_23.py
1,278
4.1875
4
"""https://t.me/pythonetc/230""" """You can modify the code behavior during unit tests not only by using mocks and other advanced techniques but also with straightforward object modification:""" import random import unittest from unittest import TestCase # class Foo: # def is_positive(self): # return self.rand() > 0 # # def rand(self): # return random.randint(-2, 2) # # # class FooTestCase(TestCase): # def test_is_positive(self): # foo = Foo() # foo.rand = lambda: 1 # self.assertTrue(foo.is_positive()) # # # if __name__ == '__main__': # unittest.main() """That's not gonna work if rand is property or any other descriptor. In that case, you should modify the class, not the object. However, modifying Foo might affect other tests, so the best way to deal with it is to create descendant.""" class Foo: def is_positive(self): return self.rand > 0 @property def rand(self): return random.randint(-2, 2) class FooTestCase(TestCase): def test_is_positive(self): class TestFoo(Foo): @property def rand(self): return 1 foo = TestFoo() self.assertTrue(foo.is_positive()) if __name__ == '__main__': unittest.main()
true
beb99591beb990888eb58b3d949b3b44a21bcb2f
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/s-z/tuple_test.py
724
4.40625
4
""" tuple([iterable]) class type(object) class type(name, bases, dict)""" # https://www.programiz.com/python-programming/methods/built-in/tuple """Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range. If an iterable is passed, corresponding tuple is created. If the iterable is omitted, empty tuple is created.""" # Example: How to creating tuples using tuple()? t1 = tuple() print('t1=', t1) # creating a tuple from a list t2 = tuple([1, 4, 6]) print('t2=', t2) # creating a tuple from a string t1 = tuple('Python') print('t1=',t1) # creating a tuple from a dictionary t1 = tuple({1: 'one', 2: 'two'}) print('t1=',t1)
true
8341587ff2d172282ab6b00a82ea56380f062e4f
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 5. Data Structures/5.6. Looping Techniques/Looping Techniques.py
1,713
4.15625
4
import math # looping through dictionaries -> items() knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k,v in knights.items(): print(k, ':', v) # looping through a sequence -> # the position index and corresponding value can be retrieved at the same time using the enumerate() function. for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v) # To loop over two or more sequences at the same time, the entries can be paired with the zip() function. questions = ['name', 'quest', 'favorite color'] answers = ['Lancelot', 'The Holy Grail', 'blue'] for q, a in zip(questions, answers): print(f'What is your {q}? It is {a}.') # To loop over a sequence in reverse, first specify the sequence in a forward direction # and then call the reversed() function. print('reversed list: ', end='') for i in reversed([1, 2, 3]): print(i, '', end='') # the sorted() function which returns a new sorted list while leaving the source unaltered. basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] print('\nsorted list: ', end='') for i in sorted(basket): print(i, '', end='') # It is sometimes tempting to change a list while you are looping over it; # however, it is often simpler and safer to create a new list instead raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] filtered_data = [] for value in raw_data: if not math.isnan(value): filtered_data.append(value) print('\nsorted(filtered_data):', sorted(filtered_data)) print('filtered_data:', filtered_data) # You can always simply delete the unnecessary data by 'del' print(f'raw_data: {raw_data}') del raw_data try: print(f'raw_data: {raw_data}') except NameError as e: print(e)
true
6b3f8316bc32ae76e7975953ae2839bc47a0d317
swyatik/Python-core-07-Vovk
/Task 4/2_number_string.py
293
4.15625
4
number = 1234 strNumber = str(number) product = int(strNumber[0]) * int(strNumber[1]) * int(strNumber[2]) * int(strNumber[3]) reversNumber = int(strNumber[::-1]) print('Product of number %d is %15d' % (number, product)) print('Inverse number to number %d is %8d' % (number, reversNumber))
true
8aa5fbf8d58db8094e0dab793af65cab51b378e8
aakinlalu/Mini-Python-Projects
/dow_csv/dow_csv_solution.py
1,713
4.125
4
""" Dow CSV ------- The table in the file 'dow2008.csv' has records holding the daily performance of the Dow Jones Industrial Average from the beginning of 2008. The table has the following columns (separated by commas). DATE OPEN HIGH LOW CLOSE VOLUME ADJ_CLOSE 2008-01-02 13261.82 13338.23 12969.42 13043.96 3452650000 13043.96 2008-01-03 13044.12 13197.43 12968.44 13056.72 3429500000 13056.72 2008-01-04 13046.56 13049.65 12740.51 12800.18 4166000000 12800.18 2008-01-07 12801.15 12984.95 12640.44 12827.49 4221260000 12827.49 2008-01-08 12820.9 12998.11 12511.03 12589.07 4705390000 12589.07 2008-01-09 12590.21 12814.97 12431.53 12735.31 5351030000 12735.31 1. Read the data from the file, converting the fields to appropriate data types. 2. Print out all the rows which have a volume greater than 5.5 billion. Bonus ~~~~~ 1. Print out the rows which have a difference between high and low of greater than 4% and sort them in order of that spread. """ import csv data = [] with open("dow2008.csv", "rb") as fp: r = csv.reader(fp) r.next() for row in r: data.append([ row[0], float(row[1]), float(row[2]), float(row[3]), float(row[4]), int(row[5]), float(row[6]), ]) # print out the rows > 5.5 billion for row in data: if row[5] > 5500000000: print row # print out the rows with 4% change new_data = [] for row in data: if (row[2]-row[3])/row[2] > 0.04: new_data.append(row) new_data.sort(key=lambda row: (row[2]-row[3])/row[2]) print print for row in new_data: print row
true
99728de2ec99c6e60ff42a3a7811f5268028031d
jhoover4/algorithms
/cracking_the_coding/chapter_1-Arrays/7_rotate_matrix.py
2,120
4.40625
4
import unittest from typing import List def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Problem: Rotate an M x N matrix 90 degrees. Answer: Time complexity: O(MxN) """ if not matrix or not matrix[0]: raise ValueError("Must supply valid M x N matrix.") col_len = len(matrix) row_len = len(matrix[0]) new_matrix = [[] for _ in range(row_len)] for row in range(col_len): for i, item in enumerate(matrix[row]): new_matrix[i].insert(0, item) return new_matrix def rotate_matrix_in_place(matrix: List[List[int]]) -> List[List[int]]: """ Problem: Rotate an M x N matrix 90 degrees in place (no new data structure) Answer: Time complexity: O(MxN) """ # TODO: Finish this if not matrix or not matrix[0]: raise ValueError("Must supply valid M x N matrix.") col_len = len(matrix) row_len = len(matrix[0]) new_matrix = [[] for _ in range(row_len)] for row in range(col_len): for i, item in enumerate(matrix[row]): new_matrix[i].insert(0, item) return new_matrix class Test(unittest.TestCase): def test_has_rotated_square(self): test_matrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] rotated_matrix = [ [21, 16, 11, 6, 1], [22, 17, 12, 7, 2], [23, 18, 13, 8, 3], [24, 19, 14, 9, 4], [25, 20, 15, 10, 5] ] self.assertEqual(rotate_matrix(test_matrix), rotated_matrix) def test_has_rotated_rectangle(self): test_matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20] ] rotated_matrix = [ [17, 13, 9, 5, 1], [18, 14, 10, 6, 2], [19, 15, 11, 7, 3], [20, 16, 12, 8, 4], ] self.assertEqual(rotated_matrix, rotate_matrix(test_matrix))
true
3708eda29bf47b6a2ab23eb56e8f95b9f88e4a5e
ChaitDevOps/Scripts
/PythonScripts/ad-lists.py
1,018
4.5
4
#!/usr/bin/python # ad-lists.py # Diving a little deeper into Lists. #.append() Appends an element to the 'END' of the exisitng list. from __future__ import print_function l = [1,2,3] l.append([4]) print(l) #.extend() extends list by appending elements from the iterable l = [4,5,6] l.extend([7,8,9]) print(l) # .index() - Returns the index of whatever element is placed as an argument. # Note: If the the element is not in the list an error is returned print(l.index(5)) # .insert() - insert takes in two arguments: insert(index,object) This method places the object at the index supplied l.insert(7,10) # if No index is supplied, it errors out. print("Here is insert:",l) print("Length of List l:" , len(l)) # .pop() - Pops off the last element of the list. ele = l.pop() print(ele) # .remove - The remove() method removes the first occurrence of a value x=[8,9,10] x.remove(9) print(x) # .reverse - reverse the list, replaces your list. x.reverse() print(x) # .sort - will sort you List. x.sort() print(x)
true
85769cf60c277a432a21b44b95e3814d23511666
ChaitDevOps/Scripts
/PythonScripts/lambda.py
556
4.15625
4
#!/usr/bin/python # Lambda Expressions # lambda.py # Chaitanya Bingu # Lamba expressions is basically a one line condensed version of a function. # Writing a Square Function, we will break it down into a Lambda Expression. def square(num): result = num**2 print result square(2) def square(num): print num**2 square(4) def cube(num): print num**3 cube(2) # Converting this to Lambda square2 = lambda num: num**2 print square2(10) adder = lambda x,y: x+y print adder(10,10) len_check = lambda item: len(item) print len_check("Arsenal Rules!")
true
9f44f5d1b42a232efb349cd9a484b1eb0d68372f
ChaitDevOps/Scripts
/PythonScripts/advanced_strings.py
2,053
4.4375
4
#!/usr/bin/python # Chait # Advanced Strings in Python. # advanced_strings.py from __future__ import print_function # .capitalize() # Converts First Letter of String to Upper Case s = "hello world" print(s.capitalize()) # .upper() and .lower() print(s.upper()) print(s.lower()) # .count() and .find() # .count() -- Will cound the number of times the argument was present in the variable/string # .find() - Will find the position of the argument. will quit after first find. print(s.count('o')) print(s.find('o')) # .center() # The center() method allows you to place your string 'centered' between a provided string with a certain length print(s.center(20,'z')) # .expandtabs() # expandtabs() will expand tab notations \t into spaces: print("FirstName\tLastName".expandtabs()) # isalnum() will return True if all characters in S are alphanumeric # isalpha() wil return True if all characters in S are alphabetic # islower() will return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise # isspace() will return True if all characters in S are whitespace. # istitle() will return True if S is a title cased string and there is at least one character in S, # i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. # isupper() will return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. # endswith() Another method is endswith() which is essentially the same as a boolean check on s[-1] s="hello" print(s.isalnum()) print(s.isalpha()) print(s.islower()) print(s.isupper()) print(s.istitle()) print(s.endswith('o')) ## Built in Reg-ex # .split() Excludes the seperator. s="chaitanya" print(s.split(s[4])) # Splits at index position 4 of the variable s. print(s.split('t')) # Splits at the letter 't' of the variable s. # .partition() #Prints the tuple, meaning first half, seperator, second half. print(s.partition(s[4])) print(s.partition('t'))
true
bcc7ae5bdfe6d3a4f2b0433ca78c7c931a629519
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Array Sequences/Array Sequences Interview Questions/Array Sequence Interview Questions/Sentence-Reversal.py
1,431
4.21875
4
#!/usr/bin/env python3 """ Solution """ def rev_word1(s): return ' '.join(s.split()[::-1]) """ Practise """ def rev_word2(s): return ' '.join(reversed(s.split())) def rev_word3(s): """ Manually doing the splits on the spaces. """ words = [] length = len(s) spaces = [' '] # Index Tracker i = 0 # While index is less than length of string while i < length: # If element isn't a space if s[i] not in spaces: # The word starts at this index word_start = i while i < length and s[i] not in spaces: # Get index where the word ends i += 1 # Append that word to the list words.append(s[word_start:i]) i += 1 # Join the reversed words return ' '.join(reversed(words)) """ SOLUTION TESTING """ import unittest class ReversalTest(unittest.TestCase): def test(self, sol): self.assertEqual(sol(' space before'),'before space') self.assertEqual(sol('space after '),'after space') self.assertEqual(sol(' Hello John how are you '),'you are how John Hello') self.assertEqual(sol('1'),'1') print('ALL TEST CASES PASSED') print("rev_word('Hi John, are you ready to go?')") print(rev_word1('Hi John, are you ready to go?')) print("rev_word(' space before')") print(rev_word1(' space before')) t = ReversalTest() print('## Testing Solution 1') t.test(rev_word1) print('## Testing Solution 2') t.test(rev_word2) print('## Testing Solution 3') t.test(rev_word3)
true
19a3cc106f1dadaf621ef20dd79d62861ab01ac7
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Sorting and Searching/01_Binary_Search.py
754
4.25
4
#!/usr/bin/env python3 def binary_search(arr, element): # First & last index value first = 0 last = len(arr) - 1 found = False while first <= last and not found: mid = (first + last) // 2 # // required for Python3 to get the floor # Match found if arr[mid] == element: found = True # set new midpoints up or down depending on comparison else: # Set down if element < arr[mid]: last = mid - 1 # Set up else: first = mid + 1 return found print('\n### Binary Search algorythm') # NOTE: List must be already sorted! arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print('List:\t' + str(arr)) print('binary_search(arr, 4): ' + str(binary_search(arr, 4))) print('binary_search(arr, 2.2): ' + str(binary_search(arr, 2.2)))
true
78993e5a2442e7947655a263788fbf83a9c50c0d
kartik-mewara/pyhton-programs
/Python/25_sets_methods.py
672
4.4375
4
s={1,2,3,4,5,6} print(s) print(type(s)) s1={} print(type(s1)) #this will result in type of dict so for making empty set we follow given method s1=set() print(type(s1)) s1.add(10) s1.add(20) print(s1) s1.add((1,2,3)) # s1.add([1,2,3]) this will throws an erros as we can only add types which are hashable of unmutable as list is unhashable # s1.add({1:2}) same goes for dictionary # set is datatype which is collection of unrepeated values print(s1) s1.add(20) s1.add(20) print(s1) print(len(s1)) #gives tghe lenght of the set s1.remove(10) print(s1) a=s1.pop() #it removes the random item and it return it print(s1) print(a) s1.clear() # it clears the full set print(s1)
true
51fe08037ca0d96b83b0dadded63411c1791aecd
kartik-mewara/pyhton-programs
/Python/05_typecasting.py
593
4.125
4
# a="1234" # a+=5 # print(a) this will not work as a is a string but we expect ans 1239so for that we will type cast a which is string into int a="1234" print(type(a)) a=int(a) a+=5 print(type(a)) print(a) # now it will work fine # similerly we can type cast string to int to string int to float float to in etc b=2.3 c="2.3" d=345 b=str(b) # c=int(c) #here we will get error becoz in string it is float and we are trying to make it int for that we need to make it first float then we will make it int c=float(c) print(type(c)) c=int(c) print(type(c)) d=float(d) print(b) print(c) print(d)
true
332bb7e70a8168e8194a995f6eca4b1983997400
kartik-mewara/pyhton-programs
/Python/13_string_template.py
255
4.34375
4
letter='''Dear <|name|> you are selected on the date Date: <|date|> ''' name=input("Enter name of person\n") date=input("Enter date of joining\n") # print(letter) letter=letter.replace("<|name|>",name) letter=letter.replace("<|date|>",date) print(letter)
true
fd6f4950b4fdd76631619868f22938333061c7e3
kheraankit/coursera
/interactive_python_rice/rock_paper_scissors_lizard_spock.py
2,975
4.28125
4
# The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random # helper functions def number_to_name(number): """ This function accepts a 'number' as a key and return the corresponding value 'name' """ if number == 0: return "rock" elif number == 1: return "Spock" elif number == 2: return "paper" elif number == 3: return "lizard" elif number == 4: return "scissors" else: print "Unrecognized number:" + str(number) def name_to_number(name): """ This function accepts 'name' as a key and return the corresponding value 'number' """ if name == "rock": return 0 elif name == "Spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name == "scissors": return 4 else: print "Unrecognized name:" + name def print_results(winning_number,computer_name,player_name): """ This function pretty prints the results """ print "Player chooses " + player_name print "Computer chooses " + computer_name # 0-player_wins 1-computer_wins 2-tie if(winning_number == 0): print "Player wins!" elif(winning_number == 1): print "Computer wins!" else: print "Player and computer tie!" print "" def rpsls(name): """ This function accepts the player's choice as a function argument and generates a random choice for computer, plays the Rock-paper-scissors-lizard-Spock game [Player vs Comptuer] and prints the results """ # holds the results. 0-player_wins 1-computer_wins 2-tie winning_number = 0 # convert name to player_number using name_to_number player_number = name_to_number(name) # compute random guess for comp_number using random.randrange() comp_number = random.randrange(0, 5) # compute difference of player_number and comp_number modulo five if(comp_number != None and player_number != None): diff_number = (comp_number - player_number) % 5 if diff_number > 0 and diff_number <=2: winning_number = 1 elif diff_number > 2: winning_number = 0 else: # difference is zero, tie between computer and player winning_number = 2 # convert comp_number to name using number_to_name computer_name = number_to_name(comp_number) # print results print_results(winning_number,computer_name,name) else: print comp_number,player_number # test your code rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors") # always remember to check your completed program against the grading rubric
true
2b6117afba9745fddf4f5622132b528848badc9a
bellajcord/Python-practice
/controlflow.py
2,822
4.4375
4
# Logical operators # and (1 > 2) and (2 < 3) # multiple (1 == 2) or (2 == 3) or (4 == 4) ################################## ### if,elif, else Statements ##### ################################## # Indentation is extremely important in Python and is basically Python's way of # getting rid of enclosing brackets like {} we've seen in the past and are common # with other languages. This adds to Python's readability and is huge part of the # "Zen of Python". It is also a big reason why its so popular for beginners. Any # text editor or IDE should be able to auto-indent for you, but always double check # this if you ever get errors in your code! Code blocks are then noted by a colon (:). if 1 < 2: print('yep') if 1 < 2: print('first') else: print('last') # To add more conditions (like else if) you just use a single phrase "elif" if 1 == 2: print('first') elif 3 == 3: print('middle') else: print('last') #loops # Time to review loops with Python, such as For Loops and While loops # Python is unique in that is discards parenthesis and brackets in favor of a # whitespace system that defines blocks of code through indentation, this forces # the user to write readable code, which is great for future you looking back at # your older code later on! # loop with list seq = [1,2,3,4,5] for item in seq: print(item) # Perform an action for every element but doesn't actually involve the elements for item in seq: print('yep') # You can call the loop variable whatever you want: for jelly in seq: print(jelly+jelly) ## For Loop with a Dictionary ages = {"sam":3, "Frank":2, "Dan":4} for key in ages: print("This is the key") print(key) print("this is the value") print(ages[key]) # A list of tuple pairs is a very common format for functions to return data in # Because it is so common we can use tuple un-packing to deal with this, example: mypairs = [(1,10),(3,30),(5,50)] #normal for tup in mypairs: print(tup) #unpacking for item1, item2 in mypairs: print(item1) print(item2) ####################### ### WHILE LOOPS ####### ####################### # While loops allow us to continually perform and action until a condition # becomes true. For example: i = 1 while i < 5: print('i is: {}'.format(i)) i = i+1 # RANGE FUNCTION # range() can quickly generate integers for you, based on a starting and ending point # Note that its a generator: range(5) list(range(5)) for i in range(5): print(i) # List Comprehension # This technique allows you to quickly create lists with a single line of code. # You can think of this as deconstructing a for loop with an append(). For Example: x = [1,2,3,4] out = [] for item in x: out.append(item**2) print(out) #writen in list comp form [item**2 for item in x]
true
0352bb392701674291b3c5d2ce0af52a5834e9d4
NathanontGamer/Multiplication-Table
/multiplication table.py
894
4.46875
4
#define function called multiplication table def muliplication_table (): #input number and number of row number = int(input("Enter column / main number: ")) number_row = int(input("Enter row / number that (has / have) to times: ")) #for loop with range number_row for i in range (1, number_row + 1): print (number, "*", i, "=", number * i) #input continue or not continue_choice = input("Do you want to coninue? (y/n)\n") #if statement decide that want to continue or not if continue_choice == "y": muliplication_table() elif continue_choice == "n": print ("Good Bye!") else: print ("Error!") #print This program can display multiplication table / Describe program plan print ("This program can display multiplication table") #called multiplication_table funcion muliplication_table()
true
01d46d24b6c692f85aec4efcba110013b0b0a579
suraj13mj/Python-Practice-Programs
/10. Python 31-01-20 --- Lists/Program5.py
218
4.21875
4
#Program to sort a 2D List lst=[[25,13],[18,2],[19,36],[17,3]] def sortby(element): #sorts based on column 2 return(element[1]) print("Before Sorting:",lst) lst.sort(key=sortby) print("After Sorting:",lst)
true
706558592b4863c72ef112dfc3ab98588d5f796b
suraj13mj/Python-Practice-Programs
/32. Python 06-03-20 --- File Handling/Program1.py
1,247
4.34375
4
#Program to demonstrate basic file operations in Python def createFile(filename): fh=open(filename,"w") print("Enter File contents:") print("Enter '#' to exit") while True: line=input() if line=="#": break fh.write(line+"\n") fh.close() def appendData(filename): fh=open(filename,"a") print("Enter the data to append:") print("Enter # to exit") while True: line=input() if line=='#': break fh.write(line+"\n") fh.close() def displayFile_1(filename): try: fh=open(filename,"r") print("\nFile contents are:\n") data=fh.read() print(data) fh.close() except Exception: print("File does not exist") #OR def displayFile_2(filename): try: fh=open(filename,"r") print("\nFile contents are:\n") for line in fh: print(line,end="") fh.close() except Exception as e: print(e) if __name__=="__main__": while True: ch=int(input("\n1.Create New File 2.Display File contents 3.Append Data to the File 4.Exit\n")) if ch==1: fnm=input("Enter the Filename to Create:") createFile(fnm) elif ch==2: fnm=input("Enter the Filename to Open:") displayFile_2(fnm) elif ch==3: fnm=input("Enter the Filename to append Data:") appendData(fnm) else: break
true
30342271877f7edcf5c7b66362c5955599dee4f7
suraj13mj/Python-Practice-Programs
/38. Python 15-04-20 --- NumPy/Program2.py
498
4.125
4
# Program to read a m x n matrix and find the sum of each row and each column import numpy as np print("Enter the order of the Matrix:") r = int(input()) c = int(input()) arr = np.zeros((r,c),dtype=np.int8) print("Enter matrix of order "+str(r)+"x"+str(c)) for i in range(r): for j in range(c): arr[i,j] = int(input()) for i in range(r): row = arr[i,...] print("Sum of Row "+str(i)+"="+str(sum(row))) for i in range(c): col = arr[...,i] print("Sum of Column "+str(i)+"="+str(sum(col)))
true
cc88f1c06b6491398275065144285e7ab8e033ca
Mhtag/python
/oops/10public_protected_pprivate.py
862
4.125
4
class Employee: holidays = 10 # Creating a class variables. var = 10 _protec = 9 # Protected variables can be used by classes and sub classes. __private = 7 # Private Variables can be used by only this class. def __init__(self, name, salary, role): self.name = name self.salary = salary self.role = role # Self is the object where this function will run def printdetails(self): return f'Name is {self.name}, salary is {self.salary}, role is {self.role}.' @classmethod def change_holidays(cls, newholidays): cls.holidays = newholidays # Class method as an alternative constructor. @classmethod def from_str(cls, string): return cls(*string.split('-')) emp = Employee('Mohit', 222, 'programmer') print(emp._protec) print(emp.__private)
true
1236969d33c8c56768f35f63367e8fd54db295ab
BALAVIGNESHDOSTRIX/py-coding-legendary
/Advanced/combin.py
473
4.1875
4
''' Create a function that takes a variable number of arguments, each argument representing the number of items in a group, and returns the number of permutations (combinations) of items that you could get by taking one item from each group. Examples: combinations(2, 3) ➞ 6 combinations(3, 7, 4) ➞ 84 combinations(2, 3, 4, 5) ➞ 120 ''' def combinations(*items): num = 1 for x in items: if x != 0: num = num * x return num
true
7c2acffba62cb6408f085fb2bf233c1ac2714c64
jotawarsd/Shaun_PPS-2
/assignments_sem1/assign6.py
375
4.3125
4
''' Assignment No: 6 To accept a number from user and print digits of number in a reverse order using function. ''' num1 = input("number : ") #get input from user def reverse(s1): n = len(s1) - 1 #establish index of last digit for i in range(n,-1,-1): #printing the number in reverse print(s1[i], end='') print("reverse = ", end = '') reverse(num1)
true
b97639963d80069a0c86b5eac5b58cae944877fd
guohuacao/Introduction-Interactive-Programming-Python
/week2-Guess-The-Number.py
2,559
4.21875
4
# "Guess the number" mini-project # This code runs under http://www.codeskulptor.org/ with python 2.7 #mini-project description: #Two player game, one person thinks of a secret number, the other peson trys to guess #In this program, it will be user try to guess at input field, program try to decide #"higher", "lower" or "correct" # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math num_range = 100 remaining_guess = 7 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global num_range global computer_guess global remaining_guess if (num_range == 100): remaining_guess = 7 else: remaining_guess = 10 print "\n" print "New game. Range is from 0 to ",num_range print "Number of remaining guess is ",remaining_guess computer_guess = random.randint(0, num_range) #print "computer gues was " ,computer_guess # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global num_range global remaining_guess num_range = 100 remaining_guess = 7 new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global num_range global remaining_guess num_range = 1000 remaining_guess = 10 new_game() def input_guess(guess): global num_range global computer_guess global remaining_guess print "guess was ", guess guess_int = int(guess) if (guess_int > num_range or guess_int < 0): print 'number is out of range' elif guess_int > computer_guess: print 'Lower!' remaining_guess -=1 print "remaining guess is ",remaining_guess elif guess_int < computer_guess: print 'Higher!' remaining_guess -= 1 print "remaining guess is ",remaining_guess else: print 'Correct!' new_game() if (remaining_guess==0): print "Number of remaining guesses is 0" print " You ran out of guesses. The number was ", computer_guess new_game() else: print "\n" # create frame f = simplegui.create_frame("guess number", 200, 200) f.add_button("Range is [0, 100)", range100, 200) f.add_button("Range is [0, 1000)", range1000, 200) f.add_input("Enter a guess", input_guess, 200) new_game() # always remember to check your completed program against the grading rubric
true
e33f71ec867753fa1a5029f0891fad03c9fce52b
sachinsaxena021988/Assignment7
/MovingAvarage.py
599
4.15625
4
#import numpy module import numpy as np #define array to for input value x=np.array([3, 5, 7, 2, 8, 10, 11, 65, 72, 81, 99, 100, 150]) #define k as number of column k=3 #define mean array to add the mean meanarray =[] #define range to loop through numpy array for i in range(len(x)-k+1): #internal sum of all kth value internalSum =0.0 for j in range(i,i+k): internalSum =internalSum+x[j] meanarray.append(internalSum/k) #print mean array print(meanarray)
true
4fa2954258c033bc635614a03bde2f888e9e360f
Veraxvis/PRG105
/5.2/derp.py
726
4.1875
4
def main(): costs = monthly() print("You spend", '$' + "{:,.2f}".format(costs) + " on your car per month.") per_year = yearly(costs) print("In total you spend", '$' + "{:,.2f}".format(per_year) + " on your car per year.") def monthly(): car_payment = float(input("Please enter your monthly car payment: ")) insurance = float(input("Please enter your monthly insurance bill: ")) gas = float(input("Please enter how much you spend on gas each month: ")) repairs = float(input("Please enter how much you spend on repairs: ")) monthly_total = car_payment + insurance + gas + repairs return monthly_total def yearly(monthly_total): year = monthly_total * 12 return year main()
true
7a23e70d9095909a575ebcad73b29b016b8f4da0
miklo88/cs-algorithms
/single_number/single_number.py
1,612
4.125
4
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' ''' UPER UPER TIME so this function takes in a list of ints. aka a list[1,2,3,4,5,6] of nums where every int shows up twice except one so like list[1,1,2,2,3,4,4,5,5,6,6] so i need to return the int that is only listed once in a list. "so what needs to be done" as an arr list being passed into single_number(arr): fn i need to look over each value in that list. while doing so i need to be able to check each value and see if there are more than one of the same value. if there is only one of a certain value. then return it. "how am i going to do it?" i'm thinking that i need to loop over the data, so either a for or while loop - then check each value if it meets certain conditions. if elif else. most likely if and else will be needed. ''' ''' solution, returning the sum of the set of the arr. so grabbing each individual unique element and adding them all up.then mult that sum by 2. then you add up the entire array. you take the sum of the set *2 - this second sum of all ele in arr and you get the difference which equals the one element that doesnt have a double. DOES NOT WORK FOR MULTIPLE ELEMENTS WITH ONLY ONE INT. it returns the sum of both nums of the single ints. ''' def single_number(arr): # Your code here return 2 * sum(set(arr)) - sum(arr) if __name__ == '__main__': # Use the main function to test your implementation arr = [1, 1, 4, 4, 5, 5, 3, 3, 9, 0, 0] print(set(arr)) print(f"The odd-number-out is {single_number(arr)}") # print(arr)
true
235df1baba7c9ffe9222dfee29da356e2a1762fa
timlax/PythonSnippets
/Create Class v2.py
1,369
4.21875
4
class Animal(object): """All animals""" alive = "" # Define the initialisation function to define the self attributes (mandatory in a class creation) def __init__(self, name, age): # Each animal will have a name and an age self.name = name self.age = age # The description function will print the animals name & age attributes def description(self): print(self.name) print(self.age) # The SetAlive function will define the attribute "alive" for an animal as alive def setAlive(self, alive): self.alive = alive # The getAlive function will show the value of the attribute "alive" for an animal def getAlive(self): return self.alive # Define your first animal with its values for the "self attributes" horse = Animal("Hilda", 22) # Call the description function to print name & age horse.description() # Call the setAlive function to define that your animal is alive horse.setAlive(True) # Call the getAlive function to know if your animal is alive print(horse.getAlive()) # Call the setAlive function to define that your animal is NOT alive horse.alive=False # Call the getAlive function to know if your animal is alive print(horse.getAlive()) # Change the value of the age attribute for your selected animal & print the new age horse.age += 1 print(horse.age)
true
c9894657052e2db7a9bafdf51ae0f63fe25258bb
mikkope123/ot-harjoitustyo
/src/city/city.py
1,752
4.5
4
import math class City: """A class representing a city on the salesman's route.': Attributes: x1, x2: cartesian coordinates representing the location of the city on the map """ def __init__(self, x1: float, x2: float): """Class constructor that creates a new city Args: self.__x1, self.__x2: cartesian coordinates representing the location of the city on the map""" self.__x1 = x1 self.__x2 = x2 def __str__(self): """Returns the string attribute of the class. Returns: A string consisting of a tuple of city coordinates.""" city_tuple = (self.__x1, self.__x2) return str(city_tuple) def distance(self, other): """Calculates the distance from the city to another Args: City class object Returns: euclidian distance between the cities""" return math.sqrt((self.__x1-other.__x1)**2 + (self.__x2-other.__x2)**2) def find_nearest(self, other_cities): """Finds the city nearest to this one. Args: A list of cities. Returns: A tuple consisting of the nearest city and the distance from self to there.""" nearest_city = None shortest_distance = math.inf for city in other_cities: r = self.distance(city) if r < shortest_distance: shortest_distance = r nearest_city = city return (nearest_city, shortest_distance) def get_coordinates(self): """A method to get the cartesian coordinates of the city. Returns: Cartesian coordinates of the city.""" return self.__x1, self.__x2
true
dff9d0f6b9dca11422d9d97ff54352aca8e6eacf
Faranaz08/assignment_3
/que13.py
600
4.1875
4
#write a py program accept N numbers from the user and find the sum of even numbers #product of odd numbers in enterd in a list lst=[] even=[] odd=[] sum=0 prod=1 N=int(input("enter the N number:")) for i in range(0,N): ele = int(input()) lst.append(ele) if ele%2==0: even.append(ele) sum=sum+ele else: odd.append(ele) prod=prod*ele print(lst) print("Even numbers :" +str(even)) print("odd numbers :" +str(odd)) print("the sum of even numbers in list :"+str(sum)) print("the product of odd numbers in the list :"+str(prod))
true
2b783a4762657b56447de189929a210aa8e69bac
exclusivedollar/Team_5_analyse
/Chuene_Function_3.py
724
4.28125
4
### START FUNCTION """This function takes as input a list of these datetime strings, each string formatted as 'yyyy-mm-dd hh:mm:ss' and returns only the date in 'yyyy-mm-dd' format. input: list of datetime strings as 'yyyy-mm-dd hh:mm:ss' Returns: returns a list of strings where each element in the returned list contains only the date in the 'yyyy-mm-dd' format.""" def date_parser(dates): # Creating a new date list. date_only = [] for date in dates: my_list = date[:len(date)-9] # Append values from my list to date_only list. date_only.append(my_list) date_only[:] # returned list contains only the date in the 'yyyy-mm-dd' format. return date_only ### END FUNCTION
true
987de188f535849170f5d44dafef82c543ad1bb6
sstagg/bch5884
/20nov05/exceptionexample.py
237
4.125
4
#!/usr/bin/env python3 numbers=0 avg=0 while True: inp=input("Please give me a number or the word 'Done': ") if inp=="Done": break else: x=float(inp) avg+=x numbers+=1 avg=avg/numbers print ("The average is %.2f" % (avg))
true
cee079505a684ef5a58041492ed437eba43572b5
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.9 Functions/1. What are Functions.py
1,282
4.5625
5
# Functions are a convenient way to divide your code into useful blocks, # allowing us to order our code, make it more readable, reuse it and save some time. # Also functions are a key way to define interfaces so programmers can share their code. # How do you write functions in Python? # As we have seen on previous tutorials, Python makes use of blocks. # A block is a area of code of written in the format of: # block_head: # 1st block line # 2nd block line # ... # Where a block line is more Python code (even another block), and the block head is of the following format: # block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while". # Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. # For example: def my_function(): print("Hello From My Function!") # declaration # Functions may also receive arguments (variables passed from the caller to the function). For example: def my_function_with_args(username, greeting): print("Hello, %s , From My Function!, I wish you %s"%(username, greeting)) # Functions may return a value to the caller, using the keyword- 'return' . For example: def sum_two_numbers(a, b): return a + b
true
a10abea0005837374d7908ed655aa4fddfe87e61
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.2 Variables and Types/1. Numbers.py
628
4.4375
4
# Python supports two types of numbers - integers and floating point numbers. (It also supports complex numbers, which # will not be explained in this tutorial). # To define an integer, use the following syntax: myint = 7 print("Integer Value printed:",myint) # To define a floating point number, you may use one of the following notations: myfloat = 7.0 print("Float Value printed:",myfloat) myfloat = float(7) print("Float Value printed:",myfloat) # Assignments can be done on more than one variable "simultaneously" on the same line like this a , b = 3 , 4 print("print a:",a) print("print b:",b) print("print a,b:", a,b)
true
55d49ce7240c7af9c27430d134507103cc6739c7
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.11 Dictionaries/1. Basics.py
688
4.15625
4
# A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. # Each value stored in a dictionary can be accessed using a key, # which is any type of object (a string, a number, a list, etc.) instead of using its index to address it. # For example, a database of phone numbers could be stored using a dictionary like this: phonebook = {} phonebook["John"] = 938477561 phonebook["Jack"] = 938377262 phonebook["Jill"] = 947662783 print(phonebook) # Alternatively, a dictionary can be initialized with the same values in the following notation: phonebook2 = { "Jony" : 938477564, "Jay" : 938377265, "Jeny" : 947662786 } print(phonebook2)
true
a9ad5d63cd98a178b4efdf2343c9e4f083d42a24
uc-woldyemm/it3038c-scripts
/Labs/Lab5.PY
486
4.15625
4
print("Hello Nani keep doing your great work") print("I know you're busy but is it okay if i can get some information about you") print("How many years old are you?") birthyear = int(input("year: ")) print("What day you born") birthdate = int(input("date: ")) print("Can you also tell me what month you were born") birthmonth = int(input("month: ")) seconds = birthyear * 24 * 60 * 60 * 365 + birthmonth * 30 * 60 + birthdate * 60 print ("you are about" , seconds , "seconds old")
true
235bd7c02a7555c8d059e401b18bf9bb4c6ee2dc
PranilDahal/SortingAlgorithmFrenzy
/BubbleSort.py
854
4.375
4
# Python code for Bubble Sort def BubbleSort(array): # Highest we can go in the array maxPosition = len(array) - 1 # Iterate through the array for x in range(maxPosition): # For every iteration, we get ONE sorted element. # After x iterations, we have x sorted elements # We don't swap on the sorted side - only go up to (maxPosition-x) for y in range(0,maxPosition - x): # If an element is greater than the element after it, swap places if array[y] > array[y+1]: array[y], array[y+1] = array[y+1], array[y] #Done! def main(): TestArray = [3,11,98,56,20,19,4,45,88,30,7,7,7,8,8] BubbleSort(TestArray) print ("#LetsCodeNepal: The bubble sorted result is-") for i in range(len(TestArray)): print ("%d" %TestArray[i]) if __name__ == '__main__': main()
true
7a5ecb354bfdd283896bcbfdb5b177bd53b90b15
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/WildCardMatching.py
1,442
4.40625
4
""" String matching where one string contains wildcard characters Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. * --> Matches with 0 or more instances of any character or set of characters. ? --> Matches with any one character. For example, “g*ks” matches with “geeks” match. And string “ge?ks*” matches with “geeksforgeeks” (note ‘*’ at the end of first string). But “g*k” doesn’t match with “gee” as character ‘k’ is not present in second string. """ def match(str1,str2,first,second): if first == len(str1) and second == len(str2) : return True if first < len(str1) and second == len(str2) : return False if (first < len(str1) and str1[first] == '?' ) or (first<len(str1) and second < len(str2) and str1[first]==str2[second]) : return match(str1,str2,first+1,second+1) if first < len(str1) and str1[first] == '*' : return match(str1,str2,first,second+1) or match(str1,str2,first+1,second+1) return False if __name__=='__main__': print(match('g*ks','geeksforgeeks',0,0)) print(match('ge?ks','geeks',0,0)) print(match('g?ek*','geeksforgeeks',0,0)) print(match('*p','geeks',0,0))
true
38333c31be9bf385cbc0ad0f612ce39907f30648
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/MoveLastToFirst.py
787
4.46875
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList """ Move last element to front of a given Linked List Write a C function that moves last element to front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. """ def move_nth(head): if not head : return else : current = head prev = head while current.next is not None : prev = current current = current.next prev.next = None current.next = head head = current return head if __name__=='__main__': ll = LinkedList() for i in range(1,10): ll.insert_at_ending(i) ll.head = move_nth(ll.head) ll.print_list()
true
b5a1b48719e01685184f6546f5bac08e7804502e
vidyasagarr7/DataStructures-Algos
/Cormen/2.3-5.py
761
4.125
4
def binary_search(input_list,key): """ Binary search algorithm for finding if an element exists in a sorted list. Time Complexity : O(ln(n)) :param input_list: sorted list of numbers :param key: key to be searched for :return: """ if len(input_list) is 0: return False else : mid = len(input_list)//2 if key == input_list[mid]: return True elif key < input_list[mid-1]: return binary_search(input_list[:mid-1],key) elif key > input_list[mid]: return binary_search(input_list[mid:],key) if __name__=="__main__": test = [23,45,65,13,778,98,25,76,48,28,85,97] test.sort() print(binary_search(test,98)) print(binary_search(test,12))
true
f0420e011a39072b2edd46884b9bcdb1ede1270b
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/CheckConsecutive.py
1,492
4.125
4
import sys """ Check if array elements are consecutive | Added Method 3 Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers. Examples: a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5. b) If array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83. c) If the array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive. d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive. """ def check_duplicates(input_list): return len(input_list) == len(set(input_list)) def check_consecutive(input_list): if not input_list : return else : _max = -sys.maxsize _min = sys.maxsize for num in input_list : if num < _min : _min = num if num > _max : _max = num if _max - _min == len(input_list)-1 and check_duplicates(input_list): return True return False if __name__=='__main__': test = [5, 2, 3, 1, 4] print(check_consecutive(test)) test1 = [83, 78, 80, 81, 79, 82] print(check_consecutive(test1)) test2 = [34, 23, 52, 12, 3] print(check_consecutive(test2)) test3 = [7, 6, 5, 5, 3, 4] print(check_consecutive(test3))
true
7eefbcb7099c14384b4046d2cfcece1fba35a473
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/InsertSpaceAndPrint.py
916
4.15625
4
""" Print all possible strings that can be made by placing spaces Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C """ def toString(List): s = [] for x in List: if x == '\0': break s.append(x) return ''.join(s) def print_string(string,out_str,i,j): if i == len(string) : out_str[j] = '\0' print(toString(out_str)) return out_str[j] = string[i] print_string(string,out_str,i+1,j+1) out_str[j] = ' ' out_str[j+1] = string[i] print_string(string,out_str,i+1,j+2) def print_strings(string): n = len(string) out_str = [0]*2*n out_str[0]=string[0] print_string(string,out_str,1,1) if __name__=='__main__': string = 'abc' print(print_strings(string))
true
dd9088ed2e952a61cbc2f117274edd650d4aae16
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/ReverseAlternateKnodes.py
1,182
4.15625
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList """ Reverse alternate K nodes in a Singly Linked List Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL. """ def reverse_alt_knodes(head,k): if not head : return else : current = head next = None prev = None count = 0 while current and count < k : next = current.next current.next = prev prev = current current = next count += 1 if next : head.next = current count = 0 while current and count < k-1 : current = current.next count += 1 if current : current.next = reverse_alt_knodes(current.next,k) return prev if __name__=='__main__': ll = LinkedList( ) for i in range(1,10): ll.insert_at_ending(i) ll.head = reverse_alt_knodes(ll.head,3) ll.print_list()
true
57e66fcfe37a98d3b167627e8d0451ad9f37f567
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/ConstantSumTriplet.py
1,203
4.25
4
""" Find a triplet that sum to a given value Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. For example, if the given array is {12, 3, 4, 1, 6, 9} and given sum is 24, then there is a triplet (12, 3 and 9) present in array whose sum is 24. Solution : - Brute force - use 3 nested loops - O(n^3) - Sort and iterating through the list, use two pointers for start and end - O(n^2) """ def find_triplet(input_list,value): input_list.sort() for i in range(len(input_list)): left = i+1 right = len(input_list)-1 while left < right : if input_list[i] + input_list[left] + input_list[right] > value : right = right -1 elif input_list[i] + input_list[left] + input_list[right] < value : left = left + 1 else : return input_list[i],input_list[left],input_list[right] return 'sum not found' if __name__=="__main__": input_list = [12, 3, 4, 1, 6, 9] value = 24 print(find_triplet(input_list,value))
true
6356464fb2f5e1c1440e0a5af8c7bc2ab5188183
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/TwoRepeatingNumbers.py
1,133
4.28125
4
""" Find the two repeating elements in a given array You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. For example, array = {4, 2, 4, 5, 2, 3, 1} and n = 5 The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2. """ def find_repeating(input_list,n): if not input_list : return else : _xor = input_list[0] for i in range(1,n+1): _xor = _xor ^ input_list[i] ^ i _xor = _xor ^ input_list[n+1] set_bit = _xor & ~(_xor-1) a,b = 0,0 for i in range(len(input_list)): if input_list[i] & set_bit : a = a ^ input_list[i] else: b = b ^ input_list[i] for i in range(1,n+1): if i & set_bit : a = a ^ i else : b = b^i return a,b if __name__=='__main__': test = [4, 2, 4, 5, 2, 3, 1] print(find_repeating(test,5))
true
ee861e0efdb6e5515dd24ad97b15d2fecefde994
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/NthElement.py
877
4.125
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList,Node """ Write a function to get Nth node in a Linked List Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output: 30 The node at index 2 is 30 """ def getNthNode(head,n): """ function to return nth node from the start in a singly linkedlist :param head: :param n: nth node :return: """ if not head : return None count = 0 temp = head while temp and count < n: temp = temp.next count += 1 if temp : return temp.data else : return temp if __name__=="__main__": ll = LinkedList() for i in range(1,10): ll.insert_at_begining(i) print(getNthNode(ll.head,5)) xt
true
c71547e58e1d6c3c5d5caade6d1091312a3d6f71
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/PrintDistinctPermutations.py
1,065
4.125
4
""" Print all distinct permutations of a given string with duplicates Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output. Examples: Input: str[] = "AB" Output: AB BA Input: str[] = "AA" Output: AA Input: str[] = "ABC" Output: ABC ACB BAC BCA CBA CAB Input: str[] = "ABA" Output: ABA AAB BAA Input: str[] = "ABCA" Output: AABC AACB ABAC ABCA ACBA ACAB BAAC BACA BCAA CABA CAAB CBAA REVISIT """ def print_distinct_permutations(input_string,left,right): if left==right: print(''.join(input_string)) else: #print('printing left {}'.format(left)) for i in range(left,right): input_string[left],input_string[i] = input_string[i],input_string[left] print_distinct_permutations(input_string,left+1,right) input_string[left],input_string[i]=input_string[i],input_string[left] if __name__=='__main__': string = list('ABCD') print_distinct_permutations(string,0,len(string))
true
b5b4d136247ccd07ddc1da1a665775f36c1713a4
vidyasagarr7/DataStructures-Algos
/Trees/SearchElement.py
1,191
4.21875
4
from Karumanchi.Trees import BinaryTree from Karumanchi.Queue import Queue def search_element(node,element): """ Algorithm for searching an element Recursively :param node: :param element: :return: """ if not node: return False else: if node.data == element: return True return search_element(node.get_left(),element) or search_element(node.get_right(),element) def _search_element(root,element): """ Non-Recursive implementation for searching an element in binary Tree :param root: :param element: :return: """ if not root : return False else: que = Queue.Queue1() que.enqueue(root) while not que.is_empty(): node = que.dequeue() if node.data == element: return True if node.get_left(): que.enqueue(node.get_left()) if node.get_right(): que.enqueue(node.get_right()) return False if __name__=="__main__": tree= BinaryTree() for i in range(1,10): tree.add_node(i) for i in range(1,15): print(_search_element(tree.root,i))
true
18858b1ec937e1850ab9ae06c83dc35d15d36c85
vidyasagarr7/DataStructures-Algos
/609-Algos/Lab-2/BubbleSort.py
513
4.28125
4
def bubble_sort(input_list): """ Bubble Sort algorithm to sort an unordered list of numbers :param input_list: unsorted list of numbers :return: sorted list """ for i in range(len(input_list)): for j in range(len(input_list)-1-i): if input_list[j]>input_list[j+1]: input_list[j],input_list[j+1] = input_list[j+1],input_list[j] return input_list if __name__=="__main__": test = [23,25,12,14,17,85,98,34,32,109,56] print(bubble_sort(test))
true
2f45a066f0b461b0992094cb8f515ce3f4dd2269
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/ReverseWords.py
420
4.4375
4
""" Reverse words in a given string Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i” """ def reverse_words(string): words_list = string.split(' ') words_list.reverse() return ' '.join(words_list) if __name__=='__main__': string = ' i like this program very much ' print(reverse_words(string))
true
e20c9d2168f9e5c23ef638185ae2e00adbb90dfa
vidyasagarr7/DataStructures-Algos
/Karumanchi/Searching/CheckDuplicates.py
1,726
4.28125
4
from Karumanchi.Sorting import MergeSort from Karumanchi.Sorting import CountingSort def check_duplicates(input_list): """ O(n^2) algorithm to check for duplicates :param input_list: :return: """ for i in range(len(input_list)): for j in range(i+1,len(input_list)): if input_list[i]==input_list[j]: return True return False def check_duplicates_opt(input_list): """ O(n*log(n)) algorithm - Sort the list :param input_list: :return: """ sorted_list = MergeSort.merge_sort(input_list) for i in range(len(sorted_list)-1): if sorted_list[i] == sorted_list[i+1]: return True return False def check_duplicates_opt2(input_list): """ considering the input elements in the range 0-(n-1) --> we can sort the array using counting sort in O(n) time and traverse in linear time :param input_list: :return: """ sorted_list = CountingSort.counting_sort(input_list,10) for i in range(len(sorted_list)-1): if sorted_list[i]==sorted_list[i+1]: return True return False def check_duplicates_negation(input_list): """ Assumption : input list values range from 0-(n-1) and all numbers are positive. :param input_list: :return: """ for i in range(len(input_list)): if input_list[input_list[i]]<0: return True else : input_list[input_list[i]] = -input_list[input_list[i]] return False if __name__=="__main__": test = [1,2,3,4,6,7,8,9,4] print(check_duplicates(test)) print(check_duplicates_opt(test)) print(check_duplicates_opt2(test)) print(check_duplicates_negation(test))
true
2ef19d4886644d077c1f53c97f7de400c7019540
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/Rearrange.py
1,096
4.1875
4
""" Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space Given an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space. Examples: Input: arr[] = {3, 2, 0, 1} Output: arr[] = {1, 0, 3, 2} Input: arr[] = {4, 0, 2, 1, 3} Output: arr[] = {3, 4, 2, 0, 1} Input: arr[] = {0, 1, 2, 3} Output: arr[] = {0, 1, 2, 3} If the extra space condition is removed, the question becomes very easy. The main part of the question is to do it without extra space. """ def rearrange(input_list): if not input_list : return else : n = len(input_list) for i in range(len(input_list)) : input_list[i] += (input_list[input_list[i]]%n)*n for i in range(len(input_list)): input_list[i] = input_list[i]//n return input_list if __name__=='__main__': test = [3, 2, 0, 1] print(rearrange(test)) test = [4,0,2,1,3] print(rearrange(test)) test = [0,1,2,3] print(rearrange(test))
true
4b1793f6d8c391ad17ecdfabc74702886aa02ebc
vidyasagarr7/DataStructures-Algos
/Karumanchi/Selection/KthSmallest.py
1,531
4.40625
4
from Karumanchi.Sorting import QuickSort def partition(list,start,end): """ Partition Algorithm to partition a list - selecting the end element as the pivot. :param list: :param start: :param end: :return: """ i=start-1 pivot = list[end] for j in range(start,end): if list[j] <= pivot: i+=1 list[i],list[j]=list[j],list[i] list[i+1],list[end]=list[end],list[i+1] return i+1 def _find_k_smallest(input_list,start,end,k): """ Algorithm using partitioning for finding kth smallest number. :param input_list: :return: """ if k>0 and k <= end-start+1: part = QuickSort.partition_end(input_list,start,end) if part-start == k-1: return input_list[part] elif part-start> k-1: return _find_k_smallest(input_list,start,part-1,k) else: return _find_k_smallest(input_list,part+1,end,k-part+start-1) return False def find_k_smallest(input_list,k): return _find_k_smallest(input_list,0,len(input_list)-1,k) def find_k_smallest_opt(input_list,k): """ Median of medians. :param input_list: :param k: :return: """ return 0 def find_median(input_list): """ Algorithm to find the median of inputlist :param input_list: :return: """ return find_k_smallest(input_list,len(input_list)//2) if __name__=="__main__": test_input = [3,2,1,7,6,5,8,9,4,5,10,11,12,13,14,15] print(find_median(test_input))
true
0f1edc71a026eac62eb4b641c0bd9ede2a98bbee
imran9891/Python
/PyFunctionReturns.py
882
4.125
4
#!/usr/bin/env python # coding: utf-8 # <h3 align="center">Function Return</h3> # In[ ]: def sum1(num1, num2): def another_func(n1,n2): return n1 + n2 return another_func def sum2(num1, num2): def another_func2(n1,n2): return n1 + n2 return another_func2(num1, num2) print(sum1(10,5)) # this will just return the address of the function print(sum1(10,5)(5,8)) # this will give arguments to the another_func # above is same as doing: total = sum1(10,5) print(total) print(total(5,8)) print(sum2(10,5)) # print(another_func(45, 55)) # this will give error, because the function is actually undefined # , and to call this function, first we will have to call the # parent function. So we can get the memory location of the # function.
true
d7c4c21563a09c85d82d652626eb7f5230b9254d
khairooo/Learn-linear-regression-the-simplest-way
/linear regression.py
1,829
4.4375
4
# necessary packages import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error,r2_score # generate random data-set np.random.seed(0) # generate 100 random numbers with 1d array x = np.random.rand(100,1) y = 2 + 3 * x + np.random.rand(100,1) # Implemantations with sckit- learn # Model initialization regression_model = LinearRegression() # fit the data (train the model) regression_model.fit(x,y) # Predict y_predicted = regression_model.predict(x) # hint: '''to visualize the data we can just import the misxtend packages as follow: >>>from mlxtend.plotting import plot_linear_regression >>>intercept, slope, corr_coeff = plot_linear_regression(X, y) >>>plt.show() ''' # Model evaluation: # 1) rmse (root mean squared error) '''what happen here under the hood is a juste the implimentation of the math equation >>> np.sqrt(((predictions - targets) ** 2).mean())''' rmse = mean_squared_error(y,y_predicted) # 2) R2 ( coefficient of determination) '''Explains how much the total variance of the dependent varaible can be reduced by using the least sqaured regression mathematically : R2 = 1 - (SSr/SSt) where: # sum of square of residuals ssr = np.sum((y_pred - y_actual)**2) # total sum of squares sst = np.sum((y_actual - np.mean(y_actual))**2) # R2 score r2_score = 1 - (ssr/sst) ''' r2 = r2_score(y,y_predicted) # Printing values,slope, intercept, root mean squared error, r2 print('Slope:' ,regression_model.coef_) print('Intercept:', regression_model.intercept_) print('Root mean squared error: ', rmse) print('R2 score: ', r2) # plotting values : # data points plt.scatter(x, y, s=10) plt.xlabel('x') plt.ylabel('y') plt.show()
true
efa056ec08f3358df04e1da1bdef6db73dec39c3
chenlongjiu/python-test
/rotate_image.py
936
4.25
4
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? ''' class Solution(object): def rotate(self, matrix): for row in xrange(len(matrix)): for col in xrange(row,len(matrix)): matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col] #then reverse: for row in xrange(len(matrix)): for col in xrange(len(matrix)/2): matrix[row][col], matrix[row][-col-1] = matrix[row][-col-1], matrix[row][col] print matrix[0] print matrix[1] print matrix[2] print "//////////////////////////" #print matrix """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix = [[1,2,3],[4,5,6],[7,8,9]] print Solution().rotate(matrix)
true
4debf55c34b266031b2c68890e629717f6043d76
geekysid/Python-Basics
/4. Dictionary/Dictionary Challenge Modified 2.py
1,714
4.21875
4
# Modify the program so that the exits is a dictionary rather than a list, with the keys being the numbers of the # locations and the values being dictionaries holding the exits (as they do at present). No change should be needed # to the actual code. locations = {0: "You are sitting in front of a computer learning Python", 1: "You are standing at the end of a road before a small brick building", 2: "You are at the top of a hill", 3: "You are inside a building, a well house for a small stream", 4: "You are in a valley beside a stream", 5: "You are in the forest"} # Here we simply converted list to dictionary by using index of list as the key of the map. This makes our code work # without any change exits = {0: {"Q": 0}, 1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, 2: {"N": 5, "Q": 0}, 3: {"W": 1, "Q": 0}, 4: {"N": 1, "W": 2, "Q": 0}, 5: {"S": 1, "W": 2, "Q": 0}} loc = 1 while True: print() # Using join() to fetch and converts all the keys of the exits[loc] dictionary availableMovements = ", ".join(exits[loc].keys()) print(f"{locations[loc]}") userInput = input("Available Movements Are: {}\nPlease enter where you wnt to move: ".format(availableMovements)) if userInput.upper() in exits[loc].keys(): # checking if the direction entered by user or not loc = exits[loc][userInput.upper()] if loc == 0: # if user press 'Q' and want to exit print("You have successfully exited game.") break else: # if user enters invalid direction print("That is not a valid movements. Please try again.") continue
true
e75b0ab18452e7da90b5f6c81bc317224eaf24f1
jmshin111/alogrithm-test
/merge two sorted list.py
1,746
4.15625
4
# A single node of a singly linked list import sys import timeit class Node: # constructor def __init__(self, data=None): self.data = data self.next = None # A Linked List class with a single head node class LinkedList: def __init__(self): self.head = None self.end = None self.len = 1 def add(self, node): self.end.next = node self.end = node self.len = self.len + 1 # Linked List with a single node def mergeTwoSortedList(linked_list1, linked_list2): min_data = sys.maxsize result_linked_list = LinkedList() result_linked_list.end = result_linked_list.head = Node('start') while linked_list1 or linked_list2: if not linked_list1: result_linked_list.add(Node(linked_list2.data)) linked_list2 = linked_list2.next if not linked_list2: result_linked_list.add(Node(linked_list1.data)) linked_list1 = linked_list1.next if int(linked_list1.data) < int(linked_list2.data): result_linked_list.add(Node(linked_list1.data)) linked_list1 = linked_list1.next else: result_linked_list.add(Node(linked_list2.data)) linked_list2 = linked_list2.next return result_linked_list linked_list = LinkedList() linked_list.end = linked_list.head = Node(1) linked_list.add(Node(2)) linked_list.add(Node(4)) linked_list2 = LinkedList() linked_list2.end = linked_list2.head = Node(1) linked_list2.add(Node(3)) linked_list2.add(Node(4)) start_time = timeit.default_timer() print(mergeTwoSortedList(linked_list.head, linked_list2.head)) terminate_time = timeit.default_timer() # 종료 시간 체크 print("%f초 걸렸습니다." % (terminate_time - start_time))
true
439f8e77560fa42094e061ba7c4e1bd71956b8fd
mohdelfariz/distributed-parallel
/Lab5-Assignment3.py
1,284
4.25
4
# Answers for Assignment-3 # Importing mySQL connector import mysql.connector # Initialize database connection properties db_connection = mysql.connector.connect( host="localhost", user="root", passwd="", database="my_first_db" ) # Show newly created database (my_first_db should be on the list) print(db_connection) # (a)Write a MySQL statement to create a simple table countries including columns-country_id, country_name and region_id. # 1) Creating database_cursor to perform SQL operation db_cursor = db_connection.cursor() # 2) We create and execute command to create a database table (countries) db_cursor.execute( "CREATE TABLE countries(country_id INT AUTO_INCREMENT PRIMARY KEY, country_name VARCHAR(255), region_id INT(6))") # 3) Print the database table (Table countries should be on the list) db_cursor.execute("SHOW TABLES") for table in db_cursor: print(table) # (b)Write a MySQL statement to rename the table countries to country_new. # 1) Altering the database table countries name db_cursor.execute( "ALTER TABLE countries RENAME TO country_new") # 2) Print the newly altered table (countries should changed to country_new) db_cursor.execute("SHOW TABLES") for table in db_cursor: print(table)
true
453d4cfd55465b4793848e9ba7935aff0592dde1
gopikris83/gopi_projects
/GlobalVariables.py
401
4.25
4
# -------- Defining variables outside of the function (Using global variables) ---------------- x = "Awesome" def myfunc(): print (" Python is "+x) myfunc() # ---------- Defining variables inside of the function (Using local variables) -------------------------- x = "Awesome" def myfunc(): x = "Fantastic" print ("Python is "+x) myfunc() print ("Python is"+x)
true
e65c2135625c668523ea865f75bc320b2cdab043
gr8tech/pirple.thinkific.com
/Python/Homework3/main.py
931
4.1875
4
''' Python Homework Assignment 3 Course: Python is Easy @ pirple Author: Moosa Email: gr8tech01@gmail.com `If` statements; Comparison of numbers ''' def number_match(num1, num2, num3): ''' Functions checks if 2 or more of the given numbers are equal Args: num1, num2, num3 num1, num2, num3 can be an Integer or an Integer string Returns: True if 2 or more numbers are equal, False otherwise Examples: number_match(1,2,1) returns True number_match(1,2,"1") returns True number_match(1,2,3) return False Logic: There are three posibilities 1. num1 is equal to num2 OR 2. num1 is equal to num3 OR 3. num2 is equal to num3 ''' num1, num2, num3 = int(num1), int(num2), int(num3) if (num1 == num2) or (num1 == num3) or (num2 == num3): return True else: return False # Function tests # Returns False print(number_match(1,2,3)) # Returns True print(number_match(1,2,1)) #Returns True print(number_match("5",6,5))
true
1582966887ebcfcec8a2ddb74e0823cb7b72c95e
Chethan64/PESU-IO-SUMMER
/coding_assignment_module1/5.py
212
4.25
4
st = input("Enter a string: ") n = len(st) flag = 0 for i in st: if not i.isdigit(): flag = 1 if(flag): print("The string is not numeric") else: print("The string is numeric")
true
b024cf8229c1ea31c1299d283b52375d0c11ec10
Abdelmuttalib/Python-Practice-Challenges
/Birthday Cake Candles Challenge/birthDayCakeCandles.py
815
4.15625
4
####### SOLUTION CODE ######## def birthdayCakeCandles(candles): ## initializing an integer to hold the value of the highest value highest = 0 ## count of highest to calculate how many the highest value is found in the array count_of_highest = 0 ## iterate over the array to determine the highest value for i in candles: if i > highest: highest = i ## iterate over the array to determine how many time the highest value occurs for i in candles: if i == highest: count_of_highest += 1 ## Returning the number of times the highest value is found in the array return count_of_highest ## Simple Test print(birthdayCakeCandles([2, 4, 6, 6])) """ OUTPUT: 2 ## as the highest number is 6 and it occurs two times in the array """
true
067c383afe1a81e2b864b2f8d274c2e7768ed190
shreyashg027/Leetcode-Problem
/Data Structure/Stacks.py
504
4.125
4
class Stack: def __init__(self): self.stack = [] def push(self, data): if data not in self.stack: self.stack.append(data) def peek(self): return self.stack[len(self.stack)-1] def remove(self): if len(self.stack) <= 0: return 'No element in the stack' else: return self.stack.pop() test = Stack() test.push('Mon') test.push('Tue') test.push('wed') print(test.peek()) print(test.remove()) print(test.peek())
true
4bce5f49c82972c9e7dadd48794bcc545e25095b
miketwo/euler
/p7.py
704
4.1875
4
#!/usr/bin/env python ''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' from math import sqrt, ceil def prime_generator(): yield 2 yield 3 num = 3 while True: num += 2 if is_prime(num): yield num def is_prime(num): for i in xrange(2, int(ceil(sqrt(num))) + 1): if num % i == 0: return False return True def main(): print is_prime(9) loop = 0 for prime in prime_generator(): loop += 1 print "{}: {}".format(loop, prime) if loop == 10001: break if __name__ == '__main__': main()
true
9e84eeb486846d437d69a8d08c717240cbb462a5
TejaswitaW/Advanced_Python_Concept
/RegEx12.py
260
4.125
4
#use of function fullmatch in regular expression import re s=input("Enter string to be matched") m=re.fullmatch(s,"abc") if(m!=None): print("Complete match found for the string:",m.start(),m.end()) else: print("No complete match found for the string")
true
d139c57f5add5f8be6008fad651ea3eca04e4c39
TejaswitaW/Advanced_Python_Concept
/ExceptionElse.py
385
4.15625
4
#Exception with else block #else block is executed only when there is no exception in try block try: print("I am try block,No exception occured") except: print("I am except block executed when there is exception in try block") else: print("I am else block,executed when there is no exception in try block") finally: print("I am finally block I get executed everytime")
true
1f4069a21af18b88a7ddf117162036d212f2135c
lfarnsworth/GIS_Python
/Coding_Challenges/Challenge2/2-List_Overlap.py
1,133
4.375
4
# 2. List overlap # Using these lists: # # list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] # list_b = ['dog', 'hamster', 'snake'] # Determine which items are present in both lists. # Determine which items do not overlap in the lists. # #Determine which items overlap in the lists: def intersection(list_a, list_b): list_c =[str for str in list_a if str in list_b] return list_c list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] list_b = ['dog', 'hamster', 'snake'] print('These are in common:') print(intersection(list_a, list_b)) print('\r\n') #Determine which items DO NOT overlap in the lists: list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] list_b = ['dog', 'hamster', 'snake'] def exclusion(list_a, list_b): list_c =[str for str in list_a if not str in list_b] list_c.extend([str for str in list_b if not str in list_a]) return list_c print('These are NOT in common:') print(exclusion(list_a, list_b)) print('\r\n') # Feedback - Great! Thanks for the helpful print statement in common/not in common. Keep an eye on how you are laying # out your code to keep it clean and organized.
true
f91c9dd7ea1c66a0a757d32dc00c3e1f0adef7e7
udhayprakash/PythonMaterial
/python3/06_Collections/03_Sets/a_sets_usage.py
1,219
4.40625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Purpose: Working with Sets Properties of sets - creating using {} or set() - can't store duplicates - sets are unordered - can't be indexed - Empty sets need to be represented using set() - stores only immutable object - basic types, tuple, string - sets are mutable objects """ running_ports = [11, 22, 11, 44, 22, 11] print("type(running_ports)", type(running_ports)) print("len(running_ports) ", len(running_ports)) print("running_ports ", running_ports) print() # Method 1 - To remove duplicates in a list/tuple of elements filtered_list = [] for each_port in running_ports: if each_port in filtered_list: continue filtered_list.append(each_port) print("len(filtered_list) ", len(filtered_list)) print("filtered_list: ", filtered_list) print() unique_ports = {11, 22, 11, 44, 22, 11} print(f"{type(unique_ports) =}") print(f"{len(unique_ports) =}") print(f"{unique_ports =}") print() # Method 2 - using sets to remove duplicates filtered_list = list(set(running_ports)) print("len(filtered_list) ", len(filtered_list)) print("filtered_list: ", filtered_list) print()
true
627c4ac2e040d41a4e005253e1dd7c20f9d5cf63
udhayprakash/PythonMaterial
/python3/04_Exceptions/11_raising_exception.py
1,248
4.28125
4
#!/usr/bin/python3 """ Purpose: Raising exceptions """ # raise # RuntimeError: No active exception to reraise # raise Exception() # Exception # raise Exception('This is an error') # Exception: This is an error # raise ValueError() # ValueError # raise TypeError() # raise NameError('This is name error') # NameError: This is name error try: raise NameError("This is name error") except NameError as ne: print(f"{ne =}") # try: # raise NameError('This is name error') # except NameError as ne: # ne.add_note("PLEASE ENSURE NOT TO REPEAT") # raise # # print(f"{ne =}") # NOT REACHABLE try: try: raise NameError("This is name error") except NameError as ne: ne.add_note("PLEASE ENSURE NOT TO REPEAT") raise # print(f"{ne =}") # NOT REACHABLE except Exception as ex: print(f"{ex =}") try: num1 = int(input("Enter an integer:")) num2 = int(input("Enter an integer:")) if num2 == 0: # raise Exception("Ensure that num2 is NON-ZERO") raise ZeroDivisionError("Ensure that num2 is NON-ZERO") except ZeroDivisionError as ze: print(repr(ze)) except Exception as ex: print(repr(ex)) else: division = num1 / num2 print(f"{division =}")
true
79eb6b4be07ee81b3a360a3fe2ab759947735a5e
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b1_process_pool.py
1,587
4.40625
4
""" Purpose: Multiprocessing with Pools Pool method allows users to define the number of workers and distribute all processes to available processors in a First-In-First-Out schedule, handling process scheduling automatically. Pool method is used to break a function into multiple small parts using map or starmap — running the same function with different input arguments. Whereas Process method is used to run different functions. """ import multiprocessing import os import time def task_sleep(sleep_duration, task_number): time.sleep(sleep_duration) print( f"Task {task_number} done (slept for {sleep_duration}s)! " f"Process ID: {os.getpid()}" ) if __name__ == "__main__": time_start = time.time() # Create pool of workers pool = multiprocessing.Pool(2) # Map pool of workers to process pool.starmap(func=task_sleep, iterable=[(2, 1)] * 10) # Wait until workers complete execution pool.close() time_end = time.time() print(f"Time elapsed: {round(time_end - time_start, 2)}s") # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 20464 # Time elapsed: 12.58s
true
6782bce539f905db7c05238f1b906edf054b5aeb
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_custom_thread_class.py
939
4.375
4
#!/usr/bin/python # Python multithreading example to print current date. # 1. Define a subclass using Thread class. # 2. Instantiate the subclass and trigger the thread. import datetime import threading class myThread(threading.Thread): def __init__(self, name, counter): threading.Thread.__init__(self) self.threadID = counter self.name = name self.counter = counter def run(self): print("Starting " + self.name) print_date(self.name, self.counter) print("Exiting " + self.name) def print_date(threadName, counter): datefields = [] today = datetime.date.today() datefields.append(today) print("%s[%d]: %s" % (threadName, counter, datefields[0])) # Create new threads thread1 = myThread("Thread", 1) thread2 = myThread("Thread", 2) # Start new Threads thread1.start() thread2.start() thread1.join() thread2.join() print("Exiting the Program!!!")
true
2e7734c27ca1713f780710c935c2981fa7bc0577
udhayprakash/PythonMaterial
/python3/09_Iterators_generators_coroutines/02_iterators/e_user_defined_iterators.py
926
4.65625
5
#!/usr/bin/python3 """ Purpose: Iterators - To get values from an iterator objects 1. Iterate over it - for loop - converting to other iterables - list(), tuple(), set(), dict() 2. To apply next() - will result in one element at a time """ a = ["foo", "bar", "baz"] itr = iter(a) for value in itr: print("value:", value) itr = iter(a) print("\n", itr) # <list_iterator object at 0x0000016CFEF10E20> print("\nitr.__next__()", itr.__next__()) print("next(itr) ", next(itr)) print("next(itr) ", next(itr)) try: print("next(itr) ", next(itr)) except StopIteration as ex: print(repr(ex)) print("\nReassigning") itr = iter(a) while True: try: print("next(itr) ", next(itr)) except StopIteration as ex: print(repr(ex)) break
true
37b606ca02ac4bfd4e53e038c0280ee660d3277c
udhayprakash/PythonMaterial
/python3/10_Modules/04a_os_module/display_tree_of_dirs.py
637
4.125
4
#!/usr/bin/python """ Purpose: To display the tree strcuture of directories only , till three levels test sub1 sub2 subsub1 """ import os import sys MAX_DEPTH = 3 # levels given_path = sys.exec_prefix # input('Enter the path:') print(given_path) def display_folders(_path, _depth): if _depth != MAX_DEPTH: _depth += 1 files_n_flders = os.listdir(_path) for each in files_n_flders: if os.path.isdir(os.path.join(_path, each)): print("+" + "--" * _depth, each) display_folders(os.path.join(_path, each), _depth) display_folders(given_path, 0)
true
f99296176c5701a5fe9cbc10d37767fa91ab06f4
udhayprakash/PythonMaterial
/python3/15_Regular_Expressions/d_re_search.py
965
4.59375
5
""" Purpose: Regular Expressions Using re.match - It helps to identify patterns at the starting of string Using re.search - It helps to identify patterns at the ANYWHERE of string """ import re target_string = "Python Programming is good for health" # search_string = "python" for search_string in ("python", "Python", "PYTHON", "PYThon"): reg_obj = re.compile(search_string, re.I) # re.IGNORECASE print(reg_obj, type(reg_obj)) # result = reg_obj.match(target_string) # .match can get only at the starting of string result = reg_obj.search(target_string) # .search - can get any where in the string, including starting print(f"{result =}") if result: print(f"result.group():{result.group()}") print(f"result.span() :{result.span()}") print(f"result.start():{result.start()}") print(f"result.end() :{result.end()}") else: print("NO match found") print()
true
5399535d50a3bc576a80fd1cd911b70a8891d6c6
udhayprakash/PythonMaterial
/python3/10_Modules/03_argparse/b_calculator.py
1,183
4.5
4
#!/usr/bin/python """ Purpose: command-line calculator """ import argparse def addition(n1, n2): return n1 + n2 def subtraction(s1, s2): return s1 - s2 def multiplication(m1, m2, m3): return m1 * m2 * m3 # Step 1: created parser object parser = argparse.ArgumentParser(description="Script to add two/three numbers") # Step 2: add arguments to parser object parser.add_argument("-num1", help="First value", type=int, default=0) parser.add_argument("-num2", help="Second Value", type=int, default=0) parser.add_argument("-num3", help="optonal value", type=float, default=0.0) # Step 3: Built parser objects and extract values args = parser.parse_args() num1 = args.num1 num2 = args.num2 print(f" {type(num1) =} {num1 = }") print(f" {type(num2) =} {num2 = }") print(f" {type(args.num3) =} {args.num3 = }") print() # Default Values are None for the args print(f"{addition(num1, num2) =}") print(f"{subtraction(num1, num2) =}") print(f"{multiplication(num1, num2,args.num3) =}") # python b_calculator.py # python b_calculator.py -num1 10 # python b_calculator.py -num1 10 -num2 20 # python b_calculator.py -num1 10 -num2 20 -num3 30
true
ef14eb6c7361331b6c3ba966a7a128a48d7b0b45
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b1a_class_based_solution.py
760
4.21875
4
""" Purpose: Class based implementation of synchronization using locks """ from threading import Lock, Thread from time import sleep class Counter: def __init__(self): self.value = 0 self.lock = Lock() def increase(self, by): self.lock.acquire() current_value = self.value current_value += by sleep(0.1) self.value = current_value print(f"counter={self.value}") self.lock.release() counter = Counter() # create threads t1 = Thread(target=counter.increase, args=(10,)) t2 = Thread(target=counter.increase, args=(20,)) # start the threads t1.start() t2.start() # wait for the threads to complete t1.join() t2.join() print(f"The final counter is {counter.value}")
true
3259d55b1aa7a9a2112a9eafe5ef2234966e0adc
udhayprakash/PythonMaterial
/python3/13_OOP/b_MRO_inheritance/01_single_inheritance.py
1,521
4.28125
4
""" Purpose: Single Inheritance Parent - child classes relation Super - sub classes relation NOTE: All child classes should make calls to the parent class constructors MRO - method resolution order """ class Account: """ Parent or super class """ def __init__(self): self.balance = 0 def deposit(self, amount): self.balance += amount return self.balance def withdraw(self, amount): self.balance -= amount return self.balance # a1 = Account() # print(vars(a1)) # print(dir(a1)) class MinimumBalanceAccount(Account): """ Child or sub class """ def __init__(self): # calling the constructor of the parent class Account.__init__(self) def withdraw(self, amount): if self.balance - amount < 100: print("Please maintain minimum balance. transaction failed!!!") else: Account.withdraw(self, amount) a2 = MinimumBalanceAccount() print(vars(a2)) # {'balance': 0} print(dir(a2)) # 'balance', 'deposit', 'withdraw' # MRO - Method Resolution Order print(Account.__mro__) # (<class '__main__.Account'>, <class 'object'>) print(MinimumBalanceAccount.__mro__) # (<class '__main__.MinimumBalanceAccount'>, <class '__main__.Account'>, <class 'object'>) print(f"Initial balance :{a2.balance}") print(dir(a2)) print() a2.deposit(1300) print(f"After deposit(1300) :{a2.balance}") a2.withdraw(900) print(f"After withdraw(900) :{a2.balance}") a2.withdraw(400)
true
b92994e333cf4ef258773b508a5107d81a1d321c
udhayprakash/PythonMaterial
/python3/13_OOP/a_OOP/11_static_n_class_methods.py
1,243
4.28125
4
#!/usr/bin/python """ Methods 1. Instance Methods 2. class Methods 3. static Methods Default Decorators: @staticmethod, @classmethod, @property """ class MyClass: my_var = "something" # class variable def display(self, x): print("executing instance method display(%s,%s)" % (self, x)) @classmethod def cmDisplay(cls, x): print("executing class method display(%s,%s)" % (cls, x)) @staticmethod def smDisplay(x): print("executing static method display(%s)" % x) # neither use instance methods, instance variable, class methods nor class variables if __name__ == "__main__": a = MyClass() a.display("Django") # accessing instance method MyClass.display(a, "Django") # accessing instance method a.cmDisplay("Django") # accessing class method MyClass.cmDisplay("Django") # accessing class method a.smDisplay("Django") # accessing static method MyClass.smDisplay("Django") # accessing static method class Myclass: val = 0 def __init__(self): self.val = 0 @staticmethod def incr(self): Myclass.val = Myclass.val + 1 I = Myclass() print(f"{I.val = }") I.incr() print(f"{I.val = }") Myclass.incr()
true
23978697bff6a4c96fa402731c3a700a5ab6a6ab
udhayprakash/PythonMaterial
/python3/06_Collections/02_Tuples/04_immutability.py
471
4.3125
4
#!/usr/bin/python3 """ Purpose: Tuples are immutable - They doesnt support in-object changes """ mytuple = (1, 2, 3) print("mytuple", mytuple, id(mytuple)) # Indexing print(f"{mytuple[2] =}") # updating an element in tuple try: mytuple[2] = "2.2222" except TypeError as ex: print(ex) print("tuple objects are not editable") # Overwriting print("\noverwriting (re-assigning)") mytuple = (1, "2.2222", 3) print("mytuple", mytuple, id(mytuple))
true
c81f107aece79ddbbddbe4b9185f3dd2ab40f8a7
udhayprakash/PythonMaterial
/python3/14_Code_Quality/00_static_code_analyses/e_ast_module.py
1,820
4.15625
4
#!/usr/bin/python """ Purpose: AST(Abstract Syntax Tree) Module Usage - Making IDEs intelligent and making a feature everyone knows as intellisense. - Tools like Pylint uses ASTs to perform static code analysis - Custom Python interpreters - Modes of Code Compilation - exec: We can execute normal Python code using this mode. - eval: To evaluate Python’s expressions, this mode will return the result fo the expression after evaluation. - single: This mode works just like Python shell which execute one statement at a time. """ import ast # Executing code code = ast.parse("print('Hello world!')") print(f"{code =}") print(f"{type(code) =}") exec(compile(code, filename="", mode="exec")) # To see AST created for above object print(f"{ast.dump(code) =}") print("\n\n") # Evaluating Python Expression expression = "6 + 8" code = ast.parse(expression, mode="eval") print(f"{code =}") print(f"{type(code) =}") print(eval(compile(code, "", mode="eval"))) # To see AST created for above object print(f"{ast.dump(code) =}") print("\n\n") # Constructing multi-line ASTs tree = ast.parse( """ fruits = ['grapes', 'mango'] name = 'peter' for fruit in fruits: print('{} likes {}'.format(name, fruit)) """ ) print(ast.dump(tree)) print("\n\n") class NodeTransformer(ast.NodeTransformer): def visit_Str(self, tree_node): return ast.Str("String: " + tree_node.s) class NodeVisitor(ast.NodeVisitor): def visit_Str(self, tree_node): print("{}".format(tree_node.s)) tree_node = ast.parse( """ fruits = ['grapes', 'mango'] name = 'peter' for fruit in fruits: print('{} likes {}'.format(name, fruit)) """ ) NodeTransformer().visit(tree_node) NodeVisitor().visit(tree_node)
true
52d5d2268407c434c4ca567c1cf52bc3d8c72783
udhayprakash/PythonMaterial
/python3/03_Language_Components/09_Loops/i_loops.py
916
4.28125
4
#!/usr/bin/python3 """ Purpose: Loops break - breaks the complete loop continue - skip the current loop pass - will do nothing. it is like a todo sys.exit - will exit the script execution """ import sys i = 0 while i <= 7: i += 1 print(i, end=" ") print("\n importance of break") i = 0 while i <= 7: i += 1 if i % 2 == 0: break print(i, end=" ") print("\n importance of continue") i = 0 while i <= 7: i += 1 if i % 2 == 0: continue print(i, end=" ") print("\n importance of pass") i = 0 while i <= 7: i += 1 if i % 2 == 0: pass # It acts as a placeholder print(i, end=" ") print("\nimportance of sys.exit") i = 0 while i < 7: i += 1 if i % 2 == 0: sys.exit(0) print(i, end=" ") # exit code 0 - successful/normal termination # exit code non-zero - abnormal termination print("next statement")
true
151a7dcf87ee5c6458eac386a5831f90dcc746a3
udhayprakash/PythonMaterial
/python3/15_Regular_Expressions/a_re_match.py
734
4.5
4
""" Purpose: Regular Expressions Using re.match - It helps to identify patterns at the starting of string - By default, it is case-sensitive """ import re # print(dir(re)) target_string = "Python Programming is good for health" search_string = "python" print(f"{target_string.find(search_string) =}") print(f"{search_string in target_string =}") print() reg_obj = re.compile(search_string) print(reg_obj, type(reg_obj)) result = reg_obj.match(target_string) print(f"{result =}") if result: print(f"result.group():{result.group()}") print(f"result.span() :{result.span()}") print(f"result.start():{result.start()}") print(f"result.end() :{result.end()}") else: print("NO match found")
true
696622f014f6ab152e691c301c2ae66a054aa1c9
udhayprakash/PythonMaterial
/python3/07_Functions/032_currying_functions.py
1,944
5.03125
5
#!/usr/bin/python3 """ Purpose: Currying Functions - Inner functions are functions defined inside another function that can be used for various purposes, while currying is a technique that transforms a function that takes multiple arguments into a sequence of functions that each take a single argument. - Inner functions can be used to create closures, encapsulate helper functions, or implement decorators, while currying is useful for creating more flexible and composable functions in functional programming. - While inner functions can be used to implement currying, they are not the same thing, and currying can also be implemented using other techniques such as lambda functions or partial function application. """ # Example of inner functions def outer(x): def inner(y): return x + y return inner add5 = outer(5) print(add5(3)) # Output: 8 # Example of currying using lambda functions def add(x): return lambda y: x + y add5 = add(5) print(add5(3)) # Output: 8 # ------------------------------------------------------------ # Example of inner functions def multiply_by(x): def inner(y): return x * y return inner double = multiply_by(2) print(double(5)) # Output: 10 # Example of currying using lambda functions def multiply(x): return lambda y: x * y triple = multiply(3) print(triple(5)) # Output: 15 # -------------------------------------------------------------- # Example of inner functions def compose(f, g): def inner(x): return f(g(x)) return inner def square(x): return x * x def add(x): return x + 1 square_and_add = compose(add, square) print(square_and_add(3)) # Output: 10 # Example of currying using partial function application from functools import partial def compose(f, g, x): return f(g(x)) square_and_add = partial(compose, add, square) print(square_and_add(3)) # Output: 10
true
713d449e4646683292f37d3e16792f2eaa58052d
udhayprakash/PythonMaterial
/python3/11_File_Operations/01_unstructured_file/i_reading_large_file.py
757
4.1875
4
#!/usr/bin/python3 """ Purpose: To read large file """ from functools import partial def read_from_file(file_name): """Method 1 - reading one line per iteration""" with open(file_name, "r") as fp: yield fp.readline() def read_from_file2(file_name, block_size=1024 * 8): """Method 2 - reading block size per iteration""" with open(file_name, "r") as fp: while True: chunk = fp.read(block_size) if not chunk: break yield chunk def read_from_file3(file_name, block_size=1024 * 8): """Method 3 - reading block size per iteration (clean code)""" with open(file_name, "r") as fp: for chunk in iter(partial(fp.read, block_size), ""): yield chunk
true
208da5282d2ac39f6a51343025bd78f422d2441b
alecbw/Learning-Projects
/Bank Account.py
1,147
4.34375
4
""" This code does the following things Top level: creates and manipulates a personal bank account * accepts deposits * allows withdrawals * displays the balance * displays the details of the account """ class BankAccount(object): balance = 0 def __init__(self, name): self.name = name def __repr__(self): return "This account belongs to %s and it has a balance of $%.2f" % (self.name, self.balance) def show_balance(self): print "The balance is $%.2f" % self.balance def deposit(self, amount): if amount <= 0: print "You can't deposit a negative amount" return else: print "So you're depositing $%.2f" % amount self.balance += amount self.show_balance() def withdraw(self, amount): if amount >= self.balance: print "You can't withdraw more than you have" return else: print "So you're withdrawing $%.2f" % amount self.balance -= amount self.show_balance() my_account = BankAccount("alec") my_account.__repr__() print my_account my_account.show_balance() my_account.deposit(2000) my_account.withdraw(1000) print my_account
true
13408db5de2e32cd359d691ac80ad724b2495253
TaiPham25/PhamPhuTai---Fundamentals---C4E16
/Session04/clera.py
742
4.15625
4
print ('Guess your number game') print ('Now think of a number from 0 to 100, then press " Enter"') input() print(""" All you have to do is to asnwer to my guess 'c' if my guess is 'C'orrect 'l' if my guess is 'L'arge than your number 's' if my guess is 'S'mall than your number """) #string formatting from random import randint # n = randint(0,100) high = 100 low = 0 while True: mid = (low + high) // 2 answer = input("Is {0} your number? ".format(mid)).lower() if answer == 'c': print("'C'orrect") break elif answer == 's': low = mid print("'S'maller than your number") elif answer == 'l': high = mid print("'L'arge than you number") else: print('zzzz')
true