├── .gitignore ├── abstraction ├── lesson.py ├── lesson2.py └── lesson3.py ├── arrays ├── arrays.py ├── reverse.py └── sort.py ├── basics ├── boolean.py ├── datatype.py ├── dictionary.py ├── exception.py ├── numbers.py ├── operators.py ├── others.py ├── sets.py ├── strings.py └── tuple.py ├── best_practices ├── main.py └── main_2.py ├── builtins ├── Readme.md ├── all.py ├── any.py ├── breakpoint.py ├── delattr.py ├── eval.py ├── exec.py ├── filter │ ├── filter.py │ ├── filter_function.py │ └── filter_none.py ├── getattr.py ├── hasattr.py ├── isinstance.py ├── issubclass.py ├── map.py ├── max_min.py ├── range.py ├── reduce │ ├── reduce.py │ ├── reduce_double_array.py │ └── reduce_min_max.py ├── setattr │ ├── setattr.py │ └── setattr_lesson2.py ├── size.py ├── sum.py ├── type.py └── vars.py ├── closure ├── lesson.py └── lesson2.py ├── collections └── counters.py ├── conditions ├── if_else.py ├── lesson.py ├── lesson2.py ├── lesson3.py ├── lesson4.py └── while_loops.py ├── datastructures ├── README.md └── sort │ ├── bubble_sort.py │ ├── insertion_sort.py │ ├── merge_sort.py │ ├── quick_sort.py │ └── selection_sort.py ├── decorators └── lesson.py ├── functions ├── functions.py ├── lesson.py ├── lesson3.py └── nested_functions.py ├── inheritance ├── lesson.py ├── lesson_2.py ├── lesson_3.py └── lesson_4.py ├── iterators ├── lesson.py ├── lesson2.py ├── lesson3.py ├── lesson4.py ├── lesson5.py ├── lesson6.py └── lesson7.py ├── lambda ├── lesson.py ├── lesson2.py └── lesson3.py ├── loop ├── break_continue.py ├── each_with_values.py ├── length.py ├── range.py ├── single_line.py └── while_infinite_loop.py ├── methods ├── methods.py ├── methods_2.py └── methods_3.py ├── projects ├── check_palindrome.py ├── duplicates │ ├── remove_duplicate_chars.py │ ├── remove_duplicate_chars_2.py │ ├── remove_duplicate_integer_in_array.py │ ├── remove_duplicate_strings_in_array.py │ ├── remove_duplicate_strings_in_array_2.py │ ├── remove_duplicate_strings_in_array_3.py │ ├── remove_duplicates_from_list.py │ └── remove_objects_with_duplicate_values.py ├── factorial.py ├── fibonacci_series.py ├── find_3_consecutive_strings.py ├── length │ ├── find_string_length.py │ └── find_string_length_2.py ├── list_to_string.py ├── match │ └── remove_matching_strings.py ├── maxmin │ ├── max_char_string_in_an_array.py │ ├── max_number_in_an_array.py │ ├── min_char_string_in_an_array.py │ └── min_number_in_an_array.py ├── online test │ ├── codingbat │ │ ├── diff21.py │ │ ├── frontback.py │ │ ├── notstring.py │ │ └── vacation.py │ └── hackerrank │ │ ├── fizzbuzz.py │ │ └── test.py ├── prime_number.py ├── print_all_prime_numbers.py ├── print_strings_in_even_position.py ├── random │ ├── generate_list_with_random_values_and_fixed_length.py │ └── generate_random_int_within_range.py ├── remove_empty_arrays_in_list.py ├── remove_objects_with_none.py ├── remove_vowels.py ├── reverse │ ├── reverse_string_recursion.py │ ├── reverse_text.py │ ├── reverse_text_alternate_caps.py │ └── reverse_text_alternate_remove.py ├── singleton.py ├── sort │ └── sort_object_list_in_an_array.py └── tax │ ├── income_tax.py │ ├── income_tax_direct.py │ └── income_tax_dynamic.py ├── pytest ├── Readme.md ├── pytest.ini ├── test_fixture.py ├── test_mark.py ├── test_parameter.py ├── test_simple.py ├── test_skip_xfail.py └── test_yield_fixture.py ├── readme.md ├── variables ├── lesson.py ├── lesson2.py ├── lesson3.py └── lesson4.py └── yield generator ├── lesson.py └── lesson2.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .DS_Store 3 | */**/.DS_Store 4 | */.DS_Store 5 | venv/ 6 | .pytest_cache/ 7 | pytest/.pytest_cache/ 8 | pytest/__pycache__/ 9 | builtins/getitem.py -------------------------------------------------------------------------------- /abstraction/lesson.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class Food(ABC): 5 | 6 | @abstractmethod 7 | def snacks(self): 8 | pass 9 | 10 | @abstractmethod 11 | def noodles(self): 12 | pass 13 | 14 | 15 | class Shops(Food): 16 | 17 | def snacks(self): 18 | print('snacks') 19 | 20 | def noodles(self): 21 | print('noodles') 22 | 23 | 24 | obj = Shops() 25 | obj.snacks() 26 | obj.noodles() 27 | -------------------------------------------------------------------------------- /abstraction/lesson2.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class Food(ABC): 5 | 6 | @abstractmethod 7 | def snacks(self): 8 | pass 9 | 10 | @abstractmethod 11 | def zomato(self): 12 | pass 13 | 14 | 15 | class Shops(Food): 16 | 17 | def snacks(self): 18 | print('snacks') 19 | 20 | 21 | class Delivery(Shops): 22 | 23 | def zomato(self): 24 | print('zomato') 25 | 26 | 27 | obj = Delivery() 28 | obj.snacks() 29 | obj.zomato() 30 | -------------------------------------------------------------------------------- /abstraction/lesson3.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class Food(ABC): 5 | 6 | def __init__(self, order): 7 | self.order = order 8 | 9 | @abstractmethod 10 | def snacks(self): 11 | pass 12 | 13 | @abstractmethod 14 | def zomato(self): 15 | pass 16 | 17 | 18 | class Shops(Food): 19 | 20 | def snacks(self): 21 | print('snacks: {}'.format(self.order)) 22 | 23 | 24 | class Delivery(Shops): 25 | 26 | def zomato(self): 27 | print('zomato: {}'.format(self.order)) 28 | 29 | 30 | obj = Delivery(5) 31 | obj.snacks() 32 | obj.zomato() 33 | -------------------------------------------------------------------------------- /arrays/arrays.py: -------------------------------------------------------------------------------- 1 | # define, overriding, adding, reverse array, count of value in array, 2 | # insert value in an array, copy array, index of array, clear array, extend another array's value 3 | y = ['sdf', 'asdf'] 4 | y[0] = 'cars' 5 | y[1] = 'bikes' 6 | y.append('motor') 7 | y.append('cycle') 8 | y.append('travel') 9 | y.pop(2) 10 | y.remove('cars') 11 | y.reverse() 12 | y.insert(0, 'sams') 13 | print(y) 14 | print(y.index('sams')) 15 | print(y.count('cycle')) 16 | k = y.copy() 17 | print(y.clear()) 18 | y.append('new') 19 | print(k) 20 | y.extend(k) 21 | print(y) 22 | 23 | # init 5 index with same value 24 | k = ["last"] * 5 25 | k[0] = "one" 26 | k[1] = "two" 27 | k[2] = "three" 28 | print(k) 29 | 30 | # declare and insert values in an array 31 | a = [] 32 | a.append('first item') 33 | a.append('second item') 34 | print(a) 35 | 36 | # replace an existing array index value 37 | a = [] 38 | a.append('first item') 39 | a.append('second item') 40 | a[1] = 'replaced' 41 | print(a) -------------------------------------------------------------------------------- /arrays/reverse.py: -------------------------------------------------------------------------------- 1 | # reverse integer list 2 | k = [1, 2, 3, 4, 5, 6] 3 | k.reverse() 4 | print(k) 5 | 6 | # reverse string list 7 | k = ['a', 'b', 'c', 'd', 'e', 'f'] 8 | k.reverse() 9 | print(k) 10 | 11 | # reverse string list 12 | k = ['a', 'b', 'c', 'd', 'e', 'f'] 13 | k.sort(reverse=True) 14 | print(k) -------------------------------------------------------------------------------- /arrays/sort.py: -------------------------------------------------------------------------------- 1 | # sort integer list 2 | k = [4, 5, 2, 1, 1, 9] 3 | k.sort() 4 | print(k) 5 | 6 | # sort string list 7 | k = ['d', 'e', 'f', 'a', 'g', 'c'] 8 | k.sort() 9 | print(k) -------------------------------------------------------------------------------- /basics/boolean.py: -------------------------------------------------------------------------------- 1 | # returns true 2 | print(bool('Prashanth')) 3 | print(bool(38)) 4 | 5 | # returns false 6 | print(bool(False)) 7 | print(bool(0)) 8 | print(bool(None)) 9 | print(bool('')) 10 | print(bool()) 11 | print(bool(())) 12 | print(bool({})) 13 | print(bool([])) 14 | 15 | # return length as boolean - True 16 | class TrueClass: 17 | def __len__(self): 18 | return 10 19 | 20 | print(len(TrueClass())) 21 | print(bool(TrueClass())) 22 | print(bool(len(TrueClass()))) 23 | 24 | # return length as boolean - False 25 | class FalseClass: 26 | def __len__(self): 27 | return 0 28 | 29 | print(len(FalseClass())) 30 | print(bool(FalseClass())) 31 | print(bool(len(FalseClass()))) 32 | 33 | # return with boolean case 34 | def value(): 35 | return True 36 | 37 | if value(): 38 | print('YES') 39 | else: 40 | print('NO') 41 | 42 | # return boolean on datatype validation 43 | print(isinstance(20, int)) 44 | print(isinstance('sams', str)) -------------------------------------------------------------------------------- /basics/datatype.py: -------------------------------------------------------------------------------- 1 | if type("bus") is str: print(True) 2 | if type(10) is int: print(True) 3 | if type(10.5) is float: print(True) 4 | if type(True) is bool: print(True) 5 | if type(["bus", "car"]) is list: print(True) 6 | if type({"a":"cars", "b":"bike"}) is dict: print(True) 7 | if type(("car", "bike")) is tuple: print(True) 8 | 9 | if isinstance("bus", str): print(True) 10 | if isinstance(10, int): print(True) 11 | if isinstance(10.5, float): print(True) 12 | if isinstance(True, bool): print(True) 13 | if isinstance(["bus", "car"], list): print(True) 14 | if isinstance({"a":"cars", "b":"bike"}, dict): print(True) 15 | if isinstance(("car", "bike"), tuple): print(True) 16 | -------------------------------------------------------------------------------- /basics/dictionary.py: -------------------------------------------------------------------------------- 1 | k = {"a": "cars", "b": "bikes", "c": "cycle"} 2 | print(k) 3 | 4 | # dict keys, values, and items 5 | print(k.keys()) 6 | print(k.values()) 7 | print(k.items()) 8 | 9 | # dict keys and values as list 10 | print(list(k.keys())) 11 | print(list(k.values())) 12 | 13 | # pick value with key name 14 | print(k['b']) 15 | print(k.get('b')) 16 | 17 | # update value of a key 18 | k['b'] = 'tractor' 19 | print(k) 20 | 21 | # iterate through dictionary keys 22 | for i in k: 23 | print(i) 24 | 25 | # iterate through dictionary values 26 | for i in k: 27 | print(k[i]) 28 | for i in k.values(): 29 | print(i) 30 | 31 | for a, b in k.items(): 32 | print(a, b) 33 | 34 | if "cycle" in k.values(): 35 | print(True) 36 | 37 | print((len(k))) 38 | 39 | # append values in existing dict 40 | k['d'] = 'motor' 41 | print(k) 42 | 43 | # remove key-pair from the dict 44 | # del k['d'] 45 | k.pop('d') 46 | print(k) 47 | 48 | # remove the last key-pair from dict 49 | k.popitem() 50 | print(k) 51 | 52 | # take copy of the existing dict 53 | m = k.copy() 54 | n = dict(k) 55 | print(m) 56 | print(n) 57 | 58 | # removes all the key-pair from the dict 59 | k.clear() 60 | print(k) 61 | 62 | # nested dictionaries 63 | x = {0: {'a': 'love', 'b': 'peace'}, 1: {'c': 'pasta', 'd': 'noodles'}, 2: {'e': 'tea'}} 64 | print(x) 65 | 66 | # call from outside 67 | d1 = {'a': 'love', 'b': 'peace'} 68 | d2 = {'c': 'pasta', 'd': 'noodles'} 69 | d3 = {'e': 'tea'} 70 | d = { 71 | 0: d1, 72 | 1: d2, 73 | 2: d3 74 | } 75 | print(d) 76 | 77 | # dict constructor to make a new dictionary 78 | test = dict(a='bible', b='prayer', c='worship') 79 | print(test) -------------------------------------------------------------------------------- /basics/exception.py: -------------------------------------------------------------------------------- 1 | # number #1 2 | try: 3 | print(x) 4 | except Exception as e: 5 | print(f'throw error {e}') 6 | 7 | # number #2 8 | try: 9 | raise 'asd' 10 | except NameError as e: 11 | print(f'Name error {e}') 12 | except Exception as e: 13 | print(f'other error {e}') 14 | 15 | # number #3 16 | try: 17 | raise 'asd' 18 | except NameError as e: 19 | print(f'Name error {e}') 20 | except Exception as e: 21 | print(f'other error {e}') 22 | finally: 23 | print(f'finally') 24 | 25 | # raise an exception 26 | try: 27 | raise Exception('raising an exception') 28 | except Exception as e: 29 | print(f'manual exception {e}') 30 | 31 | # raise an exception 32 | if not False: raise Exception('raising an exception') 33 | if not False: raise TypeError("Only integers are allowed") 34 | -------------------------------------------------------------------------------- /basics/numbers.py: -------------------------------------------------------------------------------- 1 | # print calc results in runtime 2 | print(90 + 10) 3 | 4 | # print with float value 5 | print(30 / 2) 6 | 7 | # print without float value 8 | print(30 // 2) 9 | -------------------------------------------------------------------------------- /basics/operators.py: -------------------------------------------------------------------------------- 1 | 2 | a = b = "bike" 3 | c = d = "cars" 4 | 5 | if a is "bike" and b is "bike": 6 | print(True) 7 | 8 | if a == "bike" and c != "bike": 9 | print(True) 10 | 11 | if a == "bike" or c == "bike": 12 | print(True) 13 | 14 | print(True) if a is not "cars" else print(False) 15 | 16 | k = ['bike', 'cars', 'cycle', 'motor'] 17 | 18 | if 'cards' not in k: 19 | print(True) -------------------------------------------------------------------------------- /basics/others.py: -------------------------------------------------------------------------------- 1 | # random value 2 | import random 3 | print(random.randrange(1,10)) -------------------------------------------------------------------------------- /basics/sets.py: -------------------------------------------------------------------------------- 1 | # add, remove, check if available, update, length, discard, pop, union set, delete set, clean set 2 | x = {"cars", "bikes", "cycle"} 3 | x.add("travel") 4 | x.remove("travel") 5 | print(x) 6 | print('cars' in x) 7 | x.update(["sams", "david", "cycle"]) 8 | print(len(x)) 9 | x.discard('cycle') 10 | x.pop() 11 | x.clear() 12 | # del x 13 | print(x) 14 | a = {1, 2, 3} 15 | b = {4, 5, 6} 16 | c = a.union(b) 17 | a.update(b) 18 | print(c) 19 | print(a) -------------------------------------------------------------------------------- /basics/strings.py: -------------------------------------------------------------------------------- 1 | # print a string 2 | print('Jesus is coming!') 3 | 4 | # print a string in new line 5 | print('Jesus is coming!\nAre you ready?') 6 | 7 | # print a string in new line x2 8 | print(""" 9 | Jesus is coming! 10 | Are you ready? 11 | Yes 12 | """) 13 | 14 | # concatenate two strings 15 | print('Jesus is coming!' + ' Are you ready?') 16 | 17 | # concatenate two strings as a parameter 18 | str1 = 'Jesus is coming!' 19 | str2 = 'Are you ready?' 20 | print(str1 + " " + str2) 21 | 22 | # enter input in console 23 | name = input() 24 | print(str1 + "\n" + name + ", " + str2) 25 | 26 | # fetch string value through indices 27 | print(name[0]) 28 | 29 | # get char length 30 | print(len('am here')) 31 | print('am here'.__len__()) 32 | 33 | k = " Jesus is coming soon" 34 | print('coming' in k) 35 | print('coming' not in k) 36 | print(k[1]) 37 | print(k[2:5]) 38 | print(k[-5:-1]) 39 | print(k.strip()) 40 | print(k.lower()) 41 | print(k.upper()) 42 | l = k.upper() 43 | print(l.isupper()) 44 | m = k.lower() 45 | print(m.islower()) 46 | m = k.replace('soon', 'soon.') 47 | print(m) 48 | print(m.split(' ')) 49 | for i in k: 50 | print(i) 51 | 52 | k = 'Hey! my name is {}' 53 | age = 30 54 | print(k.format(age)) 55 | 56 | k = '{} is my name. I am {}' 57 | name = 'Prashanth' 58 | age = 30 59 | print(k.format(name, age)) 60 | 61 | k = '{1} is my name. I am {0}' 62 | name = 'Prashanth' 63 | age = 30 64 | print(k.format(age, name)) 65 | 66 | k = "Jesus is coming soon \\ \t \110\145\154\154\157 \x48\x65\x6c\x6c\x6f are you ready?\b?" 67 | print(k) 68 | 69 | k = 'jesus is coming soon' 70 | print(k.capitalize()) -------------------------------------------------------------------------------- /basics/tuple.py: -------------------------------------------------------------------------------- 1 | k = ("a", "b", "c", "d", "e") 2 | print(k[2]) 3 | 4 | k = ("a", "b", "c", "d", "e") 5 | print(k[2:4]) 6 | 7 | # Negative indexing means starting from the end of the tuple. 8 | k = ("a", "b", "c", "d", "e") 9 | print(k[-4:-1]) 10 | 11 | # convert tuple to list 12 | k = ("a", "b", "c", "d", "e") 13 | m = list(k) 14 | m[1] = 'p' 15 | k = tuple(m) 16 | print(k) 17 | 18 | # merge two tuples 19 | k = ("a", "b", "c", "d", "e") 20 | l = (1, 2, 3, 4, 5, 6) 21 | print(k + l) 22 | 23 | -------------------------------------------------------------------------------- /best_practices/main.py: -------------------------------------------------------------------------------- 1 | print("am in main function") 2 | 3 | 4 | def football(): 5 | print("You're watching football") 6 | 7 | 8 | if __name__ == "__main__": 9 | print("You're in main function") 10 | -------------------------------------------------------------------------------- /best_practices/main_2.py: -------------------------------------------------------------------------------- 1 | print("am in main function") 2 | 3 | 4 | def game(data): 5 | print(f"You're watching {data}") 6 | return data 7 | 8 | 9 | def main(): 10 | print("You're in game mode...") 11 | 12 | 13 | if __name__ == '__main__': 14 | main() 15 | game('football') 16 | -------------------------------------------------------------------------------- /builtins/Readme.md: -------------------------------------------------------------------------------- 1 | # built-in functions 2 | > exercise python based built-in methods 3 | 4 | | | | | | 5 | | -------- | --------- | --------- | --------- | 6 | | eval() | hasattr() | isinstance() | reduce() | 7 | | exec() | getattr() | issubclass() | sum() | 8 | | min() | setattr() | map() | breakpoint() | 9 | | max() | delattr() | filter() | vars() | 10 | | type() | range() | any() | all() | -------------------------------------------------------------------------------- /builtins/all.py: -------------------------------------------------------------------------------- 1 | print(all("")) 2 | print(all({})) 3 | print(all([])) 4 | print(all(())) 5 | 6 | print(all([True, False])) 7 | print(all([True, True])) 8 | print(all([True, 0])) 9 | print(all([True, 1])) 10 | 11 | print(all([10, 1])) 12 | 13 | names = ["Prashanth", "Sams", "Christal"] 14 | print(all([i == 'Sams' for i in names])) 15 | -------------------------------------------------------------------------------- /builtins/any.py: -------------------------------------------------------------------------------- 1 | print(any([""])) 2 | print(any(["", False, 0])) 3 | print(any(["", False, 0, 1])) 4 | print(any(("", False, 0, 1))) 5 | 6 | print(any(["", False, 0, "Hey"])) 7 | 8 | names = ["Prashanth", "Sams", "Christal"] 9 | print(any([i == "Sams" for i in names])) 10 | 11 | print(any("")) 12 | print(any({})) 13 | print(any([])) 14 | print(any(())) -------------------------------------------------------------------------------- /builtins/breakpoint.py: -------------------------------------------------------------------------------- 1 | """ 2 | q - quit 3 | c - continue 4 | s - step by step execution 5 | PYTHONBREAKPOINT=0 python3 builtins/breakpoint.py - skip breakpoint 6 | PYTHONBREAKPOINT=1 python3 builtins/breakpoint.py - ignore breakpoint 7 | """ 8 | 9 | for i in range(10): 10 | print(i) 11 | 12 | if i == 5: 13 | breakpoint() 14 | -------------------------------------------------------------------------------- /builtins/delattr.py: -------------------------------------------------------------------------------- 1 | class X: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def sum(self): 7 | return int(self.a) + int(self.b) 8 | 9 | 10 | k = X('5', '10') 11 | 12 | delattr(k, 'b') 13 | print(hasattr(k, 'b')) 14 | -------------------------------------------------------------------------------- /builtins/eval.py: -------------------------------------------------------------------------------- 1 | print(eval("3 + 2")) 2 | print(eval("3 - 2")) 3 | print(eval("3 * 2")) 4 | print(eval("3 ** 2")) 5 | print(eval("3 % 2")) 6 | print(eval("3 == 2")) 7 | 8 | eval('print("hello world")') -------------------------------------------------------------------------------- /builtins/exec.py: -------------------------------------------------------------------------------- 1 | print(dir()) 2 | exec("def x(): print('am here')", {"x": None}) 3 | print(dir()) 4 | exec("def x(): print('am here')") 5 | print(dir()) 6 | x() 7 | -------------------------------------------------------------------------------- /builtins/filter/filter.py: -------------------------------------------------------------------------------- 1 | # Example 2 | k = [1, 2, 3, 4, 5, 6] 3 | print([i for i in k if i >= 4]) 4 | 5 | # same in filter 6 | print(list(filter(lambda i: i >= 4, k))) 7 | -------------------------------------------------------------------------------- /builtins/filter/filter_function.py: -------------------------------------------------------------------------------- 1 | # Example 2 | def greater_than_4(i): 3 | return i > 4 4 | 5 | 6 | # generic way 7 | k = [1, 2, 3, 4, 5, 6] 8 | print([i for i in k if greater_than_4(i)]) 9 | 10 | 11 | # using filter 12 | print(list(filter(greater_than_4, k))) 13 | -------------------------------------------------------------------------------- /builtins/filter/filter_none.py: -------------------------------------------------------------------------------- 1 | # generic 2 | print([i for i in [0,1,2,True,False] if bool(None) != bool(i)]) 3 | 4 | # filter 5 | print(list(filter(None, [0, 1, 2, 3]))) 6 | print(list(filter(None, [0, 0, 1, 2, 3]))) 7 | print(list(filter(None, [0, 1, 2, 3, True, False]))) 8 | print(list(filter(None, [0, 1, 2, 3, True, False, "", "sams"]))) -------------------------------------------------------------------------------- /builtins/getattr.py: -------------------------------------------------------------------------------- 1 | class X: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def sum(self): 7 | return self.a + self.b 8 | 9 | 10 | k = X('5', '10') 11 | 12 | print(getattr(k, 'b')) 13 | print(getattr(k, 'sum')) 14 | -------------------------------------------------------------------------------- /builtins/hasattr.py: -------------------------------------------------------------------------------- 1 | # checks if the array object has append attribute 2 | k = [1, 2, 3, 4] 3 | 4 | print(hasattr(k, 'append')) 5 | 6 | # checks if the tuple object has append attribute 7 | k = (1, 2, 3, 4) 8 | 9 | print(hasattr(k, 'append')) 10 | 11 | 12 | # approach 3 13 | class X: 14 | def __init__(self, a, b): 15 | self.a = a 16 | self.b = b 17 | 18 | def sum(self): 19 | return self.a + self.b 20 | 21 | 22 | k = X('5', '10') 23 | 24 | print(hasattr(k, 'b')) 25 | print(hasattr(k, 'sum')) 26 | -------------------------------------------------------------------------------- /builtins/isinstance.py: -------------------------------------------------------------------------------- 1 | class X: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def sum(self): 7 | return int(self.a) + int(self.b) 8 | 9 | 10 | class Y(X): 11 | 12 | def sum(self): 13 | return int(self.a) - int(self.b) 14 | 15 | 16 | k = Y(5, 6) 17 | print(isinstance(k, Y)) 18 | -------------------------------------------------------------------------------- /builtins/issubclass.py: -------------------------------------------------------------------------------- 1 | class X: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def sum(self): 7 | return int(self.a) + int(self.b) 8 | 9 | 10 | class Y(X): 11 | 12 | def sum(self): 13 | return int(self.a) - int(self.b) 14 | 15 | 16 | print(issubclass(Y, X)) 17 | print(issubclass(X, Y)) 18 | -------------------------------------------------------------------------------- /builtins/map.py: -------------------------------------------------------------------------------- 1 | print([*map(chr, [66, 53, 0, 94])]) 2 | print(map(str, [66, 53, 0, 94])) 3 | [print(i) for i in map(chr, [66, 53, 0, 94])] 4 | 5 | 6 | # convert to upper case 7 | def value(k): 8 | return k.upper() 9 | 10 | 11 | print([*map(value, ['mango', 'jack fruit', 'pine apple', 'grapes'])]) 12 | 13 | 14 | # income tax calculator 15 | def income_tax(sum, percent): 16 | return round(sum - (sum * percent / 100)) 17 | 18 | 19 | print([*map(income_tax, [20000, 30000, 40000, 50000], [20, 30, 40, 50])]) 20 | -------------------------------------------------------------------------------- /builtins/max_min.py: -------------------------------------------------------------------------------- 1 | print(min(23, 4, 22)) 2 | 3 | print(max(23, 4, 22)) 4 | print(max([23, 4, 22])) 5 | print(max([23, 4, 22], [21, 4, 222])) 6 | -------------------------------------------------------------------------------- /builtins/range.py: -------------------------------------------------------------------------------- 1 | print(range(5)) 2 | print(type(range(5)) == range) 3 | 4 | import sys 5 | 6 | a = (0, 1, 2, 3, 4, 5) 7 | # size of 'a' in memory 8 | print(sys.getsizeof(a)) 9 | 10 | b = [0, 1, 2, 3, 4, 5] 11 | # size of 'b' in memory 12 | print(sys.getsizeof(b)) 13 | 14 | print(sys.getsizeof(range(5))) 15 | -------------------------------------------------------------------------------- /builtins/reduce/reduce.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | print(reduce(lambda x, y: x + y, [1, 2, 3, 4])) 4 | print(reduce(lambda x, y: x * y, [1, 2, 3, 4])) -------------------------------------------------------------------------------- /builtins/reduce/reduce_double_array.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | # generic method #1 4 | print([1, 2] + [3, 4] + [5, 6]) 5 | 6 | # generic method #2 7 | a = [[1, 2], [3, 4], [5, 6]] 8 | print([k for i in a for k in i]) 9 | 10 | """ 11 | reduce - method #1 12 | """ 13 | print(reduce(lambda x, y: x + y, a)) 14 | 15 | """ 16 | reduce - method #2 17 | """ 18 | def addition(x, y): 19 | return x + y 20 | 21 | 22 | print(reduce(addition, a)) 23 | -------------------------------------------------------------------------------- /builtins/reduce/reduce_min_max.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | print(reduce(lambda x, y: x if x > y else y, [1, 5, 3, 4])) 4 | print(reduce(lambda x, y: x if x < y else y, [3, 5, 1, 4])) 5 | -------------------------------------------------------------------------------- /builtins/setattr/setattr.py: -------------------------------------------------------------------------------- 1 | class X: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def sum(self): 7 | return int(self.a) + int(self.b) 8 | 9 | 10 | k = X('5', '10') 11 | 12 | setattr(k, 'b', '20') 13 | print(getattr(k, 'b')) 14 | print(k.sum()) 15 | -------------------------------------------------------------------------------- /builtins/setattr/setattr_lesson2.py: -------------------------------------------------------------------------------- 1 | class X: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def sum(self): 7 | return int(self.a) + int(self.b) 8 | 9 | 10 | k = X('5', '10') 11 | 12 | setattr(k, 'c', '20') 13 | print(hasattr(k, 'c')) 14 | print(getattr(k, 'c')) -------------------------------------------------------------------------------- /builtins/size.py: -------------------------------------------------------------------------------- 1 | k = [2, 3, 1, 5, 6] 2 | 3 | print(len(k)) 4 | print(k.__len__()) -------------------------------------------------------------------------------- /builtins/sum.py: -------------------------------------------------------------------------------- 1 | print(sum([1, 2, 3, 4])) 2 | print(sum([i for i in [1, 2, 3]])) -------------------------------------------------------------------------------- /builtins/type.py: -------------------------------------------------------------------------------- 1 | print(type(0)) 2 | print(type("")) 3 | print(type([])) 4 | print(type(())) 5 | print(type({})) 6 | print(type({1, 2, 3})) 7 | print(type(type(''))) 8 | 9 | print(type({1, 2, 3}) == set) 10 | 11 | a = 0 12 | print(a.__class__) 13 | 14 | 15 | class Fruit: 16 | """ 17 | fruits count 18 | """ 19 | apple = 100 20 | 21 | 22 | print(Fruit.__class__) 23 | print(Fruit.__bases__) 24 | print(Fruit.__dict__) 25 | print(Fruit.__doc__) -------------------------------------------------------------------------------- /builtins/vars.py: -------------------------------------------------------------------------------- 1 | """ 2 | vars() 3 | vars(str) 4 | vars(int) 5 | vars(dict) 6 | locals() 7 | dir(Fruit()) 8 | 9 | ------same----- 10 | vars(Fruit()) 11 | Fruit.__dict__ 12 | """ 13 | 14 | global k 15 | 16 | 17 | class Fruit: 18 | 19 | def __init__(self, k=[]): 20 | self.k = k 21 | 22 | for i in range(10): 23 | print(i) 24 | self.k.append(i) 25 | 26 | 27 | obj = Fruit() 28 | print(vars(obj)) -------------------------------------------------------------------------------- /closure/lesson.py: -------------------------------------------------------------------------------- 1 | 2 | def calculation(): 3 | x = 10 4 | 5 | def add(): 6 | print(x) 7 | add() 8 | 9 | 10 | calculation() -------------------------------------------------------------------------------- /closure/lesson2.py: -------------------------------------------------------------------------------- 1 | 2 | def calculation(x): 3 | 4 | def add(y): 5 | print(x+y) 6 | return add 7 | 8 | 9 | result = calculation(100) 10 | result(50) 11 | result(150) 12 | result(200) 13 | 14 | calculation(100)(500) -------------------------------------------------------------------------------- /collections/counters.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | k = ['A', 'A', 'C', 'B', 'C', 'A', 'B', 'A', 'C', 'B'] 4 | 5 | print(Counter(k)) 6 | # Counter({'A': 4, 'C': 3, 'B': 3}) 7 | 8 | print(dict(Counter(k))) 9 | # {'A': 4, 'C': 3, 'B': 3} 10 | 11 | print(Counter(A=3, B=2, C=1)) 12 | # Counter({'A': 4, 'C': 3, 'B': 3}) -------------------------------------------------------------------------------- /conditions/if_else.py: -------------------------------------------------------------------------------- 1 | # one line if else statement 2 | print("true") if 1 == 1 else print('false') 3 | 4 | # one line for 3 conditions 5 | print("A") if 2 > 2 else print("=") if 2 == 2 else print("B") 6 | 7 | if 2 > 1 and 1 > 0: 8 | pass 9 | 10 | if 2 > 1 or 1 < 0: 11 | print('0 is smaller') 12 | 13 | if 2 > 1 > 0: 14 | print('0 is smaller') 15 | 16 | if not 0 > 1 <= 2: 17 | pass -------------------------------------------------------------------------------- /conditions/lesson.py: -------------------------------------------------------------------------------- 1 | def switch(option): 2 | return { 3 | 'a': 'cars', 4 | 'b': 'bikes', 5 | 'c': 'motor' 6 | }.get(option, 'Not found') 7 | 8 | 9 | print(switch('b')) 10 | -------------------------------------------------------------------------------- /conditions/lesson2.py: -------------------------------------------------------------------------------- 1 | def switch(option): 2 | return { 3 | 'a': 'cars', 4 | 'b': 'bikes', 5 | 'c': 'motor' 6 | }[option] 7 | 8 | 9 | print(switch('c')) 10 | -------------------------------------------------------------------------------- /conditions/lesson3.py: -------------------------------------------------------------------------------- 1 | 2 | for i in range(10): 3 | if i in (0,1): print('phase 1') 4 | if i in (2,3): print('phase 2') 5 | if i in (4,5): print('phase 3') 6 | if i in (6,7): print('phase 4') 7 | if i in (8,9): print('phase 5') -------------------------------------------------------------------------------- /conditions/lesson4.py: -------------------------------------------------------------------------------- 1 | def myfunc(name, age): 2 | return { 3 | 'Prashanth': 4 | { 5 | 30: 'Prashanth', 6 | 31: 'Not Prashanth' 7 | }.get(age, 'second skip'), 8 | 9 | 'Sunil': 10 | { 11 | 32: 'Sunil', 12 | 31: 'Not Sunil' 13 | }.get(age, '') 14 | }.get(name, 'first skip') 15 | 16 | 17 | print(myfunc('Sunil', 32)) 18 | -------------------------------------------------------------------------------- /conditions/while_loops.py: -------------------------------------------------------------------------------- 1 | # generic 2 | i = 0 3 | while i < 10: 4 | print(i) 5 | i += 1 6 | 7 | # break from 5 in 1 to 10 series 8 | while i < 10: 9 | print(i) 10 | if i == 5: break 11 | i += 1 12 | 13 | # missing 5 from 1 to 10 series 14 | while i < 10: 15 | i += 1 16 | if i == 5: continue 17 | print(i) 18 | 19 | # false condition 20 | while i < 0: 21 | print(i) 22 | else: 23 | print("no execution") -------------------------------------------------------------------------------- /datastructures/README.md: -------------------------------------------------------------------------------- 1 | # data structures 2 | > exercise python based data structures 3 | 4 | ### sorting 5 | - Selection Sort 6 | - Merge Sort 7 | - Bubble Sort 8 | - Insertion Sort 9 | -------------------------------------------------------------------------------- /datastructures/sort/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def sort(k): 2 | for i in range(len(k)): 3 | for j in range(i, len(k)-1): 4 | if k[i] > k[j+1]: 5 | temp = k[i] 6 | k[i] = k[j+1] 7 | k[j+1] = temp 8 | return k 9 | 10 | 11 | k = [1, 5, 3, 7, 2, 4] 12 | sort(k) 13 | print(k) -------------------------------------------------------------------------------- /datastructures/sort/insertion_sort.py: -------------------------------------------------------------------------------- 1 | def sort(k): 2 | for i in range(1, len(k)): 3 | while k[i-1] > k[i] and i > 0: 4 | temp = k[i-1] 5 | k[i-1] = k[i] 6 | k[i] = temp 7 | i -= 1 8 | return k 9 | 10 | 11 | k = [5, 1, 5, 3, 44, 4, 7, 2, 4, 234] 12 | sort(k) 13 | print(k) -------------------------------------------------------------------------------- /datastructures/sort/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | split and combine 3 | """ 4 | 5 | 6 | def sort(k): 7 | if len(k) > 1: 8 | mid = len(k) // 2 9 | left = k[:mid] 10 | right = k[mid:] 11 | 12 | sort(left) 13 | sort(right) 14 | 15 | i, j, p = 0, 0, 0 16 | 17 | while i < len(left) and j < len(right): 18 | if left[i] < right[j]: 19 | k[p] = left[i] 20 | i = i + 1 21 | else: 22 | k[p] = right[j] 23 | j = j + 1 24 | p = p + 1 25 | 26 | while i < len(left): 27 | k[p] = left[i] 28 | i = i + 1 29 | p = p + 1 30 | 31 | while j < len(right): 32 | k[p] = right[j] 33 | j = j + 1 34 | p = p + 1 35 | 36 | 37 | k = [5, 2, 6, 4, 1, 3] 38 | sort(k) 39 | print(k) 40 | -------------------------------------------------------------------------------- /datastructures/sort/quick_sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(k): 2 | if len(k) <= 1: 3 | return k 4 | else: 5 | pivot = k.pop() 6 | 7 | l = [] 8 | m = [] 9 | 10 | for item in k: 11 | if item > pivot: 12 | l.append(item) 13 | else: 14 | m.append(item) 15 | 16 | return quick_sort(m) + [pivot] + quick_sort(l) 17 | 18 | 19 | print(quick_sort([5, 1, 4, 3, 7, 4, 2])) 20 | -------------------------------------------------------------------------------- /datastructures/sort/selection_sort.py: -------------------------------------------------------------------------------- 1 | k = [5, 3, 1, 8, 2] 2 | 3 | 4 | def sort(k): 5 | for i in range(4): 6 | min_pos = i 7 | for j in range(i, 5): 8 | if k[j] < k[min_pos]: 9 | min_pos = j 10 | 11 | temp = k[i] 12 | k[i] = k[min_pos] 13 | k[min_pos] = temp 14 | return k 15 | 16 | 17 | print(sort(k)) -------------------------------------------------------------------------------- /decorators/lesson.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | 4 | def calculation(func): 5 | def time_wrapper(x, y): 6 | start = datetime.now() 7 | print(func(x, y)) 8 | end = datetime.now() 9 | return end - start 10 | return time_wrapper 11 | 12 | 13 | @calculation 14 | def add_numbers(x, y): 15 | return x + y 16 | 17 | 18 | @calculation 19 | def subtract_numbers(x, y): 20 | return x - y 21 | 22 | 23 | @calculation 24 | def multiply_numbers(x, y): 25 | return x * y 26 | 27 | 28 | print(multiply_numbers(5, 5)) 29 | -------------------------------------------------------------------------------- /functions/functions.py: -------------------------------------------------------------------------------- 1 | # method #1 2 | def value(): 3 | print("am in a function") 4 | 5 | value() 6 | 7 | # method #2 8 | def value2(name): 9 | print(f'name: {name}') 10 | 11 | value2('Prashanth') 12 | value2('Sams') 13 | value2('David') 14 | 15 | # arbitrary arguments - method #1 16 | def test_func(*args): 17 | print(f'{args[0]}: {args[1]}, age: {args[2]}') 18 | 19 | test_func('name', 'Prashanth', 30) 20 | 21 | # arbitrary arguments - method #2 22 | def test_func(args): 23 | print(f'{args[0]}: {args[1]}, age: {args[2]}') 24 | 25 | test_func(('name', 'Prashanth', 30)) 26 | 27 | # arbitrary keyword arguments 28 | def keywords(**args): 29 | print(f'{args["name"]}, {args["age"]}, {args["sex"]}') 30 | 31 | keywords(name='Prashanth', age='30', sex='male') 32 | 33 | # list as an argument 34 | def list(arr): 35 | for i in arr: 36 | print(i) 37 | 38 | list(['Prashanth', '30', 'male']) -------------------------------------------------------------------------------- /functions/lesson.py: -------------------------------------------------------------------------------- 1 | 2 | def keyword_check(kwargs): 3 | kc = {} 4 | if 'index' in kwargs: kc['index'] = 'elements' 5 | if 'index' not in kwargs: kc['index'] = 'element' 6 | return "".join(kc.values()) 7 | 8 | 9 | def xfunc(**kwargs): 10 | print(keyword_check(kwargs)) 11 | 12 | 13 | xfunc(index=2, inaasddex=3) -------------------------------------------------------------------------------- /functions/lesson3.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | 4 | def add_numbers(x, y): 5 | return x + y 6 | 7 | 8 | def subtract_numbers(x, y): 9 | return x - y 10 | 11 | 12 | def multiply_numbers(x, y): 13 | return x * y 14 | 15 | 16 | def calculation(func): 17 | print(func(5, 5)) 18 | 19 | 20 | calculation(add_numbers) -------------------------------------------------------------------------------- /functions/nested_functions.py: -------------------------------------------------------------------------------- 1 | def calculation(z): 2 | def new(x, y): 3 | def newx(x,y,z): 4 | return x+y+z 5 | return x+y 6 | return z 7 | 8 | 9 | print(calculation(5)) 10 | print(calculation(5+5)) 11 | print(calculation(5+5+5)) -------------------------------------------------------------------------------- /inheritance/lesson.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | 3 | def __init__(self, name, age): 4 | self.name = name 5 | self.age = age 6 | 7 | def record(self): 8 | vault = dict(name=self.name, age=self.age) 9 | print(vault) 10 | 11 | 12 | x = Person('Prashanth', 30) 13 | x.record() -------------------------------------------------------------------------------- /inheritance/lesson_2.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | 3 | def __init__(self, name, age): 4 | self.name = name 5 | self.age = age 6 | 7 | def record(self): 8 | vault = dict(name=self.name, age=self.age) 9 | print(vault) 10 | 11 | 12 | class Student(Person): 13 | 14 | def __init__(self, name, age): 15 | super().__init__(name, age) 16 | # Person.__init__(self, name, age) 17 | self.sex = 'male' 18 | 19 | 20 | Student('Prashanth', 30).record() 21 | Student('Sams', 31).record() 22 | print(Student('Sams', 31).sex) 23 | -------------------------------------------------------------------------------- /inheritance/lesson_3.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | 3 | def __init__(self, name, age): 4 | self.name = name 5 | self.age = age 6 | 7 | def record(self): 8 | vault = dict(name=self.name, age=self.age) 9 | print(vault) 10 | 11 | 12 | class Student(Person): 13 | 14 | def __init__(self, name, age, sex): 15 | super().__init__(name, age) 16 | self.sex = sex 17 | 18 | 19 | print(Student('Sams', 31, 'Male').sex) 20 | Person('Prashanth', 30).record() 21 | -------------------------------------------------------------------------------- /inheritance/lesson_4.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | 3 | def __init__(self, name, age): 4 | self.name = name 5 | self.age = age 6 | 7 | def record(self): 8 | vault = dict(name=self.name, age=self.age) 9 | print(vault) 10 | 11 | 12 | class Student(Person): 13 | 14 | def __init__(self, n, a): 15 | super().__init__(n, a) 16 | 17 | def welcome(self): 18 | print(f"{self.name} {self.age}") 19 | 20 | 21 | Student('Sams', 31).welcome() 22 | -------------------------------------------------------------------------------- /iterators/lesson.py: -------------------------------------------------------------------------------- 1 | # tuple iterator #1 2 | k = ('bike', 'car', 'cart', 'cycle') 3 | x = iter(k) 4 | 5 | print(next(x)) 6 | print(next(x)) 7 | print(next(x)) 8 | print(next(x)) -------------------------------------------------------------------------------- /iterators/lesson2.py: -------------------------------------------------------------------------------- 1 | # tuple iterator #2 2 | k = ('bike', 'car', 'cart', 'cycle') 3 | l = len(k) 4 | x = iter(k) 5 | 6 | for i in range(l): 7 | print(next(x)) -------------------------------------------------------------------------------- /iterators/lesson3.py: -------------------------------------------------------------------------------- 1 | # string iterator #2 2 | k = 'Prashanth' 3 | l = len(k) 4 | x = iter(k) 5 | 6 | for i in range(l): 7 | print(next(x)) -------------------------------------------------------------------------------- /iterators/lesson4.py: -------------------------------------------------------------------------------- 1 | # string iterator 2 | k = 'Prashanth' 3 | 4 | for i in k: 5 | print(i) 6 | 7 | 8 | # tuple iterator 9 | l = ('bike', 'car', 'cart', 'cycle') 10 | 11 | for i in l: 12 | print(i) -------------------------------------------------------------------------------- /iterators/lesson5.py: -------------------------------------------------------------------------------- 1 | class CustomIter: 2 | 3 | def __iter__(self): 4 | self.a = 1 5 | return self 6 | 7 | def __next__(self): 8 | if self.a <= 10: 9 | k = self.a 10 | self.a += 1 11 | return k 12 | else: 13 | raise StopIteration 14 | 15 | 16 | for i in iter(CustomIter()): 17 | print(i) -------------------------------------------------------------------------------- /iterators/lesson6.py: -------------------------------------------------------------------------------- 1 | class CustomIter: 2 | 3 | def __iter__(self): 4 | self.a = 1 5 | return self 6 | 7 | def __next__(self): 8 | k = self.a 9 | self.a += 2 10 | return k 11 | 12 | 13 | x = iter(CustomIter()) 14 | print(next(x)) 15 | print(next(x)) 16 | print(next(x)) 17 | -------------------------------------------------------------------------------- /iterators/lesson7.py: -------------------------------------------------------------------------------- 1 | class CustomIter: 2 | 3 | def __init__(self, increment): 4 | self.increment = increment 5 | self.a = 1 6 | 7 | def __next__(self): 8 | k = self.a 9 | self.a += self.increment 10 | return k 11 | 12 | 13 | x = CustomIter(4) 14 | print(next(x)) 15 | print(next(x)) 16 | print(next(x)) -------------------------------------------------------------------------------- /lambda/lesson.py: -------------------------------------------------------------------------------- 1 | # type #1 2 | x = lambda a: a + 1 3 | print(x(1)) 4 | 5 | # type 2 6 | x = lambda a, b: a + b 7 | print(x(1, 2)) 8 | 9 | -------------------------------------------------------------------------------- /lambda/lesson2.py: -------------------------------------------------------------------------------- 1 | result = { 2 | 'a': lambda x: x * 5, 3 | 'b': lambda x: x + 7, 4 | 'c': lambda x: x - 2 5 | }['b'](1) 6 | 7 | print(result) 8 | -------------------------------------------------------------------------------- /lambda/lesson3.py: -------------------------------------------------------------------------------- 1 | result = { 2 | 'a': { 3 | 'name': lambda x: x * 5, 4 | 'age': lambda x: x + 5 5 | }['name'](1), 6 | 'b': { 7 | 'name': lambda x: x + 7, 8 | 'age': lambda x: x + 7 9 | }['age'](1) 10 | }['a'] 11 | 12 | print(result) 13 | -------------------------------------------------------------------------------- /loop/break_continue.py: -------------------------------------------------------------------------------- 1 | fruits = ['apple', 'orange', 'banana'] 2 | 3 | # break & continue 4 | for i in fruits: 5 | if i == "orange": 6 | break 7 | else: 8 | print(i) 9 | continue 10 | -------------------------------------------------------------------------------- /loop/each_with_values.py: -------------------------------------------------------------------------------- 1 | fruits = ['apple', 'orange', 'banana'] 2 | 3 | for i, val in enumerate(fruits): 4 | print(f'{i} is {val}') -------------------------------------------------------------------------------- /loop/length.py: -------------------------------------------------------------------------------- 1 | # length of the array 2 | fruits = ['apple', 'orange', 'banana'] 3 | print(len(fruits)) 4 | 5 | # length of each value in an array 6 | for i in fruits: 7 | print(f'{i} with length {len(i)}') -------------------------------------------------------------------------------- /loop/range.py: -------------------------------------------------------------------------------- 1 | # avoid empty value in a loop 2 | for i in range(5): 3 | pass 4 | 5 | # initial and final range 6 | for i in range(10, 20): 7 | print(i) 8 | 9 | # loop 0-100 by increasing iterator by 3 10 | for i in range(0, 100, 20): 11 | print(i) 12 | 13 | # double loop 14 | for i in range(0, 5): 15 | for j in range(5, 10): 16 | print(i, j) -------------------------------------------------------------------------------- /loop/single_line.py: -------------------------------------------------------------------------------- 1 | k = ['a', 'b', 'c', 'd', 'e', 'f'] 2 | 3 | # print a list one by one 4 | [print(i) for i in k] 5 | 6 | # convert list to string 7 | print(''.join([i for i in k])) 8 | print(''.join(k)) 9 | 10 | k = [1, 2, 3, 4, 5, 6] 11 | print([i for i in k if i >= 4]) -------------------------------------------------------------------------------- /loop/while_infinite_loop.py: -------------------------------------------------------------------------------- 1 | i = 0 2 | while True: 3 | if i == 5: break 4 | print(i) 5 | i += 1 -------------------------------------------------------------------------------- /methods/methods.py: -------------------------------------------------------------------------------- 1 | class Fruit: 2 | 3 | """ 4 | can modify object instance state 5 | can modify class state 6 | """ 7 | def grapes(self): 8 | print('instance method') 9 | 10 | """ 11 | can't modify object instance state 12 | can modify class state 13 | """ 14 | @classmethod 15 | def orange(cls): 16 | print('class method') 17 | 18 | """ 19 | can't modify object instance state 20 | can't modify class state 21 | """ 22 | @staticmethod 23 | def apple(): 24 | print('simple method') 25 | 26 | 27 | Fruit().grapes() 28 | Fruit().orange() 29 | Fruit().apple() -------------------------------------------------------------------------------- /methods/methods_2.py: -------------------------------------------------------------------------------- 1 | class Fruits: 2 | def __init__(self, names): 3 | self.names = names 4 | 5 | def __repr__(self): 6 | return f'{self.names}' 7 | 8 | 9 | print(Fruits('Banana')) -------------------------------------------------------------------------------- /methods/methods_3.py: -------------------------------------------------------------------------------- 1 | class Fruits: 2 | def __init__(self, names, quantity): 3 | self.names = names 4 | self.quantity = quantity 5 | 6 | def buy(self): 7 | return self._price(self.quantity) 8 | 9 | @staticmethod 10 | def _price(p): 11 | return p * 12 12 | 13 | 14 | print(Fruits('Banana', 5).buy()) 15 | print(Fruits._price(5)) 16 | -------------------------------------------------------------------------------- /projects/check_palindrome.py: -------------------------------------------------------------------------------- 1 | # method #1 2 | def palindrome(value): 3 | 4 | for i in range(len(value)): 5 | for j in range(len(value)-i-1, -1, -1): 6 | if value[i] == value[j]: 7 | break 8 | else: 9 | return False 10 | 11 | return True 12 | 13 | print(palindrome('mom')) 14 | 15 | # method #2 16 | def palindrome(k): 17 | for i in range(len(k)): 18 | for j in range(len(k)-i, 0, -1): 19 | print(j) 20 | if k[i]==k[j-1]: 21 | break 22 | else: 23 | return False 24 | return True 25 | 26 | print(palindrome("mam")) -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicate_chars.py: -------------------------------------------------------------------------------- 1 | name ="Prashanth" 2 | 3 | def getLocation(value): 4 | for i in range(len(value)): 5 | for j in range(i, len(value)-1): 6 | if value[i] == value[j+1]: 7 | yield j+1 8 | 9 | def removeDuplicates(value): 10 | k = list(getLocation(value)) 11 | print(k) 12 | for i in range(len(value)-1, -1, -1): 13 | if i in k: 14 | value = value[:i] + '' + value[i + 1:] 15 | return value 16 | print(removeDuplicates("Prashanth")) -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicate_chars_2.py: -------------------------------------------------------------------------------- 1 | k = 'Prashanth' 2 | m = [] 3 | 4 | for i in k: 5 | if i not in m: 6 | m.append(i) 7 | 8 | print("".join(m)) -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicate_integer_in_array.py: -------------------------------------------------------------------------------- 1 | k = [5, 6, 6, 2, 3, 5, 1, 6, 7] 2 | m = [] 3 | 4 | for i in range(len(k)): 5 | for j in range(i, len(k)-1): 6 | if k[i] == k[j+1]: 7 | m.append(j+1) 8 | 9 | m = list(dict.fromkeys(m)) 10 | m.sort(reverse=True) 11 | 12 | for i in m: 13 | k.pop(i) 14 | 15 | print(k) -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicate_strings_in_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | through set you can opt out all the duplicates but it is unordered 3 | """ 4 | 5 | k = ['apple', 'orange', 'orange', 'grapes', 'apple', 'apple'] 6 | l = set(k) 7 | k = list(l) 8 | print(k) 9 | 10 | """ 11 | dict is ordered so it helps 12 | """ 13 | k = ['apple', 'orange', 'orange', 'grapes', 'apple', 'apple'] 14 | l = list(dict.fromkeys(k)) 15 | print(l) -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicate_strings_in_array_2.py: -------------------------------------------------------------------------------- 1 | k = ['apple', 'orange', 'orange', 'grapes', 'apple', 'apple', 'apple'] 2 | m = [] 3 | 4 | 5 | def remove_duplicates(k): 6 | for i in range(len(k)): 7 | for j in range(i, len(k)-1): 8 | if k[i] == k[j+1]: 9 | m.append(j+1) 10 | 11 | l = list(dict.fromkeys(m)) 12 | l.sort(reverse=True) 13 | 14 | for i in l: 15 | k.pop(i) 16 | 17 | return k 18 | 19 | 20 | print(remove_duplicates(k)) 21 | -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicate_strings_in_array_3.py: -------------------------------------------------------------------------------- 1 | k = ['apple', 'orange', 'orange', 'grapes', 'apple', 'apple', 'apple'] 2 | m = [] 3 | 4 | 5 | def remove_duplicates(k): 6 | for i in k: 7 | if i not in m: 8 | m.append(i) 9 | 10 | return m 11 | 12 | 13 | print(remove_duplicates(k)) 14 | -------------------------------------------------------------------------------- /projects/duplicates/remove_duplicates_from_list.py: -------------------------------------------------------------------------------- 1 | k = ['a', 'b', 'c', 'c', 'b'] 2 | 3 | print(list(dict.fromkeys(k))) -------------------------------------------------------------------------------- /projects/duplicates/remove_objects_with_duplicate_values.py: -------------------------------------------------------------------------------- 1 | 2 | k = [ 3 | {'name': 'Prashanth', 'age': 32, 'sex': 'male', 'color': 'black'}, 4 | {'name': 'Sunil', 'age': 34, 'sex': 'male'}, 5 | {'name': 'Lolita', 'age': 35, 'sex': 'female', 'color': 'white'}, 6 | {'name': 'Pravin', 'age': 36, 'sex': 'male'}, 7 | ] 8 | 9 | result = [] 10 | 11 | for i in k: 12 | if 'color' in i: 13 | result.append(i) 14 | 15 | print(result) 16 | 17 | output = [] 18 | 19 | for j in result: 20 | if j['sex'] == 'male': 21 | output.append(j) 22 | 23 | print(output) 24 | 25 | -------------------------------------------------------------------------------- /projects/factorial.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | k = 5 3 | fac = 1 4 | 5 | for i in range(k, 1, -1): 6 | fac = i*fac 7 | 8 | print(fac) 9 | 10 | 11 | # method 2 12 | k = 7 13 | fac = 1 14 | 15 | while(k != 0): 16 | fac = fac * k 17 | k -= 1 18 | 19 | print(fac) -------------------------------------------------------------------------------- /projects/fibonacci_series.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | num = input() 3 | value = [] 4 | a, b = 0, 1 5 | 6 | value.append(a) 7 | value.append(b) 8 | 9 | for i in range(int(num)-2): 10 | c = a + b 11 | a = b 12 | b = c 13 | # a, b = b, c 14 | value.append(c) 15 | 16 | print(value) 17 | 18 | 19 | # method 2 20 | val = 10 21 | fib = [] 22 | a, b = 0, 1 23 | 24 | fib.append(a) 25 | fib.append(b) 26 | 27 | for i in range(val): 28 | if((i != 0) and (i != 1)): 29 | fib.append(fib[i-1]+fib[i-2]) 30 | 31 | print(fib) -------------------------------------------------------------------------------- /projects/find_3_consecutive_strings.py: -------------------------------------------------------------------------------- 1 | def find_consecutive_3_strings(value): 2 | cons = 1 3 | result = [] 4 | 5 | for i in range(len(value)): 6 | for j in range(i, len(value)-1): 7 | if value[i] == value[j+1]: 8 | cons += 1 9 | if cons == 3: 10 | result.append(value[i]) 11 | break 12 | else: 13 | break 14 | 15 | cons = 1 16 | 17 | return result 18 | 19 | print(find_consecutive_3_strings('aaxxxdddxyyzzz')) -------------------------------------------------------------------------------- /projects/length/find_string_length.py: -------------------------------------------------------------------------------- 1 | i = 0 2 | 3 | 4 | def strlen(value): 5 | 6 | for i in range(len(value)): 7 | i += 1 8 | 9 | return i 10 | 11 | 12 | print(strlen('Prashanth')) -------------------------------------------------------------------------------- /projects/length/find_string_length_2.py: -------------------------------------------------------------------------------- 1 | 2 | def strlen(value, j=0): 3 | 4 | for i in value: 5 | j += 1 6 | return j 7 | 8 | 9 | print(strlen('Prashanth')) -------------------------------------------------------------------------------- /projects/list_to_string.py: -------------------------------------------------------------------------------- 1 | k = 'Prashanth' 2 | name = '' 3 | value = [] 4 | 5 | for i in k: 6 | value.append(i) 7 | 8 | print(str(''.join(value))) 9 | print(str('.'.join(value))) 10 | -------------------------------------------------------------------------------- /projects/match/remove_matching_strings.py: -------------------------------------------------------------------------------- 1 | k = ['apple', 'orange', 'orange', 'grapes', 'apple'] 2 | 3 | for i, j in enumerate(k): 4 | if j == 'grapes': 5 | k.pop(i) 6 | 7 | print(k) -------------------------------------------------------------------------------- /projects/maxmin/max_char_string_in_an_array.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | k = ['cat', 'zebra', 'girrafe', 'dog', 'tiger'] 3 | 4 | for i in range(len(k)-1): 5 | if len(k[i]) > len(k[i+1]): 6 | temp = k[i] 7 | k[i] = k[i+1] 8 | k[i+1] = temp 9 | 10 | print(k[-1]) 11 | 12 | # method 2 13 | k = ['cat', 'zebra', 'girrafe', 'dog', 'tiger'] 14 | 15 | count = 0 16 | for i in range(len(k)-1): 17 | if len(k[i]) > count: 18 | count = len(k[i]) 19 | long = i 20 | 21 | print(k[long]) 22 | -------------------------------------------------------------------------------- /projects/maxmin/max_number_in_an_array.py: -------------------------------------------------------------------------------- 1 | k = [9, 4, 2, 44, 6, 23, 123, 33, 888, 34, 999, 9] 2 | 3 | # method 1 4 | print(max(k)) 5 | 6 | # method 2 7 | for i in range(len(k)): 8 | for j in range(i, len(k)-1): 9 | if k[i] > k[j+1]: 10 | temp = k[i] 11 | k[i] = k[j+1] 12 | k[j+1] = temp 13 | 14 | print(k[-1]) 15 | 16 | # method 3 17 | k = [9, 4, 2, 44, 6, 23, 123, 33, 888, 34, 999, 9] 18 | max = 0 19 | 20 | for i in k: 21 | if i > max: 22 | max = i 23 | 24 | print(max) 25 | -------------------------------------------------------------------------------- /projects/maxmin/min_char_string_in_an_array.py: -------------------------------------------------------------------------------- 1 | k = ['cat', 'zebra', 'girrafe', 'dog', 'tiger'] 2 | 3 | for i in range(len(k)-1): 4 | if len(k[i]) < len(k[i+1]): 5 | temp = k[i] 6 | k[i] = k[i+1] 7 | k[i+1] = temp 8 | 9 | print(k) -------------------------------------------------------------------------------- /projects/maxmin/min_number_in_an_array.py: -------------------------------------------------------------------------------- 1 | k = [5, 3, 1, 8, 6, 1, 2] 2 | 3 | for i in range(len(k)): 4 | for j in range(i, len(k)-1): 5 | if k[j+1] > k[i]: 6 | temp = k[i] 7 | k[i] = k[j+1] 8 | k[j+1] = temp 9 | 10 | k = k[-1:] 11 | print("".join(map(str, k))) -------------------------------------------------------------------------------- /projects/online test/codingbat/diff21.py: -------------------------------------------------------------------------------- 1 | def missing_char(str, n): 2 | # return 3 | return str[:n] + str[n+1:] 4 | 5 | 6 | print(missing_char('kitten', 1)) 7 | print(missing_char('kitten', 0)) 8 | print(missing_char('kitten', 4)) 9 | -------------------------------------------------------------------------------- /projects/online test/codingbat/frontback.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | def front_back(str): 3 | if len(str) <= 1: 4 | return str 5 | 6 | mid = str[1:len(str)-1] # can be written as str[1:-1] 7 | 8 | # last + mid + first 9 | return str[len(str)-1] + mid + str[0] 10 | 11 | 12 | # method 2 13 | def front_back(str): 14 | 15 | first_val = str[:1] 16 | last_val = str[int(len(str))-1:] 17 | 18 | m = list(str) 19 | 20 | m[0] = last_val 21 | m[len(str)-1] = first_val 22 | 23 | return (''.join(m)) 24 | 25 | result = front_back('Hey am okay now') 26 | print(result) -------------------------------------------------------------------------------- /projects/online test/codingbat/notstring.py: -------------------------------------------------------------------------------- 1 | # Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. 2 | 3 | # not_string('candy') → 'not candy' 4 | # not_string('x') → 'not x' 5 | # not_string('not bad') → 'not bad' 6 | 7 | def not_string(str): 8 | if (str[:3] == 'not') and len(str) < 4: 9 | return str 10 | elif 'not ' in str[:4]: 11 | return str 12 | else: 13 | return 'not '+ str 14 | 15 | print(not_string('candy')) 16 | print(not_string('x')) 17 | print(not_string('not bad')) -------------------------------------------------------------------------------- /projects/online test/codingbat/vacation.py: -------------------------------------------------------------------------------- 1 | # The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. 2 | 3 | 4 | # sleep_in(False, False) → True 5 | # sleep_in(True, False) → False 6 | # sleep_in(False, True) → True 7 | 8 | def sleep_in(weekday, vacation): 9 | 10 | if not weekday or vacation: 11 | return True 12 | else: 13 | return False 14 | 15 | 16 | sleep_in(False, False) 17 | sleep_in(True, False) 18 | sleep_in(False, True) 19 | sleep_in(True, True) -------------------------------------------------------------------------------- /projects/online test/hackerrank/fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | # 4 | # Complete the 'fizzBuzz' function below. 5 | # 6 | # The function accepts INTEGER n as parameter. 7 | # 8 | 9 | def fizzBuzz(n): 10 | k = 'fizzBuzz' 11 | 12 | for i in range(n+1): 13 | if i == 0: 14 | continue 15 | elif i % 15 == 0: 16 | print(k[:int(len(k)/2)].capitalize() + k[int(len(k)/2):].capitalize()) 17 | elif i % 5 == 0: 18 | print(k[int(len(k)/2):]) 19 | elif i % 3 == 0: 20 | print(k[:int(len(k)/2)].capitalize()) 21 | 22 | else: 23 | print(i) 24 | 25 | if __name__ == '__main__': 26 | n = int(input().strip()) 27 | 28 | fizzBuzz(n) -------------------------------------------------------------------------------- /projects/online test/hackerrank/test.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prashanth-sams/python-workshop/c0c1a4dad38de37d9d1392c4880969bee0ee9283/projects/online test/hackerrank/test.py -------------------------------------------------------------------------------- /projects/prime_number.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | k = 32 3 | 4 | flag = False 5 | 6 | for i in range(2, k): 7 | if k % i == 0: 8 | flag = False 9 | break 10 | else: 11 | flag = True 12 | 13 | if flag == False: 14 | print(str(k) + ' is not a prime number') 15 | else: 16 | print(str(k) + ' is a prime number') 17 | 18 | 19 | # method 2 20 | num = 29 21 | 22 | flag = False 23 | 24 | if num > 1: 25 | for i in range(2, num): 26 | if (num % i) == 0: 27 | flag = True 28 | break 29 | 30 | if flag: 31 | print(num, "is not a prime number") 32 | else: 33 | print(num, "is a prime number") 34 | 35 | 36 | # method 3 37 | def checkPrimeNumber(value): 38 | if(value == 1): return False 39 | for i in range(2, value): 40 | if(value % i == 0): 41 | return False 42 | break 43 | 44 | return True 45 | 46 | 47 | l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] 48 | 49 | for i in l: 50 | print(checkPrimeNumber(i)) -------------------------------------------------------------------------------- /projects/print_all_prime_numbers.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | k = 32 3 | m = [] 4 | for j in range(2, k+1): 5 | for i in range(2, j): 6 | if j % i == 0: 7 | break 8 | else: 9 | m.append(j) 10 | print(list(dict.fromkeys(m))) 11 | 12 | 13 | 14 | # method 2 15 | k = 32 16 | 17 | flag = False 18 | 19 | m = [] 20 | 21 | for j in range(2, k+1): 22 | for i in range(2, j): 23 | if j % i == 0: 24 | flag = False 25 | break 26 | else: 27 | flag = True 28 | 29 | if flag == True: 30 | m.append(j) 31 | flag == False 32 | 33 | print(m) 34 | -------------------------------------------------------------------------------- /projects/print_strings_in_even_position.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | k = 'Prashanth' 3 | m = '' 4 | 5 | for i in range(len(k)): 6 | if i % 2 != 0: 7 | m = m+k[i] 8 | 9 | print(m) 10 | 11 | 12 | # method 2 13 | k = 'Prashanth' 14 | val = '' 15 | 16 | for i, j in enumerate(k): 17 | if (i % 2 != 0): 18 | val = val+j 19 | 20 | print(val) -------------------------------------------------------------------------------- /projects/random/generate_list_with_random_values_and_fixed_length.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | # method 1 5 | k = random.sample(range(0,8), 5) 6 | k.sort() 7 | print(k) 8 | 9 | 10 | # method 2 11 | l = [] 12 | 13 | for i in range(5): 14 | k = random.randint(4000,4999) 15 | l.append(k) 16 | 17 | print(l) -------------------------------------------------------------------------------- /projects/random/generate_random_int_within_range.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | k = random.randint(4000,4999) 4 | print(k) -------------------------------------------------------------------------------- /projects/remove_empty_arrays_in_list.py: -------------------------------------------------------------------------------- 1 | k = ['a', 'b', 'c', 'c', 'b'] 2 | 3 | print(list(filter(None, k))) -------------------------------------------------------------------------------- /projects/remove_objects_with_none.py: -------------------------------------------------------------------------------- 1 | k = [ 2 | {'name': 'Prashanth', 'age': 32, 'sex': 'male'}, 3 | {'name': 'XXX', 'age': 43, 'sex': None}, 4 | {'name': 'Christal', 'age': 26, 'sex': 'female', 'salary': 2000}, 5 | {'name': 'YYY', 'age': 44, 'sex': None} 6 | ] 7 | 8 | value = [] 9 | for i in k: 10 | if i['sex'] != None : value.append(i) 11 | print(value) 12 | 13 | 14 | key = [] 15 | for j in k: 16 | if 'salary' not in j: key.append(j) 17 | print(key) -------------------------------------------------------------------------------- /projects/remove_vowels.py: -------------------------------------------------------------------------------- 1 | 2 | k = 'Prashanth' 3 | val = [] 4 | 5 | def isVowel(i): 6 | vowel = ['a', 'e', 'i', 'o', 'u'] 7 | if i in vowel: 8 | return True 9 | else: 10 | return False 11 | 12 | for i in k: 13 | if isVowel(i) is True: 14 | pass 15 | else: 16 | val.append(i) 17 | 18 | print(val) -------------------------------------------------------------------------------- /projects/reverse/reverse_string_recursion.py: -------------------------------------------------------------------------------- 1 | def rev(name): 2 | if name == "": 3 | return name 4 | else: 5 | return rev(name[1:]) + name[0] 6 | 7 | print(rev('Prashanth')) -------------------------------------------------------------------------------- /projects/reverse/reverse_text.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | k = 'Hello world!' 3 | name = '' 4 | 5 | for i in k: 6 | name = f'{i}{name}' 7 | # name = i + name 8 | 9 | print(name) 10 | 11 | 12 | # method 2 13 | k = 'Hello world!'[::-1] 14 | print(k) 15 | 16 | 17 | # method 3 18 | k = 'Hello world!' 19 | print(''.join(reversed(k))) 20 | 21 | 22 | # method 4 23 | def reverse(name): 24 | n = '' 25 | for i in name: 26 | n = f'{i}{n}' 27 | return n 28 | 29 | print(reverse('Hello world!')) 30 | 31 | 32 | # method 5 33 | k = "prashanth" 34 | l = "" 35 | 36 | for i in k: l = i+l 37 | 38 | print(l) 39 | 40 | 41 | # method 6 42 | k = "Hello world!" 43 | l = [] 44 | 45 | length = len(k)-1 46 | 47 | while(length != -1): 48 | l.append(k[length]) 49 | length -= 1 50 | 51 | print(''.join(l)) 52 | 53 | 54 | # method 7 55 | k = 'Hello world!' 56 | 57 | output = [] 58 | 59 | for i in range(len(k)-1, -1, -1): 60 | output.append(k[i]) 61 | 62 | print(''.join(output)) 63 | 64 | 65 | # method 8 66 | k = 'Hello world!' 67 | l = '' 68 | 69 | for i in range(len(k)-1, -1, -1): 70 | l = l + k[i] 71 | 72 | print(l) 73 | 74 | 75 | # method 9 76 | def reverse(data): 77 | for index in range(len(data)-1, -1, -1): 78 | yield data[index] 79 | 80 | print("".join(list(reverse('abcdefg')))) 81 | 82 | # method 10 83 | k = "prashanth" 84 | l = [] 85 | 86 | for i in range(len(k), 0, -1): 87 | l.append(k[i-1]) 88 | 89 | print(str(''.join(l))) -------------------------------------------------------------------------------- /projects/reverse/reverse_text_alternate_caps.py: -------------------------------------------------------------------------------- 1 | # method 1 2 | def isodd(integer): 3 | if integer % 2 == 0: 4 | return True 5 | else: 6 | return False 7 | 8 | k = 'Prashanth' 9 | name = '' 10 | 11 | for i, val in enumerate(k): 12 | if isodd(i) is True: val = val.upper() 13 | name = f'{val}{name}' 14 | 15 | print(name) 16 | 17 | 18 | # method 2 19 | k = 'prashanth' 20 | val = '' 21 | 22 | for i in range(len(k)-1, -1, -1): 23 | if(i % 2 != 0): 24 | val = val + k[i].upper() 25 | else: 26 | val = val + k[i] 27 | 28 | print(val) 29 | -------------------------------------------------------------------------------- /projects/reverse/reverse_text_alternate_remove.py: -------------------------------------------------------------------------------- 1 | # type #1 2 | def isodd(i): 3 | if i % 2 == 0: 4 | return False 5 | else: 6 | return True 7 | 8 | k = 'Prashanth' 9 | name = '' 10 | 11 | for i, val in enumerate(k): 12 | if isodd(i) is True: val = '' 13 | name = '{}{}'.format(val, name) 14 | 15 | print(name) 16 | 17 | # type #2 18 | x = 'Prashanth'[::-2] 19 | print(x) 20 | 21 | # type #3 22 | k = "prashanth" 23 | l = [] 24 | 25 | for i, j in enumerate(range(len(k), 0, -1)): 26 | if i%2==0: 27 | print(k[j-1]) -------------------------------------------------------------------------------- /projects/singleton.py: -------------------------------------------------------------------------------- 1 | class Base(object): 2 | 3 | _instance = None 4 | 5 | def __new__(cls, *args, **kwargs): 6 | if not cls._instance: 7 | cls._instance = super(Base, cls).__new__(cls, *args, **kwargs) 8 | return cls._instance 9 | 10 | if __name__ == "__main__": 11 | B1 = Base() 12 | B2 = Base() 13 | print(B1) 14 | print(B2) -------------------------------------------------------------------------------- /projects/sort/sort_object_list_in_an_array.py: -------------------------------------------------------------------------------- 1 | from operator import itemgetter; 2 | 3 | k = [ 4 | {'name': 'Prashanth', 'age': 32, 'sex': 'male', 'color': 'black'}, 5 | {'name': 'Sunil', 'age': 34, 'sex': 'male'}, 6 | {'name': 'Lolita', 'age': 35, 'sex': 'female', 'color': 'white'}, 7 | {'name': 'Pravin', 'age': 36, 'sex': 'male'}, 8 | ] 9 | 10 | result = sorted(k, key=itemgetter('age')) 11 | 12 | print(result) -------------------------------------------------------------------------------- /projects/tax/income_tax.py: -------------------------------------------------------------------------------- 1 | """ 2 | 0% for < 20000 AED 3 | 20% for >= 20000 AED 4 | 30% for >= 40000 AED 5 | 50% for >= 60000 AED 6 | """ 7 | 8 | # method 1 9 | def salary(value): 10 | if value < 20000: 11 | return value 12 | elif value >= 20000 and value < 40000: 13 | return value - (value * 20 / 100) 14 | elif value >= 40000 and value < 60000: 15 | return value - (value * 30 / 100) 16 | elif value >= 60000: 17 | return value - (value * 50 / 100) 18 | else: 19 | raise Exception('invalid amount') 20 | 21 | 22 | print(salary(22000)) 23 | 24 | 25 | # method 2 26 | def salary_2(value): 27 | if value in (0, 20000): 28 | return value 29 | elif value in (20000, 40000): 30 | return value - (value * 20 / 100) 31 | elif value in (40000, 60000): 32 | return value - (value * 30 / 100) 33 | elif value >= 60000: 34 | return value - (value * 50 / 100) 35 | else: 36 | raise Exception('invalid amount') 37 | 38 | print(salary(22000)) 39 | 40 | -------------------------------------------------------------------------------- /projects/tax/income_tax_direct.py: -------------------------------------------------------------------------------- 1 | 2 | def salary(value, tax): 3 | return value - (value * tax / 100) 4 | 5 | 6 | print(salary(22000, 30)) 7 | -------------------------------------------------------------------------------- /projects/tax/income_tax_dynamic.py: -------------------------------------------------------------------------------- 1 | 2 | def salary(value, tax_slab): 3 | 4 | sum = [*tax_slab.values()] 5 | tax = [*tax_slab.keys()] 6 | 7 | if value < sum[0]: 8 | return value - (value * tax[0] / 100) 9 | elif value < sum[1]: 10 | return value - (value * tax[1] / 100) 11 | elif value < sum[2]: 12 | return value - (value * tax[2] / 100) 13 | else: 14 | return value - (value * 50 / 100) 15 | 16 | 17 | print(salary(82000, {1: 20000, 20: 40000, 30: 60000})) 18 | -------------------------------------------------------------------------------- /pytest/Readme.md: -------------------------------------------------------------------------------- 1 | # pytest bank 2 | > pytest exercises 3 | 4 | ### Feature 5 | - [x] Basic 6 | - [x] Fixture #mock-data 7 | - [x] Mark #Tags 8 | - [x] Parameterize #data-driven 9 | - [x] Yield #hooks 10 | - [x] Skip tests 11 | 12 | ### Pytest Runner 13 | 14 | | Type | Command | 15 | | -------------- | --------- | 16 | | generic run | `pytest -v -s pytest/test_yield_fixture.py` | 17 | | Run specific test case| `pytest -v -s pytest/test_yield_fixture.py::test_fail` | 18 | | Run tagged tests | `pytest -v -s pytest/test_mark.py -m 'slow'` | 19 | -------------------------------------------------------------------------------- /pytest/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | markers = 3 | slow: mark as slow tests 4 | fast: mark as fast tests -------------------------------------------------------------------------------- /pytest/test_fixture.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.fixture 5 | def mock_data(): 6 | name = 'Jesus' 7 | profession = 'Saving world' 8 | history = 'Created everything we know and what we see, you and me' 9 | return [name, profession, history] 10 | 11 | 12 | def test_fixture_pass(mock_data): 13 | assert mock_data[0] == 'Jesus' 14 | 15 | 16 | def test_fixture_fail(mock_data): 17 | assert mock_data[1] == 'Jesus' 18 | -------------------------------------------------------------------------------- /pytest/test_mark.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.mark.slow 5 | def test_fixture_pass(): 6 | assert 5 == 5 7 | 8 | 9 | @pytest.mark.fast 10 | def test_fixture_fail(): 11 | assert 5 == 6 12 | -------------------------------------------------------------------------------- /pytest/test_parameter.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.mark.parametrize('a, b', [(1, 1), (1, 2)]) 5 | def test_fixture_pass(a, b): 6 | assert a == b -------------------------------------------------------------------------------- /pytest/test_simple.py: -------------------------------------------------------------------------------- 1 | def test_pass(): 2 | pass 3 | 4 | 5 | def test_fail(): 6 | raise Exception('fail') -------------------------------------------------------------------------------- /pytest/test_skip_xfail.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.mark.skip 5 | def test_skip(): 6 | assert 5 == 5 7 | 8 | 9 | @pytest.mark.xfail 10 | def test_xfail(): 11 | assert 5 == 3 12 | -------------------------------------------------------------------------------- /pytest/test_yield_fixture.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.yield_fixture() 5 | def setup(): 6 | print('----start----') 7 | yield 8 | print('----end----') 9 | 10 | 11 | def test_pass(setup): 12 | print('pass method') 13 | 14 | 15 | def test_fail(setup): 16 | print('fail method') 17 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # python-dumps 2 | > Exercise yourself with basic Python snippets 3 | 4 | | Exercise | Status | Exercise | Status | Exercise | Status | Exercise | Status | 5 | | -------------- | --------- | -------------- | --------- | -------------- | --------- | -------------- | --------- | 6 | | [Variables](https://github.com/prashanth-sams/python-dumps/tree/master/variables) | :white_check_mark: | [Functions](https://github.com/prashanth-sams/python-dumps/tree/master/functions) | :white_check_mark: | Dictionary | :white_check_mark: | [Pytest](https://github.com/prashanth-sams/python-dumps/tree/master/pytest) | :white_check_mark: | 7 | | Strings | :white_check_mark: | [Arrays](https://github.com/prashanth-sams/python-dumps/tree/master/arrays) | :white_check_mark: | [Inheritance](https://github.com/prashanth-sams/python-dumps/tree/master/inheritance) | :white_check_mark: | [Abstraction](https://github.com/prashanth-sams/python-dumps/tree/master/abstraction) | :white_check_mark: | 8 | | Numbers | :white_check_mark: | Sets | :white_check_mark: | [Iterators](https://github.com/prashanth-sams/python-dumps/tree/master/iterators) | :white_check_mark: | [Lambda](https://github.com/prashanth-sams/python-dumps/tree/master/lambda) | :white_check_mark: | 9 | | Boolean | :white_check_mark: | Tuple | :white_check_mark: | [Generators](https://github.com/prashanth-sams/python-dumps/tree/master/yield%20generator) | :white_check_mark: | [Projects](https://github.com/prashanth-sams/python-dumps/tree/master/projects) | :white_check_mark: | 10 | | [Loops](https://github.com/prashanth-sams/python-dumps/tree/master/loop) | :white_check_mark: | If else | :white_check_mark: | Operators | :white_check_mark: | Exception | :white_check_mark: | 11 | | Datatype | :white_check_mark: | [Decorators](https://github.com/prashanth-sams/python-dumps/tree/master/decorators) | :white_check_mark: | [Closure](https://github.com/prashanth-sams/python-dumps/tree/master/closure) | :white_check_mark: | [Built-ins](https://github.com/prashanth-sams/python-dumps/tree/master/builtins) | :white_check_mark: | 12 | | Methods | :white_check_mark: | Best Practices | :white_check_mark: | Data structures | :white_check_mark: | 13 | -------------------------------------------------------------------------------- /variables/lesson.py: -------------------------------------------------------------------------------- 1 | # assign multi variables in single statement 2 | value1, value2 = 5, 7 3 | print(value1 + value2) 4 | 5 | # concatenate string and a number 6 | Value3, Name3 = 3, "Prashanth" 7 | print(str(Value3) + ": " + Name3) 8 | 9 | # assign a value for two variable names 10 | Value4 = Value5 = 10 11 | print(Value4 + Value5) 12 | 13 | # legal variables 14 | myvar = "John" 15 | my_var = "John" 16 | _my_var = "John" 17 | myVar = "John" 18 | MYVAR = "John" 19 | myvar2 = "John" -------------------------------------------------------------------------------- /variables/lesson2.py: -------------------------------------------------------------------------------- 1 | x = 30 2 | 3 | def age(): 4 | x = 31 5 | print(f'my age is {x}') 6 | 7 | 8 | age() 9 | print(f'my age is {x}') 10 | -------------------------------------------------------------------------------- /variables/lesson3.py: -------------------------------------------------------------------------------- 1 | def age(): 2 | global x 3 | x = 30 4 | print(f'my age is {x}') 5 | 6 | 7 | age() 8 | print(f'my age is {x}') 9 | -------------------------------------------------------------------------------- /variables/lesson4.py: -------------------------------------------------------------------------------- 1 | x = 30 2 | 3 | def age(): 4 | global x 5 | x = 31 6 | print(f'my age is {x}') 7 | 8 | 9 | age() 10 | print(f'my age is {x}') 11 | -------------------------------------------------------------------------------- /yield generator/lesson.py: -------------------------------------------------------------------------------- 1 | # k = ['cars', 'bikes', 'motors', 'cycle'] 2 | # l = [] 3 | # 4 | # def return_func(): 5 | # for i in k: 6 | # l.append(i) 7 | # 8 | # return l 9 | # 10 | # print(return_func()) 11 | 12 | k = ['cars', 'bikes', 'motors', 'cycle'] 13 | 14 | def yield_func(): 15 | for i in k: 16 | yield i 17 | 18 | 19 | print(list(yield_func())) -------------------------------------------------------------------------------- /yield generator/lesson2.py: -------------------------------------------------------------------------------- 1 | k = ['cars', 'bikes', 'motors', 'cycle'] 2 | 3 | 4 | # type #1 5 | def yield_func(): 6 | for i in k: 7 | yield i 8 | 9 | 10 | result = yield_func() 11 | print(next(result)) 12 | print(next(result)) 13 | print(next(result)) 14 | print(next(result)) 15 | 16 | 17 | # type #2 18 | def yield_func2(): 19 | for i in k: 20 | yield i 21 | 22 | 23 | result = yield_func2() 24 | for i in result: 25 | print(i) 26 | --------------------------------------------------------------------------------