├── requirements.txt ├── src ├── classes │ ├── __str__.py │ ├── methods.py │ ├── pass-statement.py │ ├── self-parameter.py │ ├── delete-object-properties.py │ ├── simple-object.py │ ├── simple_class.py │ ├── change_object_properties.py │ ├── init-example.py │ └── classes_readme.md ├── data_types │ ├── __init__.py │ ├── linear │ │ ├── array │ │ │ └── array.py │ │ ├── tuple │ │ │ └── basics.py │ │ └── list │ │ │ └── basics.py │ ├── numeric │ │ ├── complex │ │ │ └── basics.py │ │ ├── float │ │ │ ├── commonUtils.py │ │ │ ├── testUtils.py │ │ │ └── iteration.py │ │ └── integer │ │ │ └── iterations.py │ ├── non_linear │ │ ├── set │ │ │ └── basics.py │ │ └── dictionaries │ │ │ ├── collision.py │ │ │ └── basics.py │ ├── binary │ │ ├── memoryview │ │ │ └── basics.py │ │ ├── bytes │ │ │ └── basics.py │ │ └── bytearray │ │ │ └── basics.py │ ├── string │ │ ├── iterations.py │ │ └── slicing.py │ ├── boolean │ │ └── basics.py │ └── commonUtils.py ├── math │ ├── calculations │ │ ├── divide.py │ │ ├── number-system.py │ │ └── multiply.py │ ├── number-systems │ │ ├── problems.py │ │ ├── binary_to_decimal.py │ │ ├── decimal_to_octal.py │ │ ├── octal_to_decimal.py │ │ ├── decimal_to_binary.py │ │ ├── decimal_to_hexadecimal.py │ │ ├── hexadecimal_to_decimal.py │ │ ├── decimal_to_roman.py │ │ ├── binary_to_hexadecimal.py │ │ └── roman_to_decimal.py │ ├── fibonacci.py │ └── NumberSystem.md ├── data_structures │ ├── linked_list │ │ ├── double-linked-list.py │ │ ├── circular-linked-list.py │ │ ├── commonUtils.py │ │ ├── ReadMe.md │ │ ├── testUtils.py │ │ └── linked-list.py │ ├── tree │ │ ├── binary-tree │ │ │ ├── traversal.py │ │ │ ├── find-maximum-depth.py │ │ │ └── binary-tree.py │ │ ├── ReadME.md │ │ ├── binary-search-tree │ │ │ └── binary-tree-vs-binary-search-tree.md │ │ └── general │ │ │ └── simple-tree.py │ ├── array │ │ └── ReadMe.md │ ├── stack │ │ └── ReadMe.md │ ├── queue │ │ ├── ReadMe.md │ │ ├── queue_collections_deque.py │ │ ├── queue_list.py │ │ ├── basics_queue.py │ │ ├── queue_lifo.py │ │ ├── circular.py │ │ └── queue_priority.py │ ├── heap │ │ └── ReadMe.md │ ├── graph │ │ └── ReadMe.md │ ├── priority_queue │ │ └── priority_queue_readme.md │ └── ReadMe.md ├── basics │ ├── g_modules.py │ ├── j_sequence_data_types.py │ ├── g_boolean.py │ ├── boolean.md │ ├── f_numbers.py │ ├── operators.md │ ├── numbers.md │ ├── h_operators.py │ ├── range.md │ ├── c_if.py │ ├── i_range.py │ ├── errors.py │ ├── if.md │ ├── rough.py │ ├── error.md │ ├── b_variable_scope.py │ ├── d_data_types.py │ ├── variable_scope.md │ ├── a_basics.py │ ├── variables.md │ ├── data_types.md │ ├── strings.md │ ├── basics.md │ └── b_variables.py ├── recursive │ ├── recursive_error.py │ └── stack_frames.py ├── functions │ ├── simple_function.py │ └── lambda.py ├── defs │ ├── commonUtils.py │ ├── print-even-numbers.py │ ├── print_even_sequence.py │ ├── split.py │ ├── count_pair_for_max.py │ ├── testUtils.py │ └── print_all_primes.py ├── problems │ ├── string_length.py │ ├── number_length.py │ ├── testUtils.py │ ├── palindrome.py │ └── fibonacci.py ├── bits │ ├── 1_to_3_bits.md │ ├── 1_to_3_bits.py │ ├── 4_and_8_bits.md │ ├── 4_and_8_bits.py │ ├── basics.py │ ├── 16_and_32_bits.md │ ├── 16_and_32_bits.py │ ├── 64_and_128_bits.md │ ├── 64_and_128_bits.py │ ├── data_type_bit_sizes.md │ └── data_types_bits.py ├── leetcode │ ├── palindrome_remove_one_char.py │ ├── two_sum.py │ ├── palindrome.py │ ├── palindrome_number.py │ ├── __template__.py │ ├── first_unique_character.py │ ├── 680_valid_palindrom_II_remove_one_char.py │ ├── arrays │ │ └── 283_move_zeroes_easy.py │ ├── valid_number.py │ ├── add_strings.py │ └── strings │ │ └── 67_Add_Binary.py ├── sorting │ └── quick_sort.py ├── Inheritance │ ├── simple_inheritance.py │ └── inheritance_readme.md ├── operators │ └── bit_wise │ │ └── shift_left │ │ └── basics.py ├── utilities │ ├── testUtils.py │ └── commonUtils.py ├── algorithms │ └── search │ │ └── binary_search.py ├── interview │ ├── find_sum_of_integer_array.py │ └── string_substitute.py └── controls │ └── if.py ├── .github ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── docs.yml ├── python-one-pic.jpeg ├── .vscode ├── settings.json ├── extensions.json └── tasks.json ├── git_hub _commands ├── LocalSetup.md ├── module.py ├── .tours └── 10-interesting-things-in-strings-to-remember.tour ├── mkdocs.yml ├── __complexities └── big-o-notations.md ├── README.md └── .gitignore /requirements.txt: -------------------------------------------------------------------------------- 1 | stylepy -------------------------------------------------------------------------------- /src/classes/__str__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/classes/methods.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_types/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/classes/pass-statement.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/classes/self-parameter.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/math/calculations/divide.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_types/linear/array/array.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/math/calculations/number-system.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/classes/delete-object-properties.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_structures/linked_list/double-linked-list.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_structures/tree/binary-tree/traversal.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_structures/linked_list/circular-linked-list.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_structures/tree/binary-tree/find-maximum-depth.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/data_types/numeric/complex/basics.py: -------------------------------------------------------------------------------- 1 | print('\n >>>> Complex Number Example') -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## What has changed? 2 | 1. Answer 3 | 1. Answer 4 | -------------------------------------------------------------------------------- /python-one-pic.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L3-Squad/python-basics/HEAD/python-one-pic.jpeg -------------------------------------------------------------------------------- /src/basics/g_modules.py: -------------------------------------------------------------------------------- 1 | import random 2 | from stylepy import h2 3 | h2(random.randrange(1, 10)) -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | "editor.insertSpaces": true, 4 | "editor.detectIndentation": false 5 | } 6 | -------------------------------------------------------------------------------- /git_hub _commands: -------------------------------------------------------------------------------- 1 | git config user.name "Jassu007" 2 | git config user.email "your-email@example.com" 3 | 4 | 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 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/recursive/recursive_error.py: -------------------------------------------------------------------------------- 1 | from stylepy import h4 2 | call_count = 0 3 | 4 | def greet(): 5 | global call_count 6 | call_count += 1 7 | h4(call_count,'. hello buddy!') 8 | greet() 9 | 10 | greet() -------------------------------------------------------------------------------- /src/data_types/non_linear/set/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/non_linear/set/basics.py 2 | # python -m data_types.non_linear.set.basics data_types/set/basics.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Set Basics') 7 | -------------------------------------------------------------------------------- /src/math/number-systems/problems.py: -------------------------------------------------------------------------------- 1 | # binary to deciamal 2 | # decimal to binary 3 | # hexadecimal to deciamal 4 | # decimal to hexadecimal 5 | # octal to decimal 6 | # decimal to octal 7 | # binary to hexadecimal 8 | # decimal to roman 9 | # roman to decimal -------------------------------------------------------------------------------- /src/data_structures/array/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Array Time Complexity Table 2 | 3 | | Operation | Array | 4 | |-----------------|--------| 5 | | Access | O(1) | 6 | | Search | O(n) | 7 | | Insert | O(n) | 8 | | Delete | O(n) | 9 | -------------------------------------------------------------------------------- /src/data_structures/stack/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Stack Time Complexity Table 2 | 3 | | Operation | Stack | 4 | |---------------|-------| 5 | | Access | O(n) | 6 | | Search | O(n) | 7 | | Insert (Push) | O(1) | 8 | | Delete (Pop) | O(1) | 9 | | Peek | O(1) | 10 | -------------------------------------------------------------------------------- /src/data_structures/queue/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Queue Time Complexity Table 2 | 3 | | Operation | Queue | 4 | |-----------------|-------| 5 | | Access | O(n) | 6 | | Search | O(n) | 7 | | Insert (Enqueue)| O(1) | 8 | | Delete (Dequeue)| O(1) | 9 | | Peek | O(1) | 10 | -------------------------------------------------------------------------------- /src/data_types/binary/memoryview/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/binary/memoryview/basics.py 2 | # python -m data_types.binary.memoryview data_types/binary/memoryview/basics.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Memory View Basics') 7 | 8 | utils.print_blockquote([]) -------------------------------------------------------------------------------- /src/data_structures/heap/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Data Structures Types. 2 | 3 | ## Heap Non Linear Type 4 | 5 | | Heap Type | Insert | Delete | Find Max/Min | 6 | |-----------------|-----------|-----------|--------------| 7 | | Binary Heap | O(log n) | O(log n) | O(1) | 8 | | Fibonacci Heap | O(1)* | O(log n)* | O(1) | 9 | -------------------------------------------------------------------------------- /src/basics/j_sequence_data_types.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('\n >>>> Sequence Data Type Example') 4 | 5 | h2('\n >>>> List Data Type Example') 6 | h3(' >>> Create N number of List element with same value') 7 | h4([7] * 4); 8 | 9 | h3('\n >>>> Tuple Data Type Example') 10 | h4((1,2) * 4); 11 | 12 | h5('\n >>>> Complex Data Type Example') -------------------------------------------------------------------------------- /src/data_types/string/iterations.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3 2 | h1('\n >>>> String Iteration Example') 3 | 4 | greet = 'welcome' 5 | 6 | h3('\n >>>> Iterate using for loop') 7 | for word in greet: 8 | print(word) 9 | 10 | h3('\n >>>> Iterate using while loop') 11 | index = 0 12 | while index < len(greet): 13 | print(greet[index]) 14 | index += 1 15 | -------------------------------------------------------------------------------- /src/data_structures/tree/ReadME.md: -------------------------------------------------------------------------------- 1 | # Data Structures Types. 2 | 3 | ## Tree Non Linear Type 4 | 5 | | Tree Type | Insert | Delete | Traversal | 6 | |----------------|-----------|-----------|-----------| 7 | | Binary Tree | O(n) | O(n) | O(n) | 8 | | AVL Tree | O(log n) | O(log n) | O(n) | 9 | | Red-Black Tree | O(log n) | O(log n) | O(n) | 10 | -------------------------------------------------------------------------------- /src/data_structures/tree/binary-tree/binary-tree.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1 2 | h1('\n >>> Binary Tree Implementation') 3 | print('- each node has at most two children') 4 | print('- referred to as the left child and the right child.') 5 | print('- no specific ordering in terms of how nodes are arranged.') 6 | print(' A') 7 | print(' / \\') 8 | print(' B C') 9 | print(' / / \\') 10 | print('D E F') 11 | -------------------------------------------------------------------------------- /src/classes/simple-object.py: -------------------------------------------------------------------------------- 1 | # import simple_class as sc 2 | from simple_class import Bus, Fruit, WashingMachine 3 | 4 | bus = Bus() 5 | print(f"Bus Model is {bus.model}") 6 | 7 | fruit = Fruit() 8 | print(f"Fruit name : {fruit.name}, color: {fruit.color} ") 9 | 10 | wash_machine = WashingMachine() 11 | 12 | wash_machine.wash_clothes() 13 | print(f"Washing Machine name : {wash_machine.brand}, color: {wash_machine.model} ") 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/math/number-systems/binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | def binary_to_decimal(binary): 2 | decimal = 0 3 | power = 0 4 | for digit in reversed(binary): # Process digits from right to left 5 | decimal += int(digit) * (2 ** power) 6 | power += 1 7 | return decimal 8 | 9 | 10 | binary=input("Enter the binary:") # For example: 1011 11 | decimal = binary_to_decimal(binary) 12 | print(f"The decimal equivalent of binary {binary} is {decimal}") -------------------------------------------------------------------------------- /src/math/number-systems/decimal_to_octal.py: -------------------------------------------------------------------------------- 1 | def decimal_to_octal(decimal): 2 | octal = "" 3 | while decimal > 0: 4 | remainder = decimal % 8 5 | octal = str(remainder) + octal 6 | decimal //= 8 7 | return octal 8 | 9 | 10 | decimal_number = int(input("Enter the decimal number: ")) # for example 26 11 | octal_number = decimal_to_octal(decimal_number) 12 | print(f"The octal equivalent of decimal {decimal_number} is {octal_number}.") -------------------------------------------------------------------------------- /src/math/number-systems/octal_to_decimal.py: -------------------------------------------------------------------------------- 1 | def octal_to_decimal(octal): 2 | decimal = 0 3 | power = 0 4 | for digit in reversed(octal): 5 | decimal += int(digit) * (8 ** power) 6 | power += 1 7 | return decimal 8 | 9 | 10 | octal_number = input("Enter the octal number: ") # For example: 56 11 | decimal_number = octal_to_decimal(octal_number) 12 | print(f"The decimal equivalent of octal {octal_number} is {decimal_number}.") 13 | -------------------------------------------------------------------------------- /src/data_types/binary/bytes/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/binary/bytes/basics.py 2 | # python -m data_types.binary.bytes data_types/binary/bytes/basics.py 3 | import sys 4 | import os 5 | 6 | # Add the parent directory of 'data_types' to the system path 7 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) 8 | 9 | import data_types.commonUtils as utils 10 | 11 | utils.print_h1('Byte Basics') 12 | 13 | utils.print_blockquote([]) -------------------------------------------------------------------------------- /src/functions/simple_function.py: -------------------------------------------------------------------------------- 1 | 2 | from stylepy import h4 3 | def returning_one(): 4 | return 1 5 | 6 | def returning_one_with_comma(): 7 | return 1, 8 | 9 | def returning_one_two_three(): 10 | return 1,2,3 11 | 12 | h4(type(returning_one()), 'returning_one: ', returning_one()) 13 | h4(type(returning_one_with_comma()), 'returning_one_with_comma: ', returning_one_with_comma()) 14 | h4(type(returning_one_two_three()), 'returning_one_two_three: ', returning_one_two_three()) -------------------------------------------------------------------------------- /src/math/number-systems/decimal_to_binary.py: -------------------------------------------------------------------------------- 1 | def decimal_to_binary(decimal): 2 | binary = "" 3 | while decimal > 0: 4 | remainder = decimal % 2 5 | binary = str(remainder) + binary 6 | decimal //= 2 7 | return binary 8 | 9 | 10 | decimal_number = int(input("Enter the decimal number: ")) # for example : 10 11 | 12 | binary_number = decimal_to_binary(decimal_number) 13 | 14 | print(f"The binary equivalent of decimal {decimal_number} is {binary_number}.") 15 | -------------------------------------------------------------------------------- /src/data_types/binary/bytearray/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/binary/bytearray/basics.py 2 | # python -m data_types.binary.bytearray data_types/binary/bytearray/basics.py 3 | import sys 4 | import os 5 | 6 | # Add the parent directory of 'data_types' to the system path 7 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) 8 | 9 | from data_types import commonUtils as utils 10 | 11 | utils.print_h1('Byte Array Basics') 12 | 13 | utils.print_blockquote([]) -------------------------------------------------------------------------------- /src/math/number-systems/decimal_to_hexadecimal.py: -------------------------------------------------------------------------------- 1 | def decimal_to_hexadecimal(decimal): 2 | hex_digits = "0123456789ABCDEF" 3 | hexadecimal = "" 4 | while decimal > 0: 5 | remainder = decimal % 16 6 | hexadecimal = hex_digits[remainder] + hexadecimal 7 | decimal //= 16 8 | return hexadecimal 9 | 10 | decimal_number = int(input("Enter the number: ")) # For example: 76 11 | hexadecimal_number = decimal_to_hexadecimal(decimal_number) 12 | print(f"The hexadecimal equivalent of decimal {decimal_number} is {hexadecimal_number}.") 13 | -------------------------------------------------------------------------------- /src/math/number-systems/hexadecimal_to_decimal.py: -------------------------------------------------------------------------------- 1 | def hexadecimal_to_decimal(hexadecimal): 2 | hex_digits = "0123456789ABCDEF" 3 | decimal = 0 4 | power = 0 5 | for digit in reversed(hexadecimal.upper()): 6 | decimal += hex_digits.index(digit) * (16 ** power) 7 | power += 1 8 | return decimal 9 | 10 | 11 | hexadecimal_number=input("Enter the hexadecimal_number:") # For example: 1A 12 | decimal_number = hexadecimal_to_decimal(hexadecimal_number) 13 | print(f"The decimal equivalent of hexadecimal {hexadecimal_number} is {decimal_number}.") 14 | -------------------------------------------------------------------------------- /src/data_types/numeric/float/commonUtils.py: -------------------------------------------------------------------------------- 1 | from stylepy import timeComplexity 2 | from stylepy import spaceComplexity 3 | def timeComplexity(value, desc): 4 | result = f'\n 🕒 Time Complexity: Approximately {value}' 5 | 6 | if (desc): 7 | result += f'\n Description: {desc}' 8 | print(result) 9 | timeComplexity("value", "desc") 10 | def spaceComplexity(value, desc): 11 | result = f' 💾 Space Complexity: Approximately {value}' 12 | 13 | if (desc): 14 | result += f'\n Description: {desc}' 15 | print(result) 16 | spaceComplexity("value", "desc") -------------------------------------------------------------------------------- /src/data_structures/graph/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Data Structures Types. 2 | 3 | ## Graph Non Linear Type 4 | 5 | | Graph Type | Add Vertex | Remove Vertex | Add Edge | Remove Edge | Search | Path Finding | 6 | |----------------|------------|---------------|----------|-------------|--------|--------------| 7 | | Directed Graph | O(1) | O(V + E) | O(1) | O(E) | O(V+E) | O(V + E) | 8 | | Undirected Graph| O(1) | O(V + E) | O(1) | O(E) | O(V+E) | O(V + E) | 9 | | Weighted Graph | O(1) | O(V + E) | O(1) | O(E) | O(V+E) | O(V + E) | 10 | -------------------------------------------------------------------------------- /src/defs/commonUtils.py: -------------------------------------------------------------------------------- 1 | from stylepy import timeComplexity 2 | from stylepy import spaceComplexity 3 | from stylepy import h1,h2,h3,h4,h5,h5,h6 4 | def timeComplexity(value, desc): 5 | result = f'\n 🕒 Time Complexity: Approximately {value}' 6 | 7 | if (desc): 8 | result += f'\n Description: {desc}' 9 | h4(result) 10 | timeComplexity("value","desc") 11 | def spaceComplexity(value, desc): 12 | result = f' 💾 Space Complexity: Approximately {value}' 13 | 14 | if (desc): 15 | result += f'\n Description: {desc}' 16 | h4(result) 17 | spaceComplexity("value","desc") -------------------------------------------------------------------------------- /src/data_structures/linked_list/commonUtils.py: -------------------------------------------------------------------------------- 1 | from stylepy import timeComplexity 2 | from stylepy import spaceComplexity 3 | from stylepy import h1,h2,h3,h4,h5,h6 4 | def timeComplexity(value, desc): 5 | result = f'\n 🕒 Time Complexity: Approximately {value}' 6 | 7 | if (desc): 8 | result += f'\n Description: {desc}' 9 | h3(result) 10 | timeComplexity("value","desc") 11 | def spaceComplexity(value, desc): 12 | result = f' 💾 Space Complexity: Approximately {value}' 13 | 14 | if (desc): 15 | result += f'\n Description: {desc}' 16 | h3(result) 17 | spaceComplexity("value","desc") -------------------------------------------------------------------------------- /LocalSetup.md: -------------------------------------------------------------------------------- 1 | ## Local Setup 2 | 3 | ### Create a virtual environment: 4 | 5 | ``` 6 | python -m venv venv 7 | ``` 8 | 9 | ### Activate 10 | 11 | > Windows 12 | 13 | 14 | ``` 15 | source venv/scripts/activate 16 | ``` 17 | 18 | > MacOS 19 | 20 | ``` 21 | source venv/bin/activate 22 | ``` 23 | 24 | ### Deactivate 25 | 26 | > Windows and Mac 27 | 28 | ``` 29 | deactivate 30 | ``` 31 | 32 | ## Local Setup 33 | 34 | ``` 35 | python -m pip install --upgrade pip 36 | pip install stylepy mkdocs mkdocs-material mkdocs-gen-nav-plugin mkdocs-awesome-pages-plugin pymdown-extensions mkdocstrings 37 | chmod +x ./generate_docs.sh 38 | ./generate_docs.sh 39 | mkdocs serve 40 | ``` -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-python.python", // Python extension (Linting, Debugging, IntelliSense, etc.) 4 | "ms-toolsai.jupyter", // Jupyter Notebooks support 5 | "ms-vscode.cpptools", // C/C++ extension (useful if you are using Python with C/C++ bindings) 6 | "VisualStudioExptTeam.vscodeintellicode", // AI-assisted IntelliSense 7 | "njpwerner.autodocstring", // Auto-generates Python docstrings 8 | "ms-azuretools.vscode-docker", // Docker support (useful for containerized applications) 9 | "formulahendry.code-runner", // Run code snippet or code file 10 | "github.vscode-pull-request-github" // Review and manage GitHub pull requests and issues 11 | ] 12 | } -------------------------------------------------------------------------------- /src/recursive/stack_frames.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import inspect 3 | 4 | # Set the recursion limit to a lower value for demonstration 5 | sys.setrecursionlimit(30) 6 | 7 | def print_stack_frames(): 8 | # Iterate over the stack frames 9 | for frame_info in inspect.stack(): 10 | frame = frame_info.frame # Get the frame object 11 | print(f"Frame: {frame.f_lineno} line - {frame.f_code.co_name}") # Print information about each frame 12 | 13 | def greet(count=0): 14 | if count < 5: # Limiting recursion depth for demonstration 15 | print(f"Recursion count: {count}") 16 | print_stack_frames() 17 | print("----------------------") 18 | greet(count + 1) 19 | 20 | greet() 21 | -------------------------------------------------------------------------------- /src/classes/simple_class.py: -------------------------------------------------------------------------------- 1 | # Blue prints or skelentons for entities 2 | # Python keyword for the class is "class" 3 | from stylepy import h1,h2,h3 4 | class Fruit: 5 | name = "Apple" 6 | color = "red" 7 | 8 | class WashingMachine: 9 | color = "white" 10 | model = "1A" 11 | brand = "IFB" 12 | capacity = 7 13 | price = 999.0 14 | water_consumption = 2.5 15 | 16 | def wash_clothes(self): 17 | h3("washing initiated") 18 | 19 | class Bus: 20 | length=0 21 | brand = "Volvo" 22 | model = "V9" 23 | capacity = 50 24 | fuel_type = "Diesel" 25 | price = 250000 26 | 27 | def get_length(): 28 | return Bus.length 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/basics/g_boolean.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('\n >>>> Boolean Data Type Example') 4 | h2('\n >>> When boolean returns `False`') 5 | 6 | h5('For False ', bool(False)); 7 | h6('For Zero ', bool(0)); 8 | h5('For Empty String ', bool('')); 9 | h6('For Empty List ', bool([])); 10 | h6('For Empty Tuple ', bool(())); 11 | h5('For Empty Dictionary ', bool({})); 12 | h6('For None ', bool(None)); 13 | 14 | h3('\n >>> When boolean returns `True`') 15 | h5('For greater than Zero ', bool(1)); 16 | h6('For atleast one String ', bool('a')); 17 | h5('For atleast one item in List ', bool(['a'])); 18 | h6('For atleast one item in Tuple ', bool(('a'))); 19 | h5('For atleast one item in Dictionary ', bool({'a': 'A'})); -------------------------------------------------------------------------------- /src/problems/string_length.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3 2 | from testUtils import print_and_assert, getTestResult 3 | 4 | h1('\n >>> String Length Example without using len() def') 5 | h2(' >>> string_length()') 6 | def string_length(text): 7 | count = 0; 8 | for character in text: 9 | count += 1 10 | return count; 11 | 12 | h3('\n >>> String Length Test Cases') 13 | print_and_assert(string_length, 'Venkat', 6) 14 | print_and_assert(string_length, 'R.Venkat', 8) 15 | print_and_assert(string_length, 'Python', 6) 16 | print_and_assert(string_length, 'Full Stack Development', 10) 17 | print_and_assert(string_length, '734250', 6) 18 | print_and_assert(string_length, '52734250', 9); 19 | 20 | getTestResult('String Length') -------------------------------------------------------------------------------- /src/defs/print-even-numbers.py: -------------------------------------------------------------------------------- 1 | from testUtils import print_and_assert, getTestResult 2 | from stylepy import h1 3 | def print_event_numbers(number_list): 4 | even_numbers = [] 5 | for number in number_list: 6 | if (number % 2 == 0): 7 | even_numbers.append(number) 8 | return even_numbers 9 | 10 | h1('\n >>> Print Event Numbers List Test Cases') 11 | print_and_assert(print_event_numbers, [1,2,3,4,5,6], [2,4,6]) 12 | print_and_assert(print_event_numbers, [0], [0]) 13 | print_and_assert(print_event_numbers, [], []) 14 | print_and_assert(print_event_numbers, [], []) 15 | print_and_assert(print_event_numbers, [], []) 16 | print_and_assert(print_event_numbers, [], []) 17 | 18 | getTestResult('Print Event Numbers List') -------------------------------------------------------------------------------- /src/defs/print_even_sequence.py: -------------------------------------------------------------------------------- 1 | from stylepy import h3,h2,h4 2 | def print_even_sequence(array): 3 | for a in array: 4 | if a % 2 == 0: 5 | print("\nSequence for {0}".format(a)) 6 | for k in range(0,a): 7 | print(k, end=" ") 8 | 9 | print_even_sequence([10, 22, 33, 44, 55, 66, 77]) 10 | h2('\n Here O(a * k) , where a = size of array and k is largest even') 11 | 12 | h3('\n\n 🕒 Time Complexity: Approximately O(n × m) \n In the worst case, where n is the length of the array and m is the average size of the even numbers. However, the actual time complexity can vary significantly based on the contents of the input array.') 13 | h3('\n 💾 Space Complexity: O(1) \n As it only uses a constant amount of additional memory.') -------------------------------------------------------------------------------- /src/basics/boolean.md: -------------------------------------------------------------------------------- 1 | 2 | # Boolean Data Type Examples 3 | 4 | ## Boolean Data Type Example 5 | 6 | ### When Boolean Returns `False` 7 | 8 | - **For `False`:** `bool(False)` 9 | - **For Zero:** `bool(0)` 10 | - **For Empty String:** `bool('')` 11 | - **For Empty List:** `bool([])` 12 | - **For Empty Tuple:** `bool(())` 13 | - **For Empty Dictionary:** `bool({})` 14 | - **For None:** `bool(None)` 15 | 16 | --- 17 | 18 | ### When Boolean Returns `True` 19 | 20 | - **For greater than Zero:** `bool(1)` 21 | - **For at least one String:** `bool('a')` 22 | - **For at least one item in List:** `bool(['a'])` 23 | - **For at least one item in Tuple:** `bool(('a'))` 24 | - **For at least one item in Dictionary:** `bool({'a': 'A'})` 25 | -------------------------------------------------------------------------------- /src/defs/split.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h4,h2,h3 2 | h1('\n >>>> Split String Example'); 3 | 4 | original = "Hello, World!" 5 | target = original.split(",") 6 | h3("Using Native Split function: ", target) 7 | 8 | # Faced `TabError: inconsistent use of tabs and spaces in indentation` 9 | 10 | def splitString(text, sepearator): 11 | word = '' 12 | splitted_list = [] 13 | 14 | for char in text: 15 | if char == sepearator: 16 | splitted_list.append(word) 17 | word = '' 18 | else: 19 | word += char 20 | 21 | if word != '': 22 | splitted_list.append(word) 23 | 24 | return splitted_list 25 | 26 | h4('Using Custom function: ', splitString(original, ',')) 27 | h4('Custom Def Time and Space Complexity is O(n)') -------------------------------------------------------------------------------- /src/bits/1_to_3_bits.md: -------------------------------------------------------------------------------- 1 | # 1, 2 and 3 Bit Basics 2 | 3 | ## 1 Bit 4 | ###### 5 | | Decimal | Binary | 6 | |---------|--------| 7 | | 0 | 0 | 8 | | 1 | 1 | 9 | 10 | ## 2 Bit 11 | #### 12 | | Decimal | Binary | 13 | |---------|--------| 14 | | 0 | 00 | 15 | | 1 | 01 | 16 | | 2 | 10 | 17 | | 3 | 11 | 18 | 19 | ## 3 Bit 20 | #### 21 | In the 3-bit table, only decimal numbers up to 7 are included, as the binary representation of 8 (1000) requires 4 bits. 22 | 23 | #### 24 | | Decimal | Binary | 25 | |---------|--------| 26 | | 0 | 000 | 27 | | 1 | 001 | 28 | | 2 | 010 | 29 | | 3 | 011 | 30 | | 4 | 100 | 31 | | 5 | 101 | 32 | | 6 | 110 | 33 | | 7 | 111 | 34 | 35 | -------------------------------------------------------------------------------- /src/problems/number_length.py: -------------------------------------------------------------------------------- 1 | from testUtils import print_and_assert, getTestResult 2 | from stylepy import h1,h2,h3,h4 3 | h2('\n >>> Number Length Example without using len() def') 4 | h3(' >>> number_length(0)') 5 | 6 | def number_length(number): 7 | if number == 0: 8 | return 1 9 | count = 0 10 | 11 | while number: 12 | number //= 10 13 | count += 1 14 | 15 | return count; 16 | 17 | print('\n >>> Number Length Test Cases') 18 | print_and_assert(number_length, 0, 2) 19 | print_and_assert(number_length, 25, 2) 20 | print_and_assert(number_length, 725, 3) 21 | print_and_assert(number_length, 4325, 4) 22 | print_and_assert(number_length, 734250, 6) 23 | print_and_assert(number_length, 52734250, 8) 24 | 25 | getTestResult('Number Length') 26 | -------------------------------------------------------------------------------- /src/classes/change_object_properties.py: -------------------------------------------------------------------------------- 1 | import simple_class as sc 2 | from stylepy import h1, h2, h3, h4, h5, h6 3 | 4 | # Without creating an object or instance we cannot work/use the class 5 | # An object is a memory it has all the features and functions that defined in the class 6 | 7 | # create an object 8 | def get_length1(bus): 9 | return bus.length 10 | 11 | bus = sc.Bus() 12 | h1(f"Bus length : {bus.length}") 13 | bus.length = 10 14 | bus.get_length = get_length1 15 | h2(f"Bus length : {bus.length}") 16 | h3(f"bus length is : {bus.get_length(bus)}") 17 | bus.additional_param = 9 18 | 19 | # we can assign and change the properties from out side but it is a bad design 20 | 21 | 22 | h4(f" bus additional param : {bus.additional_param}") 23 | 24 | apple = sc.Fruit() 25 | 26 | washing_machine = sc.WashingMachine() -------------------------------------------------------------------------------- /module.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import subprocess 3 | import os 4 | 5 | def run_python_file(file_path): 6 | # Convert file path to module path 7 | module_path = file_path.replace('/', '.').replace('\\', '.') 8 | module_path = os.path.splitext(module_path)[0] # Remove file extension 9 | 10 | command = [sys.executable, "-m", module_path] 11 | 12 | print("Executing command:", ' '.join(command)) 13 | 14 | # Run as module 15 | try: 16 | subprocess.run(command, check=True) 17 | except subprocess.CalledProcessError as e: 18 | print(f"Error running module {module_path}: {e}") 19 | 20 | if __name__ == "__main__": 21 | if len(sys.argv) != 2: 22 | print("Usage: python runfile.py ") 23 | sys.exit(1) 24 | 25 | file_path = sys.argv[1] 26 | run_python_file(file_path) 27 | -------------------------------------------------------------------------------- /src/data_types/linear/tuple/basics.py: -------------------------------------------------------------------------------- 1 | # python -m data_types.commonUtils data_types/tuples/basics.py 2 | # python -m data_types.tuples.basics data_types/tuples/basics.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Tuple Basics') 7 | utils.print_ordered_list([ 8 | 'Tuple is Ordered (order will not be changed)', 9 | 'Tuple is Immutable', 10 | 'Convert to List for Mutation (Changing / Removing)' 11 | ]) 12 | 13 | 14 | fruits = ('apple','banana', 'guava') 15 | subjects = ('english', 'science', 'maths', 'scoial') 16 | daily_cycle = ('morning', 'afternoon', 'dinner') 17 | exam_result = ('english', 80) 18 | 19 | 20 | fruit_list = list(fruits) 21 | 22 | fruits_subjects = fruits + subjects 23 | print(fruits_subjects) 24 | 25 | ''' 26 | convert to the list 27 | [].(fruits) 28 | need to check whether order in place 29 | ''' -------------------------------------------------------------------------------- /src/leetcode/palindrome_remove_one_char.py: -------------------------------------------------------------------------------- 1 | 2 | def valid_palindrome(s): 3 | 4 | def is_valid(i, j ): 5 | while i < j: 6 | if s[i] != s[j]: 7 | return False 8 | else: 9 | i += 1 10 | j -= 1 11 | return True 12 | def remove_one_from_range(i, j ): 13 | return is_valid(i+1, j) or is_valid(i, j-1 ) 14 | 15 | left, right = 0 , len(s) -1 16 | while left < right: 17 | if s[left] != s[right]: 18 | return remove_one_from_range(left, right ) 19 | else: 20 | left += 1 21 | right -= 1 22 | return True 23 | 24 | s = 'aba' 25 | print(f" {s} is {'palindrome' if valid_palindrome(s) else 'not a palindrome'} ") 26 | s = 'abac' 27 | print(f" {s} is {'palindrome' if valid_palindrome(s) else 'not a palindrome'} ") 28 | s = 'abacd' 29 | print(f" {s} is {'palindrome' if valid_palindrome(s) else 'not a palindrome'} ") -------------------------------------------------------------------------------- /src/basics/f_numbers.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('\n >>>> Number Data Type Example') 4 | 5 | h2('\n >>>> Integer Data Type Example') 6 | age = 25 7 | h3(f'Int age ({age}) can be whole number, positive or negative, without decimals, of unlimited length.') 8 | h4('examples: 35656222554887711, -3255522, 25') 9 | 10 | h3('\n >>>> Float Data Type Example') 11 | weight = 76.50 12 | h4(f'Float weight ({weight}) can be number, positive or negative, containing one or more decimals') 13 | h5('examples: 1.10, 1.0, -35.59, 35e3, 12E4, -87.7e100') 14 | 15 | h4('\n >>>> Complex Data Type Example') 16 | something = 1j 17 | h5(f'complex something ({something}) are written with a "j" as the imaginary part') 18 | h6('examples: 1.10, 1.0, -35.59, 35e3, 12E4, -87.7e100') 19 | 20 | h5('\n >>>> Type Case Functions'); 21 | h6('examples: float(weight), int(age), complex()'); -------------------------------------------------------------------------------- /src/math/number-systems/decimal_to_roman.py: -------------------------------------------------------------------------------- 1 | def decimal_to_roman(decimal): 2 | # Define Roman numeral mappings 3 | roman_numerals = [ 4 | (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), 5 | (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), 6 | (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), 7 | (1, "I") 8 | ] 9 | 10 | roman = "" 11 | for value, numeral in roman_numerals: 12 | while decimal >= value: 13 | roman += numeral 14 | decimal -= value 15 | return roman 16 | 17 | 18 | decimal_number = int(input("Enter the decimal number: ")) # for example 2024 19 | if decimal_number > 0: 20 | roman_number = decimal_to_roman(decimal_number) 21 | print(f"The Roman numeral equivalent of decimal {decimal_number} is {roman_number}.") 22 | else: 23 | print("Please enter a positive integer.") 24 | -------------------------------------------------------------------------------- /src/leetcode/two_sum.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | import numbers 3 | 4 | def brute_force(lst, target): 5 | if type(target) != int : 6 | return 0 7 | for i in range(len(lst)): 8 | for j in range(len(lst)): 9 | if lst[i] + lst[j] == target: 10 | return [i, j ] 11 | 12 | def time_optimized(lst, target): 13 | if not isinstance(target, numbers.Number): 14 | return 0 15 | dicti = {} 16 | for index, value in enumerate(lst): 17 | dicti[value] = index 18 | 19 | h3(type(dicti), dicti) 20 | for i in range(len(lst)): 21 | complement = target - lst[i] 22 | if complement in dicti and dicti[complement] != i: 23 | return [i, dicti[complement]] 24 | 25 | h1("""Brute-force solution""") 26 | h3(f"list[2,5,7,4] and target 11 {brute_force([2,5,7,4], 11 )}") 27 | h3(f"list[2,5,7,4] and target 11 {time_optimized([2,5,7,4], 11 )}") -------------------------------------------------------------------------------- /src/bits/1_to_3_bits.py: -------------------------------------------------------------------------------- 1 | #import data_types.commonUtils as utils 2 | from stylepy import h1, h2, h3, h4, h5, h6 3 | 4 | h1('1, 2 and 3 Bit Basics') 5 | 6 | h2('1 Bit') 7 | h6(''' 8 | | Decimal | Binary | 9 | |---------|--------| 10 | | 0 | 0 | 11 | | 1 | 1 | 12 | ''') 13 | 14 | h2('2 Bit') 15 | h4(''' 16 | | Decimal | Binary | 17 | |---------|--------| 18 | | 0 | 00 | 19 | | 1 | 01 | 20 | | 2 | 10 | 21 | | 3 | 11 | 22 | ''') 23 | 24 | h2('3 Bit') 25 | h4('In the 3-bit table, only decimal numbers up to 7 are included, as the binary representation of 8 (1000) requires 4 bits.') 26 | h4(''' 27 | | Decimal | Binary | 28 | |---------|--------| 29 | | 0 | 000 | 30 | | 1 | 001 | 31 | | 2 | 010 | 32 | | 3 | 011 | 33 | | 4 | 100 | 34 | | 5 | 101 | 35 | | 6 | 110 | 36 | | 7 | 111 | 37 | ''') -------------------------------------------------------------------------------- /.tours/10-interesting-things-in-strings-to-remember.tour: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://aka.ms/codetour-schema", 3 | "title": "10 Interesting Things in Strings to Remember", 4 | "steps": [ 5 | { 6 | "file": "data_types/string/basics.py", 7 | "description": "10 Interesting Things in String to Remember", 8 | "line": 9 9 | }, 10 | { 11 | "file": "data_types/string/basics.py", 12 | "description": "There is Six ways of string concatenation in Python. Below is the Table with approach, Code and its Time and Space Complexity", 13 | "line": 19 14 | }, 15 | { 16 | "file": "data_types/string/basics.py", 17 | "description": "Below are the String Concatenation examples in Python where we have two variables, greet and name to gree the person like below.\nPattern: Hello \nExample: Hello Venkat.R", 18 | "line": 31 19 | } 20 | ], 21 | "ref": "main" 22 | } -------------------------------------------------------------------------------- /src/basics/operators.md: -------------------------------------------------------------------------------- 1 | # Operators Examples 2 | 3 | ## Operators 4 | 5 | - **Arithmetic Operators:** (+, -, *, /, //, %, **) 6 | - **Assignment Operators:** (=, +=, -=, *=, /=, //=, **=, \\=, ^=, >>=, <<=) 7 | - **Comparison Operators:** (==, !=, >, >=, <, <=) 8 | - **Logical Operators:** (and, or, not) 9 | - **Membership Operators:** (in, not in) 10 | - **Identity Operators:** (is, is not) 11 | - **Bitwise Operators:** (&, |, ^, ~, <<, >>) 12 | 13 | --- 14 | 15 | ## Arithmetic Interesting Operators 16 | 17 | ### Exponentiation Operator 18 | 19 | When **x = 2** and **y = 5:** 20 | Exponentiation: `x ** y` is `2` to the power of `5`, aka `2^5 = 32` 21 | 22 | --- 23 | 24 | ### Floor Division Operator 25 | 26 | When **fruits = 10** and **people = 3:** 27 | We need to share the fruits. 28 | 29 | **Floor Division:** 30 | Maximum fruits that can be shared per person: `fruits // share_people = 3` 31 | -------------------------------------------------------------------------------- /src/basics/numbers.md: -------------------------------------------------------------------------------- 1 | 2 | # Number Data Type Examples 3 | 4 | ## Integer Data Type Example 5 | 6 | ### `age = 25` 7 | Int `age (25)` can be a whole number, positive or negative, without decimals, of unlimited length. 8 | 9 | #### Examples: 10 | - 35656222554887711 11 | - -3255522 12 | - 25 13 | 14 | --- 15 | 16 | ## Float Data Type Example 17 | 18 | ### `weight = 76.50` 19 | Float `weight (76.50)` can be a number, positive or negative, containing one or more decimals. 20 | 21 | #### Examples: 22 | - 1.10 23 | - 1.0 24 | - -35.59 25 | - 35e3 26 | - 12E4 27 | - -87.7e100 28 | 29 | --- 30 | 31 | ## Complex Data Type Example 32 | 33 | ### `something = 1j` 34 | Complex `something (1j)` are written with a "j" as the imaginary part. 35 | 36 | #### Examples: 37 | - 1j 38 | - 3+2j 39 | - -4j 40 | 41 | --- 42 | 43 | ## Type Cast Functions 44 | 45 | #### Examples: 46 | - `float(weight)` 47 | - `int(age)` 48 | - `complex()` 49 | """ 50 | -------------------------------------------------------------------------------- /src/basics/h_operators.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('\n >>>> Operators Example') 4 | h5('Arithmetic operators: (+,-,*,/,//,%,**)') 5 | h5('Assignment operators: (=,+=,-=,*=,/=,//=,**=,\=,^=,>>=,<<=)') 6 | h5('Comparison operators: (==,!=,>,>=,<,<=)') 7 | h5('Logical operators: (and ,or ,not)') 8 | h5('Membership operators: (in ,not in)') 9 | h5('Identity operators: (is, is not)') 10 | h5('Bitwise Operators: (&,|,^,~,<<,>>)') 11 | 12 | h2('\n Arithmetic Interesting Operators') 13 | h3 (' >>> Exponentiation Operator') 14 | x = 2 15 | y = 5 16 | h4('when x is 2 and y = 5') 17 | h5('Exponentiation: x ** y is 2 to power of 5 aka 2^5 = ', x**y) 18 | 19 | h4 ('\n >>> Floor Division Operator') 20 | fruits = 10 21 | share_people = 3 22 | h4('when fruits are 10 and people are 3 and we need to share the fruits') 23 | h5('then we can use Floor Division ') 24 | h6('Maximum can be shared: fruits // share_people = ', fruits // share_people) -------------------------------------------------------------------------------- /src/bits/4_and_8_bits.md: -------------------------------------------------------------------------------- 1 | # 4 and 8 Bit Basics 2 | 3 | ## 4 Bits 4 | #### 5 | Note: 4 bits can represent numbers from 0 to 15 (2^4 - 1). 6 | 7 | #### 8 | | Decimal | Binary | 9 | |---------|--------| 10 | | 0 | 0000 | 11 | | 1 | 0001 | 12 | | 2 | 0010 | 13 | | 3 | 0011 | 14 | | 4 | 0100 | 15 | | 5 | 0101 | 16 | | 6 | 0110 | 17 | | 7 | 0111 | 18 | | 8 | 1000 | 19 | | 9 | 1001 | 20 | | 10 | 1010 | 21 | 22 | ## 8 Bits 23 | #### 24 | Note: 8 bits can represent numbers from 0 to 255 (2^8 - 1). 25 | 26 | #### 27 | | Decimal | Binary | 28 | |---------|-----------| 29 | | 0 | 00000000 | 30 | | 1 | 00000001 | 31 | | 2 | 00000010 | 32 | | 3 | 00000011 | 33 | | 4 | 00000100 | 34 | | 5 | 00000101 | 35 | | 6 | 00000110 | 36 | | 7 | 00000111 | 37 | | 8 | 00001000 | 38 | | 9 | 00001001 | 39 | | 10 | 00001010 | 40 | 41 | -------------------------------------------------------------------------------- /src/defs/count_pair_for_max.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | from testUtils import print_and_assert, getTestResult 3 | 4 | h2('\n >>> Find Two Sum is equal Max Number in list') 5 | h2(' >>>> Count Pairs for Sum of 2 numbers = Max Number') 6 | 7 | def count_pairs_which_sum_to_max(number_list): 8 | max_number = max(number_list) 9 | count = 0 10 | 11 | for left in range(0, len(number_list)): 12 | # print('left is', left) 13 | for right in range(left + 1, len(number_list)): 14 | left_value = number_list[left] 15 | right_value = number_list[right] 16 | if (left_value + right_value == max_number): 17 | print(left_value, right_value, max_number) 18 | count += 1 19 | 20 | return count 21 | 22 | h2('\n >>> Test Cases') 23 | print_and_assert(count_pairs_which_sum_to_max, [1,2,3,4,5,6], [2,4,6]) 24 | 25 | getTestResult('Find Two Sum is equal Max Number in list') -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Generate Documentation 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v2 14 | 15 | - name: Install MkDocs 16 | run: | 17 | python3 -m pip install --upgrade pip 18 | pip install stylepy mkdocs mkdocs-material mkdocs-gen-nav-plugin mkdocs-awesome-pages-plugin pymdown-extensions mkdocstrings 19 | 20 | - name: Generate Documentation 21 | run: | 22 | chmod +x ./generate_docs.sh 23 | ./generate_docs.sh 24 | 25 | - name: Build MkDocs Site 26 | run: | 27 | mkdocs build 28 | 29 | - name: Deploy to GitHub Pages 30 | uses: peaceiris/actions-gh-pages@v3 31 | with: 32 | github_token: ${{ secrets.GITHUB_TOKEN }} 33 | publish_dir: ./site # Publish from the site generated by MkDocs 34 | keep_files: true 35 | -------------------------------------------------------------------------------- /src/sorting/quick_sort.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | def quick_sort(arr): 3 | if len(arr) <= 1: 4 | return arr 5 | 6 | pivot = arr[-1] 7 | lesser_than_pivot = [] 8 | equal_to_pivot = [] 9 | greater_than_pivot = [] 10 | 11 | for value in arr[:-1]: 12 | if value < pivot: 13 | lesser_than_pivot.append(value) 14 | elif value == pivot: 15 | equal_to_pivot.append(value) 16 | else: 17 | greater_than_pivot.append(value) 18 | 19 | if lesser_than_pivot and greater_than_pivot: 20 | return quick_sort(lesser_than_pivot) + [pivot] + equal_to_pivot + quick_sort(greater_than_pivot) 21 | elif lesser_than_pivot: 22 | return quick_sort(lesser_than_pivot) + [pivot] + equal_to_pivot 23 | else: 24 | return [pivot] + equal_to_pivot + quick_sort(greater_than_pivot) 25 | 26 | 27 | h4('Sorted', quick_sort([5,3,1,8])); 28 | h4('Sorted with duplicates', quick_sort([8,1,1,8,1,1,1,1])); 29 | -------------------------------------------------------------------------------- /src/math/number-systems/binary_to_hexadecimal.py: -------------------------------------------------------------------------------- 1 | def binary_to_hexadecimal(binary): 2 | # Binary to hexadecimal mapping 3 | binary_to_hex = { 4 | "0000": "0", "0001": "1", "0010": "2", "0011": "3", 5 | "0100": "4", "0101": "5", "0110": "6", "0111": "7", 6 | "1000": "8", "1001": "9", "1010": "A", "1011": "B", 7 | "1100": "C", "1101": "D", "1110": "E", "1111": "F" 8 | } 9 | 10 | # Pad binary to make its length a multiple of 4 11 | while len(binary) % 4 != 0: 12 | binary = "0" + binary 13 | 14 | # Convert groups of 4 to hexadecimal 15 | hexadecimal = "" 16 | for i in range(0, len(binary), 4): 17 | group = binary[i:i+4] 18 | hexadecimal += binary_to_hex[group] 19 | 20 | return hexadecimal 21 | 22 | binary_number = input("Enter the binary number: ") # For example 1011 or 0001 23 | hexadecimal_number = binary_to_hexadecimal(binary_number) 24 | print(f"The hexadecimal equivalent of binary {binary_number} is {hexadecimal_number}.") 25 | -------------------------------------------------------------------------------- /src/basics/range.md: -------------------------------------------------------------------------------- 1 | # Range Data Type Example 2 | 3 | ## Print Until 7 `range(8)` wrap with list 4 | - Output: `[0, 1, 2, 3, 4, 5, 6, 7]` 5 | 6 | ## Print from 2 to 7 `range(2, 8)` wrap with list 7 | - Output: `[2, 3, 4, 5, 6, 7]` 8 | 9 | ## Print from 0 to 20 increment by 2 (2 Table) 10 | - Using `range(0, 13, 2)` wrap with list 11 | - Output: `[0, 2, 4, 6, 8, 10, 12]` 12 | 13 | ## Print from 0 to 20 increment by 4 (4 Table) 14 | - Using `range(0, 13, 4)` wrap with list 15 | - Output: `[0, 4, 8, 12]` 16 | 17 | ## Print from 0 to 20 increment by 7 (7 Table) 18 | - Using `range(0, 13, 7)` wrap with list 19 | - Output: `[0, 7]` 20 | 21 | ## Type value of `type(range(2, 8))` 22 | - Output: `` 23 | 24 | --- 25 | 26 | ## Print Fibonacci Sequence until 10th Number 27 | - Example: 28 | ```python 29 | def fibonacci(n): 30 | a, b = 0, 1 31 | for _ in range(n): 32 | yield a 33 | a, b = b, a + b 34 | 35 | # Generate first 10 Fibonacci numbers 36 | fib_sequence = list(fibonacci(10)) 37 | Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] -------------------------------------------------------------------------------- /src/data_structures/tree/binary-search-tree/binary-tree-vs-binary-search-tree.md: -------------------------------------------------------------------------------- 1 | # Difference between Binary Tree vs Binary Search Tree (BST) 2 | 3 | In General, a Binary Tree allows nodes to be added without any specific order, whereas a Binary Search Tree requires nodes to be inserted and maintained in a sorted manner, making search operations more efficient. 4 | 5 | | Feature | Binary Tree | Binary Search Tree (BST) | 6 | |---------------------|----------------------|--------------------------| 7 | | **Node Arrangement**| Any order | Sorted order | 8 | | **Search Efficiency**| Generally slower | Faster | 9 | | **Insertion Rule** | No specific rule | Left < Parent < Right | 10 | | **Ordering** | Not ordered | Ordered | 11 | | **Traversal Outcome**| Not sorted | In-order gives sorted list | 12 | | **Use Case** | General purpose | Search-oriented tasks | 13 | | **Balancing** | Not necessarily balanced | May need balancing | 14 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: 'Webslate - Python Basics' 2 | site_url: 'https://web-slate.github.io/python-basics/' 3 | theme: 4 | name: material 5 | palette: 6 | primary: deep purple 7 | accent: deep purple 8 | font: 9 | text: Roboto 10 | code: Roboto Mono 11 | features: 12 | - navigation.sections 13 | - navigation.footer 14 | - search.suggest 15 | - search.highlight 16 | - search.share 17 | - content.code.copy 18 | 19 | plugins: 20 | - search 21 | - gen_nav: 22 | enabled: true 23 | 24 | 25 | markdown_extensions: 26 | - pymdownx.highlight: 27 | use_pygments: true 28 | linenums: true 29 | - pymdownx.superfences 30 | 31 | nav: 32 | - Basics: basics/introduction.md 33 | - Data Types: data_types/introduction.md 34 | - Methods: basics/methods/introduction.md 35 | - Recursions: basics/recursions/introduction.md 36 | - Data Structures: data_structures/introduction.md 37 | - OOPs: oops/introduction.md 38 | - Algorithms: algorithms/introduction.md 39 | - Leet Code: leet_code/introduction.md 40 | -------------------------------------------------------------------------------- /src/bits/4_and_8_bits.py: -------------------------------------------------------------------------------- 1 | #import data_types.commonUtils as utils 2 | from stylepy import h1, h2, h3, h4, h5, h6 3 | 4 | h1('4 and 5 Bit Basics') 5 | 6 | h2('4 Bits') 7 | h4('Note: 4 bits can represent numbers from 0 to 15 (2^4 - 1).') 8 | h4(''' 9 | | Decimal | Binary | 10 | |---------|--------| 11 | | 0 | 0000 | 12 | | 1 | 0001 | 13 | | 2 | 0010 | 14 | | 3 | 0011 | 15 | | 4 | 0100 | 16 | | 5 | 0101 | 17 | | 6 | 0110 | 18 | | 7 | 0111 | 19 | | 8 | 1000 | 20 | | 9 | 1001 | 21 | | 10 | 1010 | 22 | ''') 23 | 24 | h2('8 Bits') 25 | h4('Note: 8 bits can represent numbers from 0 to 255 (2^8 - 1).') 26 | h4(''' 27 | | Decimal | Binary | 28 | |---------|-----------| 29 | | 0 | 00000000 | 30 | | 1 | 00000001 | 31 | | 2 | 00000010 | 32 | | 3 | 00000011 | 33 | | 4 | 00000100 | 34 | | 5 | 00000101 | 35 | | 6 | 00000110 | 36 | | 7 | 00000111 | 37 | | 8 | 00001000 | 38 | | 9 | 00001001 | 39 | | 10 | 00001010 | 40 | ''') -------------------------------------------------------------------------------- /src/math/number-systems/roman_to_decimal.py: -------------------------------------------------------------------------------- 1 | def roman_to_decimal(roman): 2 | # Define Roman numeral to decimal mappings 3 | roman_to_decimal_map = { 4 | 'I': 1, 'V': 5, 'X': 10, 'L': 50, 5 | 'C': 100, 'D': 500, 'M': 1000 6 | } 7 | 8 | decimal = 0 9 | prev_value = 0 10 | 11 | # Iterate through each Roman numeral in reverse order 12 | for numeral in reversed(roman): 13 | value = roman_to_decimal_map[numeral] 14 | 15 | # Subtract if the value is less than the previous value, otherwise add 16 | if value < prev_value: 17 | decimal -= value 18 | else: 19 | decimal += value 20 | 21 | prev_value = value # Update the previous value 22 | 23 | return decimal 24 | 25 | 26 | roman_number = input("Enter the Roman numeral: ").upper() # for example MCMLXXXVII 27 | try: 28 | decimal_number = roman_to_decimal(roman_number) 29 | print(f"The decimal equivalent of Roman numeral {roman_number} is {decimal_number}.") 30 | except KeyError: 31 | print("Invalid Roman numeral. Please enter a valid Roman numeral.") 32 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "type": "npm", 7 | "script": "start", 8 | "isBackground": true, 9 | "problemMatcher": { 10 | "owner": "typescript", 11 | "pattern": "$tsc", 12 | "background": { 13 | "activeOnStart": true, 14 | "beginsPattern": { 15 | "regexp": "(.*?)" 16 | }, 17 | "endsPattern": { 18 | "regexp": "bundle generation complete" 19 | } 20 | } 21 | } 22 | }, 23 | { 24 | "type": "npm", 25 | "script": "test", 26 | "isBackground": true, 27 | "problemMatcher": { 28 | "owner": "typescript", 29 | "pattern": "$tsc", 30 | "background": { 31 | "activeOnStart": true, 32 | "beginsPattern": { 33 | "regexp": "(.*?)" 34 | }, 35 | "endsPattern": { 36 | "regexp": "bundle generation complete" 37 | } 38 | } 39 | } 40 | } 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /src/bits/basics.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | h1('To determine whether your Mac is 32-bit or 64-bit, you can use a command in the Terminal. ') 3 | 4 | h2('Below for mac / linux system.') 5 | 6 | h3("uname -m ") 7 | 8 | 9 | # Output `x86_64`` 10 | 11 | # Windows 12 | 13 | 14 | h4("wmic os get osarchitecture") 15 | 16 | 17 | # Output below 18 | 19 | 20 | #OSArchitecture 21 | 22 | #64-bit 23 | 24 | 25 | # is integer variable depends on my bit system ? 26 | 27 | # In Python, the size of an integer is not constrained by the number of bits in a byte but by the available memory. Thus, integers can be of any size until the memory is exhausted. 28 | 29 | # An int in Java is always 32 bits, regardless of whether the system is 32-bit or 64-bit. 30 | 31 | # In NodeJS, all numbers are represented as double-precision 64-bit binary format IEEE 754 numbers 32 | 33 | # In Go, int and uint types are platform dependent. On a 32-bit system, these types are 32 bits, while on a 64-bit system, they are 64 bits. 34 | 35 | # In Rust, integer types have fixed sizes regardless of the platform. Types such as i32, i64, u32, u64, 36 | -------------------------------------------------------------------------------- /src/data_structures/queue/queue_collections_deque.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4 2 | h2(""" 3 | - collections.deque in Python is a mutable data structure, and you can add, remove, or modify elements. 4 | - It is a double-ended queue, optimized for fast operations at both ends. 5 | 6 | """) 7 | 8 | from collections import deque 9 | h1("initialise the queue using deque ") 10 | # Creating a deque 11 | my_deque = deque([10, 4, 5, 8]) 12 | 13 | h2("adding value 25 to the right - using .append()") 14 | # Adding an element to the right 15 | my_deque.append(25) 16 | h3("Print the queue items") 17 | h4(my_deque) # Output: deque([10, 4, 5, 8, 25]) 18 | 19 | h2("removing item from the left - fifo using .popleft()") 20 | # Removing an element from the left 21 | removed_element = my_deque.popleft() 22 | h3("Removed element:", removed_element) # Output: Removed element: 10 23 | h4(my_deque) # Output: deque([4, 5, 8, 25]) 24 | 25 | 26 | # Removing an element from the right 27 | h2("removing item from the right - lifo using .pop()") 28 | removed_element = my_deque.pop() 29 | h3("Removed element:", removed_element) # Output: Removed element: 25 30 | h4(my_deque) # Output: deque([4, 5, 8]) 31 | -------------------------------------------------------------------------------- /src/data_structures/tree/general/simple-tree.py: -------------------------------------------------------------------------------- 1 | # from testUtils import solution_title, print_and_assert_new, getTestResult 2 | # from commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> Simple Tree Implementation') 5 | 6 | class TreeNode: 7 | def __init__(self, value): 8 | self.value = value 9 | self.children = [] 10 | 11 | def add_child(self, child_node): 12 | self.children.append(child_node) 13 | 14 | def traverse_child(self): 15 | nodes = [self] 16 | while len(nodes) > 0: 17 | current_node = nodes.pop() 18 | print('>', current_node.value) 19 | nodes += current_node.children 20 | 21 | ceo = TreeNode('CEO') 22 | finance = TreeNode('Finance Head') 23 | marketing = TreeNode('Marketing Head') 24 | it = TreeNode('IT Head') 25 | 26 | ceo.add_child(finance) 27 | ceo.add_child(marketing) 28 | ceo.add_child(it) 29 | 30 | finance_lead = TreeNode('Finance Lead') 31 | marketing_lead = TreeNode('Marketing Lead') 32 | it_lead = TreeNode('IT Lead') 33 | 34 | finance.add_child(finance_lead) 35 | marketing.add_child(marketing_lead) 36 | it.add_child(it_lead) 37 | 38 | ceo.traverse_child() -------------------------------------------------------------------------------- /src/data_structures/linked_list/ReadMe.md: -------------------------------------------------------------------------------- 1 | ## Linked List Time Complexity Table 2 | 3 | | Operation | Singly-Linked List | Doubly-Linked List | Circular Linked List | 4 | |----------------------|--------------------|--------------------|----------------------| 5 | | Access Head | O(1) | O(1) | O(1) | 6 | | Insert Head | O(1) | O(1) | O(1) | 7 | | Delete Head | O(1) | O(1) | O(1) | 8 | | Access Tail | O(n) | O(1) | O(n) | 9 | | Insert Tail | O(n) | O(1) | O(1) | 10 | | Delete Tail | O(n) | O(1) | O(1) | 11 | | Access Middle | O(n) | O(n) | O(n) | 12 | | Insert Middle | O(n) | O(n) | O(n) | 13 | | Delete Middle | O(n) | O(n) | O(n) | 14 | | Search for a Value | O(n) | O(n) | O(n) | 15 | -------------------------------------------------------------------------------- /src/basics/c_if.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | # Statement 4 | h1('\n >>>> Statement Example') 5 | 6 | # isEligibleToVote Function 7 | h2('\n >>>> isEligibleToVote Function with passing age') 8 | 9 | def isEligibleToVote(age: int = 0) -> None: 10 | try: 11 | if(age > 0 and age < 21): 12 | print(str(age) + ' Wow, You will be soon eligible to vote') 13 | elif(age > 21): 14 | print(str(age) + ' Congrats, You are eligible to vote!') 15 | else: 16 | print(str(age) + ' Invalid `age` parameter') 17 | except Exception as e: 18 | print('Got error for param "' + age + '"\nError is ', e) 19 | 20 | # Example usage 21 | h3('\n >>>> Passing nothing consider default parameter if provided') 22 | isEligibleToVote() 23 | h4('\n >>>> Passing `16` return "Wow, You will be soon eligible to vote"') 24 | isEligibleToVote(16) 25 | h5('\n >>>> Passing `19` return "Wow, You will be soon eligible to vote"') 26 | isEligibleToVote(19) 27 | h6('\n >>>> Passing `25` return "Congrats, You are eligible to vote!"') 28 | isEligibleToVote(25) 29 | h4('\n >>>> Passing `\'\'` as parameter throws TypeError: \'<\' not supported between instances of \'str\' and \'int\'') 30 | isEligibleToVote('') -------------------------------------------------------------------------------- /src/math/fibonacci.py: -------------------------------------------------------------------------------- 1 | from tabulate import tabulate 2 | def fibonacci_recursive(n: int): 3 | if n <= 1: 4 | return n 5 | return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) 6 | 7 | print("Reccursive Fibonacci") 8 | n = 10 9 | print([fibonacci_recursive(value) for value in range(n)]) 10 | 11 | 12 | def fibonacci_memoized(n, memo={}): 13 | if n <= 1: 14 | return n 15 | if n not in memo: 16 | memo[n] = fibonacci_memoized(n - 1, memo) + fibonacci_memoized(n - 2, memo) 17 | return memo[n] 18 | print("Reccursive memoized") 19 | n = 10 20 | print([fibonacci_memoized(value) for value in range(n)]) 21 | 22 | def fibonacci_optimised(n): 23 | if n <= 1: 24 | return n 25 | prev = 0 26 | current = 1 27 | for _ in range(2, n+1 ): 28 | temp = current 29 | current = current + prev 30 | prev = temp 31 | return current 32 | 33 | print("Reccursive optimised") 34 | n = 10 35 | print([fibonacci_optimised(value) for value in range(n)]) 36 | 37 | table = (["Solution", "Time complexity", "Space complexity"], 38 | ["Recursive", "O(2^n)", "O(2^n)"], 39 | ["Recursive memoized" , "O(n)" , "O(n)"], 40 | ["Optimised" , "O(n)" , "O(1)"]) 41 | 42 | print(tabulate(table, headers="firstrow")) 43 | 44 | -------------------------------------------------------------------------------- /src/basics/i_range.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('\n >>>> Range Data Type Example') 4 | h5('\n >>>> Print Until 7 `range(8)` wrap with list') 5 | h5(list(range(8))) 6 | 7 | h5('\n >>>> Print from 2 to 7 `range(2, 8)` wrap with list') 8 | h6(list(range(2, 8))) 9 | 10 | h4('\n >>>> Print from 0 to 20 increment 2 like 2 Table') 11 | h5('Using `range(0, 13, 2)` wrap with list') 12 | h6(list(range(0, 13, 2))) 13 | 14 | h4('\n >>>> Print from 0 to 20 increment 2 like 4 Table') 15 | h5('Using `range(0, 13, 4)` wrap with list') 16 | h6(list(range(0, 13, 4))) 17 | 18 | h4('\n >>>> Print from 0 to 20 increment 2 like 7 Table') 19 | h5('Using `range(0, 13, 7)` wrap with list') 20 | h6(list(range(0, 13, 7))) 21 | 22 | h5('\n Type value of type(range(2, 8)) is below') 23 | h6(type(range(2, 8))) 24 | 25 | 26 | # def square(number): 27 | # return number ** 2 28 | 29 | # numbers = [1, 2, 3, 4, 5] 30 | # squared_numbers = list(map(square, numbers)) 31 | 32 | h2('\n >>>> Print Fibonacci Sequence until 10th Number') 33 | 34 | def fibonacci(n): 35 | a, b = 0, 1 36 | for _ in range(n): 37 | yield a 38 | a, b = b, a + b 39 | 40 | # Example: Generate first 10 Fibonacci numbers 41 | fib_sequence = list(fibonacci(10)) 42 | h4(fib_sequence) -------------------------------------------------------------------------------- /src/data_types/linear/list/basics.py: -------------------------------------------------------------------------------- 1 | import data_types.commonUtils as utils 2 | 3 | utils.print_h1('List Basics') 4 | 5 | utils.print_ordered_list([ 6 | 'List is Ordered (order will not be changed)', 7 | 'List is Changable' 8 | ]) 9 | 10 | fruits = ['apple', 'orange', 'cherry'] 11 | print('\nCreated fruits list: ', fruits) 12 | print('Access Apple: fruits[0]: ', fruits[0]) 13 | print('Adding New Fruit: Grape') 14 | fruits.append('grapes') 15 | print('Picking Last item from fruit:', fruits[-1]) 16 | 17 | print('Iterating the Fruits') 18 | for fruit in fruits: 19 | print(' - ', fruit) 20 | 21 | marks = [78, 90, 75, 61, 90] 22 | print('\nCreated marks list: ', marks); 23 | marks.reverse() 24 | print('Reversed the Marks using reverse(): ', marks); 25 | marks.sort() 26 | print('Sort the Marks in ascending using sort(): ', marks); 27 | marks.sort(reverse=True) 28 | print('Sort the Marks in descending using sort(reverse=True): ', marks); 29 | print('marks : ', marks) 30 | 31 | conf = [True, False] 32 | print('conf =: ', conf) 33 | 34 | employee = ['Venkat', 37, 'Developer'] 35 | print('employ: ', employee) 36 | 37 | 38 | ''' 39 | 1. How iterator internally working? 40 | 2. When do we go for list 41 | 3. How memory allocation working in List data type? 42 | 4. Which data structure can be created using List? 43 | ''' 44 | -------------------------------------------------------------------------------- /src/defs/testUtils.py: -------------------------------------------------------------------------------- 1 | failures = 0 2 | 3 | def flag_failure(): 4 | global failures 5 | failures = (failures or 0) + 1 6 | 7 | def failure_count(): 8 | return failures 9 | 10 | def solution_title(title): 11 | print('=' * 70) 12 | print(f'>>> {title}') 13 | print('=' * 70) 14 | 15 | def print_and_assert(function_name, param, expected): 16 | try: 17 | assert function_name(param) == expected 18 | print(f'✅ Pass: {function_name.__name__}({param}) is returning {expected} as expected') 19 | except AssertionError: 20 | flag_failure() 21 | print(f'❌ AssertionError: {function_name.__name__}({param}) is returning {function_name(param)} but `{expected}` is expected') 22 | 23 | def print_and_assert_new(function_name, *params, expected): 24 | try: 25 | assert function_name(*params) == expected 26 | print(f'✅ Pass: {function_name.__name__}{params} is returning {expected} as expected') 27 | except AssertionError: 28 | flag_failure() 29 | print(f'❌ AssertionError: {function_name.__name__}{params} is returning {function_name(*params)} but `{expected}` is expected') 30 | 31 | def getTestResult(testName): 32 | if (failure_count() > 0): 33 | print(f"{failure_count()} Failure in {testName} tests") 34 | else: 35 | print(f"{testName} tests are passed!") -------------------------------------------------------------------------------- /src/data_types/numeric/float/testUtils.py: -------------------------------------------------------------------------------- 1 | failures = 0 2 | 3 | def flag_failure(): 4 | global failures 5 | failures = (failures or 0) + 1 6 | 7 | def failure_count(): 8 | return failures 9 | 10 | def solution_title(title): 11 | print('=' * 70) 12 | print(f'>>> {title}') 13 | print('=' * 70) 14 | 15 | def print_and_assert(function_name, param, expected): 16 | try: 17 | assert function_name(param) == expected 18 | print(f'✅ Pass: {function_name.__name__}({param}) is returning {expected} as expected') 19 | except AssertionError: 20 | flag_failure() 21 | print(f'❌ AssertionError: {function_name.__name__}({param}) is returning {function_name(param)} but `{expected}` is expected') 22 | 23 | def print_and_assert_new(function_name, *params, expected): 24 | try: 25 | assert function_name(*params) == expected 26 | print(f'✅ Pass: {function_name.__name__}{params} is returning {expected} as expected') 27 | except AssertionError: 28 | flag_failure() 29 | print(f'❌ AssertionError: {function_name.__name__}{params} is returning {function_name(*params)} but `{expected}` is expected') 30 | 31 | def getTestResult(testName): 32 | if (failure_count() > 0): 33 | print(f"{failure_count()} Failure in {testName} tests") 34 | else: 35 | print(f"{testName} tests are passed!") -------------------------------------------------------------------------------- /src/data_structures/linked_list/testUtils.py: -------------------------------------------------------------------------------- 1 | failures = 0 2 | 3 | def flag_failure(): 4 | global failures 5 | failures = (failures or 0) + 1 6 | 7 | def failure_count(): 8 | return failures 9 | 10 | def solution_title(title): 11 | print('=' * 70) 12 | print(f'>>> {title}') 13 | print('=' * 70) 14 | 15 | def print_and_assert(function_name, param, expected): 16 | try: 17 | assert function_name(param) == expected 18 | print(f'✅ Pass: {function_name.__name__}({param}) is returning {expected} as expected') 19 | except AssertionError: 20 | flag_failure() 21 | print(f'❌ AssertionError: {function_name.__name__}({param}) is returning {function_name(param)} but `{expected}` is expected') 22 | 23 | def print_and_assert_new(function_name, *params, expected): 24 | try: 25 | assert function_name(*params) == expected 26 | print(f'✅ Pass: {function_name.__name__}{params} is returning {expected} as expected') 27 | except AssertionError: 28 | flag_failure() 29 | print(f'❌ AssertionError: {function_name.__name__}{params} is returning {function_name(*params)} but `{expected}` is expected') 30 | 31 | def getTestResult(testName): 32 | if (failure_count() > 0): 33 | print(f"{failure_count()} Failure in {testName} tests") 34 | else: 35 | print(f"{testName} tests are passed!") -------------------------------------------------------------------------------- /src/problems/testUtils.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | failures = 0 3 | 4 | def flag_failure(): 5 | global failures 6 | failures = (failures or 0) + 1 7 | 8 | def failure_count(): 9 | return failures 10 | 11 | def solution_title(title): 12 | print('=' * 70) 13 | print(f'>>> {title}') 14 | print('=' * 70) 15 | 16 | def print_and_assert(function_name, param, expected): 17 | try: 18 | assert function_name(param) == expected 19 | h4(f'✅ Pass: {function_name.__name__}({param}) is returning {expected} as expected') 20 | except AssertionError: 21 | flag_failure() 22 | h4(f'❌ AssertionError: {function_name.__name__}({param}) is returning {function_name(param)} but `{expected}` is expected') 23 | 24 | def print_and_assert_new(function_name, *params, expected): 25 | try: 26 | assert function_name(*params) == expected 27 | h4(f'✅ Pass: {function_name.__name__}{params} is returning {expected} as expected') 28 | except AssertionError: 29 | flag_failure() 30 | h4(f'❌ AssertionError: {function_name.__name__}{params} is returning {function_name(*params)} but `{expected}` is expected') 31 | 32 | def getTestResult(testName): 33 | if (failure_count() > 0): 34 | h5(f"{failure_count()} Failure in {testName} tests") 35 | else: 36 | h6(f"{testName} tests are passed!") -------------------------------------------------------------------------------- /src/bits/16_and_32_bits.md: -------------------------------------------------------------------------------- 1 | 2 | # 16 and 32 Bit Basics 3 | 4 | ## 16 Bits 5 | #### 6 | Note: 16 bits can represent numbers from 0 to 65,535 (2^16 - 1). 7 | 8 | #### 9 | | Decimal | Binary | 10 | |---------|-------------------| 11 | | 0 | 0000000000000000 | 12 | | 1 | 0000000000000001 | 13 | | 2 | 0000000000000010 | 14 | | 3 | 0000000000000011 | 15 | | 4 | 0000000000000100 | 16 | | 5 | 0000000000000101 | 17 | | 6 | 0000000000000110 | 18 | | 7 | 0000000000000111 | 19 | | 8 | 0000000000001000 | 20 | | 9 | 0000000000001001 | 21 | | 10 | 0000000000001010 | 22 | 23 | ## 32 Bits 24 | #### 25 | Note: 32 bits can represent numbers from 0 to 4,294,967,295 (2^32 - 1). Full binary representation for numbers larger than 16 bits is quite lengthy, so only the least significant 16 bits are shown for brevity. 26 | 27 | #### 28 | | Decimal | Binary (only showing least significant 16 bits for brevity) | 29 | |---------|------------------------------------------------------------| 30 | | 0 | 0000000000000000 | 31 | | 1 | 0000000000000001 | 32 | | 2 | 0000000000000010 | 33 | | ... | ... | 34 | | 10 | 0000000000001010 | 35 | 36 | -------------------------------------------------------------------------------- /src/data_structures/priority_queue/priority_queue_readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## Priority Queue: 3 | 4 | A priority queue is a queue that arranges the elements based on the priority of the elements. 5 | 6 | Elements with higher priority values are typically retreived before elements with lower priority values. 7 | 8 | In a priority queue each element has a priority queue associated with it. 9 | When you add an element in a queue it is inserted in a position based on it's priority value. 10 | 11 | If you add an element with a higher priority value to priority queue, it may be inserted near the front of the queue. 12 | Element with lower priorty valued inserted at back 13 | 14 | There are several ways to implement a priority queue, including using an array, linkedlist, heap, or binary serach tree. 15 | 16 | Each method has its own advantages and disadvantages. 17 | 18 | Priority Queues are often used in real-time systems, where the order in which elements are processed can have significant consequences. 19 | They are also used in algorithms to improve their efficiencies, such as Dijkstra's algorithm for finding the shortest path in a graph. A* search algorithm for pathfinding. 20 | 21 | If two elemnets have the same priority, they are served according to their order in the queue. 22 | 23 | How priority is assigned to the elements in a Priority Queue? 24 | 25 | In a priority queue, generally, the value of an element is considered for assigning the priority. 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/Inheritance/simple_inheritance.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | class Parent: 3 | parent_name1 = "Sivan" 4 | def __init__(self, name=""): 5 | h4(" Parent class is created") 6 | self.parent_name = "Sivan" 7 | def get_parent_name(self): 8 | h4(f" Parent Name is {self.parent_name}") 9 | 10 | def grace_us(self): 11 | h4(" All is well") 12 | 13 | 14 | class Child(Parent): 15 | def __init__(self, name, parent_name=""): 16 | # Parent.__init__(self, name=parent_name) 17 | super().__init__(name=parent_name) 18 | 19 | # print(" Overriding Parent's Init class") 20 | self.name = name 21 | h4(" Child Name is Vinayagar") 22 | 23 | 24 | # child_class = Child(name= "Vinayagar") 25 | # # print(" Trying to call parent init") 26 | # print(child_class.parent_name) 27 | 28 | child_class = Child("Vinayagar", "Sivan") 29 | h3(" Trying to call parent init") 30 | child_class.get_parent_name() 31 | 32 | 33 | 34 | h3(" To use global variable inside a function we need use a keyword : Global") 35 | 36 | x = 5 37 | 38 | h4("Initial glbal varibale value is x : " , x) 39 | def myfunc(): 40 | global x 41 | x = 300 42 | h5("Set the global variable x inside a function ", x) 43 | def myfunc2(): 44 | 45 | x = 100 46 | h6("second Local variable is", x) 47 | myfunc2() 48 | 49 | myfunc() 50 | h3("global variable is x ", x) 51 | 52 | -------------------------------------------------------------------------------- /src/bits/16_and_32_bits.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('16 and 32 Bit Basics') 4 | 5 | h2('16 Bits') 6 | h4('Note: 16 bits can represent numbers from 0 to 65,535 (2^16 - 1).') 7 | h4(''' 8 | | Decimal | Binary | 9 | |---------|-------------------| 10 | | 0 | 0000000000000000 | 11 | | 1 | 0000000000000001 | 12 | | 2 | 0000000000000010 | 13 | | 3 | 0000000000000011 | 14 | | 4 | 0000000000000100 | 15 | | 5 | 0000000000000101 | 16 | | 6 | 0000000000000110 | 17 | | 7 | 0000000000000111 | 18 | | 8 | 0000000000001000 | 19 | | 9 | 0000000000001001 | 20 | | 10 | 0000000000001010 | 21 | ''') 22 | 23 | h2('32 Bits') 24 | h4('Note: 32 bits can represent numbers from 0 to 4,294,967,295 (2^32 - 1). Full binary representation for numbers larger than 16 bits is quite lengthy, so only the least significant 16 bits are shown for brevity.') 25 | h4(''' 26 | | Decimal | Binary (only showing least significant 16 bits for brevity) | 27 | |---------|------------------------------------------------------------| 28 | | 0 | 0000000000000000 | 29 | | 1 | 0000000000000001 | 30 | | 2 | 0000000000000010 | 31 | | ... | ... | 32 | | 10 | 0000000000001010 | 33 | ''') -------------------------------------------------------------------------------- /src/math/calculations/multiply.py: -------------------------------------------------------------------------------- 1 | 2 | from stylepy import h1,h2,h3,h4,h5,h6 3 | def multiplyWithAddTest(a, b): 4 | try: 5 | # Perform an arithmetic operation that will fail for non-numeric types 6 | test = (a + b) - b 7 | return a * b 8 | except TypeError as e: 9 | # If an error occurs, return the error message 10 | return f"Invalid parameter value {a}, {b}" 11 | 12 | h1(' >>> multiplyWithAddTest') 13 | h4(multiplyWithAddTest(7, 5)) # Valid numerical input 14 | h4(multiplyWithAddTest(7, "abc")) # Invalid input 15 | h4(multiplyWithAddTest("xyz", 3)) # Invalid input 16 | 17 | 18 | def multiplyWithTypeCheck(a, b): 19 | try: 20 | # Perform an arithmetic operation that will fail for non-numeric types 21 | # if (isinstance(a, int) and isinstance(b, int)): #below is alternative check statement 22 | if type(a) is int and type(b) is int: 23 | return a * b 24 | else: 25 | raise TypeError('Parameter is not valid data type') 26 | except TypeError as e: 27 | # If an error occurs, return the error message 28 | # return f"Invalid parameter value {a}, {b}" 29 | return f"{e}: {a}, {b}" 30 | 31 | h1(' >>> multiplyWithTypeCheck') 32 | h4(multiplyWithTypeCheck(7, 5)) # Valid numerical input 33 | h4(multiplyWithTypeCheck(7, "abc")) # Invalid input 34 | h4(multiplyWithTypeCheck("xyz", 3)) # Invalid input 35 | h4(multiplyWithTypeCheck(7.5, 3)) # Invalid input 36 | 37 | -------------------------------------------------------------------------------- /src/classes/init-example.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | # __init__() is a built function 3 | # https://chat.openai.com/share/eb3388df-6669-41ee-a16e-d471ec115799 4 | # It facilitates the initial creation of object properties and do the initial function calls 5 | # TypeError: Bus.__init__() takes 0 positional arguments but 1 was given 6 | class Bus: 7 | 8 | # Below one gives this error # TypeError: Bus.__init__() takes 0 positional arguments but 1 was given 9 | # def __init__(): 10 | # length = 4 11 | # width = 2 12 | 13 | # What the above error means, The error you're encountering typically occurs when __init__() method is defined without any parameters, 14 | # But, python tries to call it with the "self" argument automatically 15 | 16 | 17 | def __init__(self): 18 | 19 | self.length = 4 20 | self.width = 2 21 | # def __str__(self): 22 | # # print(f"length is {self.length}") 23 | # # return f"length is {self.length}" 24 | 25 | # If the methods are not defined with a first parameter then we cannot use the object variables, to access 26 | # To access object variables 27 | 28 | # def area(): 29 | # length = 4 30 | # width = 2 31 | # return length*width 32 | # def area(self): 33 | 34 | # return self.length*self.width 35 | 36 | 37 | bus = Bus() 38 | print(bus) 39 | # bus.length 40 | # print(bus.area()) 41 | print(f"Bus object has created") 42 | 43 | -------------------------------------------------------------------------------- /__complexities/big-o-notations.md: -------------------------------------------------------------------------------- 1 | ### Complexity Graph 2 | 3 | ![image](https://github.com/web-slate/python-basics/assets/1652629/c99fd9dd-4073-4f99-9660-6ec052e35d12) 4 | 5 | - Constant O(1) 6 | - Logarithmic O(log n) 7 | - Linear O(n) 8 | - Linearithmic O(n log n) 9 | - Quadratic O(n^2) 10 | - Cubic O(n^3) 11 | - Exponential O(2^n) 12 | 13 | ### Time Complexity Notations and Examples 14 | 15 | | Character | Description | Example Problem | 16 | |-----------|---------------------------------------------------------|--------------------------------------------------| 17 | | `n` | Size of the input | Linear Search (searching an array of size `n`) | 18 | | `k` | A specific portion of the input or a constant | String Slicing (slicing a substring of length `k`)| 19 | | `m` | Another input dimension, often used with `n` | Matrix Operations (on an `m x n` matrix) | 20 | | `log n` | Logarithm of the input size | Binary Search (in a sorted array of size `n`) | 21 | | `n^2` | Square of the input size | Bubble Sort (sorting an array of size `n`) | 22 | | `2^n` | Exponential growth relative to the input size | Subset generation (of a set with `n` elements) | 23 | | `n!` | Factorial of the input size | Permutations (finding all permutations of `n` items) | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/data_types/boolean/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/boolean/basics.py 2 | # python -m data_types.boolean.basics data_types/boolean/basics.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Boolean Basics') 7 | 8 | show_gender = False 9 | actively_looking_for_job = True 10 | 11 | utils.print_blockquote([ 12 | 'Can Show Gender details in general? ' + 13 | 'No' if show_gender == False else 'Yes', 14 | 'Are you looking for job? ' + 'Yes' if actively_looking_for_job == True else 'No', 15 | 'True is treated as the integer 1 print(True == 1) # Outputs: True ', 16 | 'False is treated as the integer print(False == 0) # Outputs: True' 17 | ]) 18 | 19 | utils.print_blockquote([ 20 | 'Arithmetic with booleans', 21 | 'print(True + True) # Outputs: 2 (equivalent to 1 + 1)', 22 | 'print(True * 10) # Outputs: 10 (equivalent to 1 * 10)', 23 | ]) 24 | 25 | post_graduated = False 26 | 27 | utils.print_blockquote([ 28 | 'I have variable called post_graduated set to False' 29 | 'Trying to delete post_graduated by `del post_graduated` ', 30 | 'Try to print (print(post_graduated)) then system throws NameError: name post_graduated is not defined', 31 | 'Use Try/Catch to make sure if its deleted ' 32 | ]) 33 | 34 | del post_graduated 35 | 36 | # Throws NameError: name post_graduated is not defined 37 | # print(post_graduated) 38 | 39 | try: 40 | print(post_graduated) # Try to access the variable 41 | except NameError: 42 | utils.print_span("post_graduated has been deleted.") 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/bits/64_and_128_bits.md: -------------------------------------------------------------------------------- 1 | # 64 and 128 Bit Basics 2 | 3 | ## 64 Bits 4 | #### 5 | Note: 64 bits can represent numbers from 0 to 18,446,744,073,709,551,615 (2^64 - 1). Only the least significant 16 bits are shown. 6 | 7 | #### 8 | | Decimal | Binary (only showing least significant 16 bits for brevity) | 9 | |---------|------------------------------------------------------------| 10 | | 0 | 0000000000000000 | 11 | | 1 | 0000000000000001 | 12 | | 2 | 0000000000000010 | 13 | | ... | ... | 14 | | 10 | 0000000000001010 | 15 | 16 | ## 128 Bits 17 | ### 18 | Note: 128 bits can represent a very large range of numbers, from 0 up to 340,282,366,920,938,463,463,374,607,431,768,211,455 (2^128 - 1). Only the least significant 16 bits are shown for simplicity. 19 | 20 | #### 21 | | Decimal | Binary (only showing least significant 16 bits for brevity) | 22 | |---------|------------------------------------------------------------| 23 | | 0 | 0000000000000000 | 24 | | 1 | 0000000000000001 | 25 | | 2 | 0000000000000010 | 26 | | ... | ... | 27 | | 10 | 0000000000001010 | 28 | 29 | -------------------------------------------------------------------------------- /src/leetcode/palindrome.py: -------------------------------------------------------------------------------- 1 | from tabulate import tabulate 2 | print("frute force solution") 3 | print("""===================""") 4 | 5 | def is_valid_polindrome(s: str) -> bool: 6 | string = keep_alphanumeric(s) 7 | return string == string[::-1] 8 | 9 | 10 | def keep_alphanumeric(s: str) -> str : 11 | string = ''.join(char.lower() for char in s if char.isalnum()) 12 | return string 13 | 14 | s = 'mam , () test' 15 | print(f"given {s} { ' palindrome ' if is_valid_polindrome(s) else ' is not palindrome'}") 16 | s = 'mam ()' 17 | print(f"given {s} { ' palindrome ' if is_valid_polindrome(s) else ' is not palindrome'}") 18 | print(""" """) 19 | print("Optimised solution") 20 | print("""===================""") 21 | 22 | def is_valid(s: str) -> bool: 23 | s = ''.join(char.lower() for char in s if char.isalnum()) 24 | left, right = 0 , len(s) - 1 25 | while left < right: 26 | if s[left] != s[right]: 27 | return False 28 | else: 29 | left += 1 30 | right -= 1 31 | return True 32 | 33 | s = 'mam , () test' 34 | print(f"given {s} { ' palindrome ' if is_valid(s) else ' is not palindrome'}") 35 | s = 'mam ()' 36 | print(f"given {s} { ' palindrome ' if is_valid(s) else ' is not palindrome'}") 37 | 38 | table_data = [ 39 | ["Approach", "Time Complexity", "Example Code"], 40 | ["Brute-Force", "O(n)", "is_palindrome_bruteforce_string(s)"], 41 | ["Optimized", "O(n/2) = O(n)", "is_palindrome_optimized_string(s)"] 42 | ] 43 | 44 | table = tabulate(table_data, headers="firstrow", tablefmt="fancy_grid") 45 | 46 | print(table) -------------------------------------------------------------------------------- /src/Inheritance/inheritance_readme.md: -------------------------------------------------------------------------------- 1 | ## Inheritance 2 | 3 | - Inheritance allows us to define a class that inherits all features and methods from the another class 4 | 5 | - Parent Class or base class: Parent class is the class being inherited from 6 | - Pass keyword when you do not want to add any other properties or methods to the class 7 | 8 | class Student(Person): 9 | pass 10 | 11 | Add /_/_init__() Function 12 | 13 | The __init__() function is called automatically every time the class is being used to create a new object. 14 | 15 | When you add the __init__() function, the child class no longer inherit the parent's /_/_init__() function 16 | 17 | The child's __init__() function overrides the inheritence of the parent's __init__() function 18 | 19 | To keep the inheritence of the parent's /_/_init__(), add a call to the parent's /_/_init__() 20 | 21 | class Student(Person): 22 | def __init__(self, fname, lname): 23 | Person.__init__(self, fname, lname) 24 | 25 | ## Super() 26 | 27 | Super() function that will make the child class inherit all the methods and properties from its parent. 28 | 29 | super().__init__() 30 | 31 | If you add a method in the child class with thhe same name as a function in the parent class, the inheritance of the parent method will be overridden. 32 | 33 | def myfunc(): 34 | x = 300 35 | print(x) 36 | 37 | myfunc() 38 | 39 | def myfunc(): 40 | x = 300 41 | def myinnerfunc(): 42 | print(x) 43 | myinnerfunc() 44 | 45 | myfunc() 46 | 47 | def myfunc(): 48 | global x 49 | x = 300 50 | 51 | myfunc() 52 | 53 | print(x) -------------------------------------------------------------------------------- /src/bits/64_and_128_bits.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | h1('64 and 128 Bit Basics') 4 | 5 | h2('64 Bits') 6 | h4('Note: 64 bits can represent numbers from 0 to 18,446,744,073,709,551,615 (2^64 - 1). Only the least significant 16 bits are shown.') 7 | h4(''' 8 | | Decimal | Binary (only showing least significant 16 bits for brevity) | 9 | |---------|------------------------------------------------------------| 10 | | 0 | 0000000000000000 | 11 | | 1 | 0000000000000001 | 12 | | 2 | 0000000000000010 | 13 | | ... | ... | 14 | | 10 | 0000000000001010 | 15 | ''') 16 | 17 | h2('128 Bits') 18 | h3('Note: 128 bits can represent a very large range of numbers, from 0 up to 340,282,366,920,938,463,463,374,607,431,768,211,455 (2^128 - 1). Only the least significant 16 bits are shown for simplicity.') 19 | h4(''' 20 | | Decimal | Binary (only showing least significant 16 bits for brevity) | 21 | |---------|------------------------------------------------------------| 22 | | 0 | 0000000000000000 | 23 | | 1 | 0000000000000001 | 24 | | 2 | 0000000000000010 | 25 | | ... | ... | 26 | | 10 | 0000000000001010 | 27 | ''') -------------------------------------------------------------------------------- /src/problems/palindrome.py: -------------------------------------------------------------------------------- 1 | from testUtils import print_and_assert, getTestResult, solution_title 2 | from stylepy import h1,h2,h3,h4 3 | h1('\n >>> Is Palindrome Example') 4 | h2('\n >>> The concept of a palindrome focuses solely on the sequence of characters, disregarding spaces and letter casing.') 5 | h3(' >>> palindrome(word)') 6 | 7 | class palindromSolutions(object): 8 | def using_string_solution(self, word): 9 | return word[::-1] 10 | 11 | def using_iteration_with_range(self, word): 12 | last_index = len(word) - 1 13 | text = '' 14 | for i in range(last_index, -1, -1): 15 | text += word[i] 16 | return text 17 | 18 | palindrome = palindromSolutions() 19 | using_string_solution = palindrome.using_string_solution 20 | solution_title('Using String Slicing') 21 | print_and_assert(using_string_solution, 'madam', 'madam') 22 | print_and_assert(using_string_solution, 'kayak', 'kayak') 23 | # print_and_assert(using_string_solution, 'EVIL OLIVE', 'EVIL OLIVE') 24 | # print_and_assert(using_string_solution, 'DO GEESE SEE GOD', 'DO GEESE SEE GOD') 25 | 26 | getTestResult('Simple Palindrome') 27 | 28 | # using_iteration_with_range = palindrome.using_iteration_with_range 29 | # solution_title('Using Iteration with Range') 30 | # print_and_assert(using_iteration_with_range, 'madam', 'madam') 31 | # print_and_assert(using_string_solution, 'kayak', 'kayak') 32 | # print_and_assert(using_string_solution, 'EVIL OLIVE', 'EVIL OLIVE') 33 | # # print_and_assert(using_string_solution, 'DO GEESE SEE GOD', 'DO GEESE SEE GOD') 34 | 35 | # getTestResult('Using Iteration with Range') 36 | 37 | -------------------------------------------------------------------------------- /src/basics/errors.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | 3 | h1('\nSyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers') 4 | 5 | print("\nModuleNotFoundError: No module named 'utils'") 6 | h5("soluton: \nimport sys \n sys.path.append('../')") 7 | 8 | h5("\n ImportError: cannot import name 'failure_count' from 'testUtils'") 9 | h6("Soluton: Actual issue, function was missing") 10 | 11 | h5("SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?") 12 | 13 | h6('TypeError: can only concatenate str (not "int") to str') 14 | 15 | h5("NameError: name 'hoistedVariable' is not defined") 16 | h6('undefined errors') 17 | 18 | h5("TypeError: greet() missing 1 required positional argument: 'name'") 19 | 20 | h6('SyntaxError: non-default argument follows default argument') 21 | 22 | h5("TypeError: isEligibleToVote() missing 1 required positional argument: 'aaaa'") 23 | h6('Solution: We should provide default value else it will be considered required parameter') 24 | 25 | h5('ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5000 digits; use sys.set_int_max_str_digits() to increase the limit') 26 | h6('Solution: you need to set like `sys.set_int_max_str_digits(10000)`') 27 | 28 | h5('SyntaxError: trailing comma not allowed without surrounding parentheses') 29 | h6('Import statement should not end with comma') 30 | 31 | h5("AttributeError: 'str' object has no attribute 'reversed'") 32 | h6('There is no method called reversed') 33 | 34 | h5("TypeError: 'palindromSolutions' object is not callable") 35 | h6("when you simply try to call the class as function") -------------------------------------------------------------------------------- /src/data_structures/queue/queue_list.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | class Queue: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def enqueue(self, item): 7 | """Add an item to the end of the queue.""" 8 | self.items.append(item) 9 | 10 | def dequeue(self): 11 | """Remove and return the first item from the queue.""" 12 | if not self.is_empty(): 13 | return self.items.pop(0) 14 | else: 15 | h4("Queue is empty") 16 | return None 17 | 18 | def is_empty(self): 19 | """Check if the queue is empty.""" 20 | return len(self.items) == 0 21 | 22 | def size(self): 23 | """Return the number of items in the queue.""" 24 | return len(self.items) 25 | 26 | def peek(self): 27 | """Return the first item in the queue without removing it.""" 28 | if not self.is_empty(): 29 | return self.items[0] 30 | else: 31 | h4("Queue is empty") 32 | return None 33 | 34 | # Example usage: 35 | if __name__ == "__main__": 36 | grocery_queue = Queue() 37 | h4("Initial queue:", grocery_queue.items) 38 | 39 | # Adding people to the queue 40 | grocery_queue.enqueue("Venkat") 41 | grocery_queue.enqueue("Suba") 42 | grocery_queue.enqueue("Gutti") 43 | h4("Queue after adding people:", grocery_queue.items) 44 | 45 | # Serving people from the queue 46 | serving_person = grocery_queue.dequeue() 47 | h4("Serving:", serving_person) 48 | h4("Queue after serving:", grocery_queue.items) 49 | 50 | # Checking the next person to be served 51 | next_person = grocery_queue.peek() 52 | h4("Next person to be served:", next_person) 53 | -------------------------------------------------------------------------------- /src/operators/bit_wise/shift_left/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py operators/bit_wise/shift_left/basics.py 2 | 3 | import data_types.commonUtils as utils 4 | 5 | utils.print_h1('Shift Left Basics') 6 | 7 | utils.print_h2('Shift Left can be used in ..') 8 | utils.print_ordered_list([ 9 | 'Efficient Multiplication', 10 | 'Power of Two Operations', 11 | 'Setting and Clearing Bits' 12 | ]) 13 | 14 | utils.print_h2('Using Leet code problems ..') 15 | utils.print_ordered_list([ 16 | 'Two Sum', 17 | 'Valid Parentheses', 18 | 'Maximum Subarray', 19 | 'LRU Cache', 20 | 'Middle of Linked List' 21 | ]) 22 | 23 | n = 1 24 | original_value = 3 25 | # original_value * (2^n) 26 | multiplication_without_shift_operator = original_value * 2**n 27 | multiplication_with_shift_left_operator = original_value << n 28 | 29 | print('\n') 30 | print('n is', n, ' = multiplication_without_shift_operator: ', multiplication_without_shift_operator) 31 | print('n is', n, ' = multiplication_with_shift_left_operator: ', multiplication_with_shift_left_operator) 32 | 33 | 34 | m = 2 35 | multiplication_without_shift_operator_m = original_value * 2**m 36 | multiplication_with_shift_operator_m = original_value << m 37 | 38 | print('m is', m, ' = multiplication_without_shift_operator_m: ', multiplication_without_shift_operator_m) 39 | print('m is', m, ' = multiplication_with_shift_operator_m: ', multiplication_with_shift_operator_m) 40 | 41 | print(''' 42 | | Decimal | Binary | 43 | |---------|--------| 44 | | 0 | 0000 | 45 | | 1 | 0001 | 46 | | 2 | 0010 | 47 | | 3 | 0011 | 48 | | 4 | 0100 | 49 | | 5 | 0101 | 50 | | 6 | 0110 | 51 | | 7 | 0111 | 52 | | 8 | 1000 | 53 | | 9 | 1001 | 54 | | 10 | 1010 | 55 | | 11 | 1011 | 56 | | 12 | 1100 | 57 | ''') -------------------------------------------------------------------------------- /src/basics/if.md: -------------------------------------------------------------------------------- 1 | # Statement Example 2 | 3 | ## isEligibleToVote Function with Passing Age 4 | 5 | This section demonstrates a simple function to check if someone is eligible to vote based on their age. 6 | 7 | ### Function Definition 8 | ```python 9 | def isEligibleToVote(age: int = 0) -> None: 10 | try: 11 | if age > 0 and age < 21: 12 | print(str(age) + ' Wow, You will be soon eligible to vote') 13 | elif age > 21: 14 | print(str(age) + ' Congrats, You are eligible to vote!') 15 | else: 16 | print(str(age) + ' Invalid `age` parameter') 17 | except Exception as e: 18 | print('Got error for param "' + age + '"\nError is ', e) 19 | ``` 20 | 21 | ### Example Usage 22 | 23 | #### Passing Nothing (Default Parameter) 24 | By default, if no parameter is passed, the default value of `age = 0` is used. 25 | ```python 26 | isEligibleToVote() 27 | ``` 28 | **Output:** 29 | ``` 30 | 0 Invalid `age` parameter 31 | ``` 32 | 33 | #### Passing `16` as Parameter 34 | ```python 35 | isEligibleToVote(16) 36 | ``` 37 | **Output:** 38 | ``` 39 | 16 Wow, You will be soon eligible to vote 40 | ``` 41 | 42 | #### Passing `19` as Parameter 43 | ```python 44 | isEligibleToVote(19) 45 | ``` 46 | **Output:** 47 | ``` 48 | 19 Wow, You will be soon eligible to vote 49 | ``` 50 | 51 | #### Passing `25` as Parameter 52 | ```python 53 | isEligibleToVote(25) 54 | ``` 55 | **Output:** 56 | ``` 57 | 25 Congrats, You are eligible to vote! 58 | ``` 59 | 60 | #### Passing Empty String as Parameter 61 | When passing an empty string, it throws a `TypeError` because comparison between a string and an integer is not supported. 62 | ```python 63 | isEligibleToVote('') 64 | ``` 65 | **Output:** 66 | ``` 67 | Got error for param "" 68 | Error is '<' not supported between instances of 'str' and 'int' 69 | ``` 70 | 71 | -------------------------------------------------------------------------------- /src/leetcode/palindrome_number.py: -------------------------------------------------------------------------------- 1 | 2 | from tabulate import tabulate 3 | class Solution: 4 | #log10(n) 5 | def brute_force(self, x: int) -> bool: 6 | number_str = str(number) 7 | reversed_str = number_str[::-1] 8 | return number_str == reversed_str 9 | 10 | #log10(n) 11 | def is_palindrome_suboptimal(number): 12 | number_str = str(number) 13 | for i in range(len(number_str) // 2): 14 | if number_str[i] != number_str[len(number_str) - 1 - i]: 15 | return False 16 | return True 17 | 18 | #log10(n)) 19 | def isPalindrome(self, x: int) -> bool: 20 | number = x 21 | reversed = 0 22 | while(x != 0 ): 23 | digit = x % 10 24 | reversed = reversed * 10 + digit 25 | x = x // 10 26 | return reversed == number 27 | 28 | a = Solution() 29 | number = 121 30 | is_valid = a.isPalindrome(x = number) 31 | print(f"given numbe {number} is {'Palindrome' if is_valid else 'Not palidrome'} ") 32 | 33 | 34 | def print_solution_table(solutions_info): 35 | table = tabulate(solutions_info, headers="keys", tablefmt="pipe") 36 | print(table) 37 | 38 | # Example usage 39 | solutions_info = [ 40 | {"Solution": "Brute-Force (String Conversion)", "Time Complexity": "O(log10(n))", "Space Complexity": "O(log10(n))", "Notes": "Conversion to string and comparison of reversed string contribute to time and space."}, 41 | {"Solution": "Suboptimal", "Time Complexity": "O(log10(n))", "Space Complexity": "O(1)", "Notes": "Iterating over half of the string, but potential issues with odd-length strings."}, 42 | {"Solution": "Optimized", "Time Complexity": "O(log10(n))", "Space Complexity": "O(1)", "Notes": "Direct comparison of digits without converting to a string, more efficient overall."}, 43 | ] 44 | print_solution_table(solutions_info) 45 | -------------------------------------------------------------------------------- /src/data_structures/queue/basics_queue.py: -------------------------------------------------------------------------------- 1 | print(""" 2 | Queue Class: 3 | The basic FIFO queue. It is often used for thread-safe communication between threads in a multithreaded environment. 4 | Example: from queue import Queue 5 | """) 6 | 7 | from queue import Queue 8 | 9 | class CustomQueue: 10 | def __init__(self): 11 | self.queue = Queue() 12 | 13 | def enqueue(self, item): 14 | """Add an item to the end of the queue.""" 15 | self.queue.put(item) 16 | 17 | def dequeue(self): 18 | """Remove and return the first item from the queue.""" 19 | if not self.is_empty(): 20 | return self.queue.get() 21 | else: 22 | print("Queue is empty") 23 | return None 24 | 25 | def is_empty(self): 26 | """Check if the queue is empty.""" 27 | return self.queue.empty() 28 | 29 | def size(self): 30 | """Return the number of items in the queue.""" 31 | return self.queue.qsize() 32 | 33 | def peek(self): 34 | """Return the first item in the queue without removing it.""" 35 | if not self.is_empty(): 36 | return self.queue.queue[0] 37 | else: 38 | print("Queue is empty") 39 | return None 40 | 41 | # Example usage: 42 | if __name__ == "__main__": 43 | grocery_queue = CustomQueue() 44 | print("Initial queue:", list(grocery_queue.queue.queue)) 45 | 46 | # Adding people to the queue 47 | grocery_queue.enqueue("Venkat") 48 | grocery_queue.enqueue("Suba") 49 | grocery_queue.enqueue("Gutti") 50 | print("Queue after adding people:", list(grocery_queue.queue.queue)) 51 | 52 | # Serving people from the queue 53 | serving_person = grocery_queue.dequeue() 54 | print("Serving:", serving_person) 55 | print("Queue after serving:", list(grocery_queue.queue.queue)) 56 | 57 | # Checking the next person to be served 58 | next_person = grocery_queue.peek() 59 | print("Next person to be served:", next_person) 60 | -------------------------------------------------------------------------------- /src/data_structures/queue/queue_lifo.py: -------------------------------------------------------------------------------- 1 | print(""" 2 | LifoQueue Class: 3 | A Last In, First Out (LIFO) queue, also known as a stack. It is useful when you need a stack-like behavior. 4 | Example: from queue import LifoQueue 5 | """) 6 | from queue import LifoQueue 7 | 8 | class CustomLifoQueue: 9 | def __init__(self): 10 | self.queue = LifoQueue() 11 | 12 | def enqueue(self, item): 13 | """Add an item to the end of the queue.""" 14 | self.queue.put(item) 15 | 16 | def dequeue(self): 17 | """Remove and return the last item from the queue.""" 18 | if not self.is_empty(): 19 | return self.queue.get() 20 | else: 21 | print("Queue is empty") 22 | return None 23 | 24 | def is_empty(self): 25 | """Check if the queue is empty.""" 26 | return self.queue.empty() 27 | 28 | def size(self): 29 | """Return the number of items in the queue.""" 30 | return self.queue.qsize() 31 | 32 | def peek(self): 33 | """Return the last item in the queue without removing it.""" 34 | if not self.is_empty(): 35 | return self.queue.queue[-1] 36 | else: 37 | print("Queue is empty") 38 | return None 39 | 40 | # Example usage: 41 | if __name__ == "__main__": 42 | grocery_queue = CustomLifoQueue() 43 | print("Initial queue:", list(grocery_queue.queue.queue)) 44 | 45 | # Adding people to the queue 46 | grocery_queue.enqueue("Venkat") 47 | grocery_queue.enqueue("Suba") 48 | grocery_queue.enqueue("Gutti") 49 | print("Queue after adding people:", list(grocery_queue.queue.queue)) 50 | 51 | # Serving people from the queue 52 | serving_person = grocery_queue.dequeue() 53 | print("Serving:", serving_person) 54 | print("Queue after serving:", list(grocery_queue.queue.queue)) 55 | 56 | # Checking the next person to be served 57 | next_person = grocery_queue.peek() 58 | print("Next person to be served:", next_person) 59 | -------------------------------------------------------------------------------- /src/utilities/testUtils.py: -------------------------------------------------------------------------------- 1 | failures = 0 2 | 3 | def flag_failure(): 4 | global failures 5 | failures = (failures or 0) + 1 6 | 7 | def failure_count(): 8 | return failures 9 | 10 | def solution_title(title): 11 | print('=' * 70) 12 | print(f'>>> {title}') 13 | print('=' * 70) 14 | 15 | def reason_points(title): 16 | print(f'How ?{title}') 17 | 18 | def print_and_assert(function_name, param, expected): 19 | try: 20 | assert function_name(param) == expected 21 | print(f'✅ Pass: {function_name.__name__}({param}) is returning {expected} as expected') 22 | except AssertionError: 23 | flag_failure() 24 | print(f'❌ AssertionError: {function_name.__name__}({param}) is returning {function_name(param)} but `{expected}` is expected') 25 | 26 | def print_and_assert_new(function_name, *params, expected): 27 | try: 28 | assert function_name(*params) == expected 29 | print(f'✅ Pass: {function_name.__name__}{params} is returning {expected} as expected') 30 | except AssertionError: 31 | flag_failure() 32 | print(f'❌ AssertionError: {function_name.__name__}{params} is returning {function_name(*params)} but `{expected}` is expected') 33 | 34 | def print_and_assert_reference(function_name, *params, expected, param_index = 0): 35 | try: 36 | function_name(*params) 37 | assert params[param_index] == expected 38 | print(f'✅ Pass: {function_name.__name__}{params} is returning {expected} as expected') 39 | except AssertionError: 40 | flag_failure() 41 | print(f'❌ AssertionError: {function_name.__name__}{params} is returning {params[param_index]} but `{expected}` is expected') 42 | 43 | def getTestResult(testName): 44 | if (failure_count() > 0): 45 | print(f"{failure_count()} Failure in {testName} tests") 46 | else: 47 | print(f"{testName} tests are passed!") -------------------------------------------------------------------------------- /src/bits/data_type_bit_sizes.md: -------------------------------------------------------------------------------- 1 | # Data Type Bit Sizes 2 | 3 | #### 4 | | Data Type | Typical Maximum Bits | Notes | 5 | |------------|----------------------------|-------------------------------------------------| 6 | | int | Variable (system-dependent)| Limited by available memory, can be very large. | 7 | | float | 64 | Double-precision float, IEEE 754 standard. | 8 | | complex | 2x64 | Consists of two 64-bit floats. | 9 | | bool | 8 | Typically stored as a byte. | 10 | | str | Variable (system-dependent)| Dependent on length and encoding. | 11 | | bytes | Variable (system-dependent)| Dependent on the length of the sequence. | 12 | | bytearray | Variable (system-dependent)| Similar to bytes, mutable version. | 13 | | list | Variable (system-dependent)| Dependent on the number and types of elements. | 14 | | tuple | Variable (system-dependent)| Dependent on the number and types of elements. | 15 | | set | Variable (system-dependent)| Dependent on the number of elements. | 16 | | dict | Variable (system-dependent)| Dependent on the number of key-value pairs. | 17 | | NoneType | N/A | Represents no value, no associated bit size. | 18 | 19 | ## Notes 20 | 1. The "int" type in Python can handle very large numbers, as its size is dynamic and adjusts based on the value it's holding. 21 | 2. For types like "str", "bytes", "bytearray", "list", "tuple", "set", and "dict", the bit size depends on their content and can vary widely. 22 | 3. "NoneType" does not represent a data storage type and thus does not have an associated bit size. 23 | 4. The sizes for "float" and "complex" are more standardized due to the use of the IEEE 754 standard for floating-point arithmetic. 24 | 25 | -------------------------------------------------------------------------------- /src/defs/print_all_primes.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1 2 | from testUtils import print_and_assert, getTestResult 3 | 4 | def is_prime_using_power_of_point_5(n): 5 | if n <= 1: 6 | return False 7 | # for i in range(2, int(n**0.5) + 1): 8 | for i in range(2, (n//2) + 1): 9 | if n % i == 0: 10 | return False 11 | return True 12 | 13 | def is_prime_using_floor_division(number_in_element): 14 | if number_in_element < 2: 15 | return False 16 | for i in range(2, (number_in_element//2) + 1): 17 | if number_in_element % i == 0: 18 | return False 19 | return True 20 | 21 | def is_prime(number_in_element): 22 | if number_in_element < 2: 23 | return False 24 | for i in range(2, number_in_element): 25 | if number_in_element % i == 0: 26 | return False 27 | return True 28 | 29 | def print_all_primes_from_array(array): 30 | prime_numbers = [] 31 | for k in array: 32 | if is_prime(k): 33 | prime_numbers.append(k) 34 | return prime_numbers 35 | 36 | def print_all_primes_from_range(number_range): 37 | prime_numbers = [] 38 | for k in range(0, number_range + 1): 39 | if is_prime(k): 40 | prime_numbers.append(k) 41 | return prime_numbers 42 | 43 | h1('\n >>> Print All Prime Numbers from Range Test Cases') 44 | print_and_assert(print_all_primes_from_range, 5, [2,3,5]) 45 | print_and_assert(print_all_primes_from_range, 10, [2,3,5,7]) 46 | print_and_assert(print_all_primes_from_range, 20, [2,3,5,7,11,13,17,19]) 47 | print_and_assert(print_all_primes_from_range, 20, [2,3,5,7,11,13,17,19,21]) 48 | getTestResult('Print All Prime Numbers from Range') 49 | 50 | h1('\n >>> Print All Prime Numbers from Input Array Test Cases') 51 | print_and_assert(print_all_primes_from_array, [1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,19,20], [2,3,5,7,11,13,17,19]) 52 | getTestResult('Print All Prime Numbers from Input Array') -------------------------------------------------------------------------------- /src/data_types/numeric/integer/iterations.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/numeric/integer/iterations.py 2 | # python -m data_types.numeric/integer data_types/numeric/integer/iterations.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Integer Iterations') 7 | 8 | utils.print_blockquote([ 9 | 'Types are short, long, int32, int64', 10 | 'Binary, Octal, and Hexadecimal Integers', 11 | 'Underscores in Numeric Literals (Python 3.6+) ex: large_num = 1_000_000' 12 | ]) 13 | 14 | salary = 9000 15 | increment = 500 16 | 17 | print('\n >>>> Iterate using for loop with type casting') 18 | print(' >>>> Follow this approach on demand and Its not recommended') 19 | for text in str(salary): 20 | print(text) 21 | 22 | # print('\n >>>> Iterate using while loop') 23 | # def iterateInteger(integer_number): 24 | # stack = [] 25 | # while integer_number > 0: 26 | # digit = integer_number % 10 27 | # stack.append(digit) 28 | # integer_number //= 10 29 | 30 | # while stack: 31 | # print(stack.pop()) 32 | 33 | # iterateInteger(salary) 34 | 35 | # def iterateInteger(integer_number): 36 | # stack = [] 37 | # while integer_number > 0: 38 | # digit = integer_number % 10 39 | # stack.append(digit) 40 | # integer_number //= 10 41 | 42 | # while stack: 43 | # print(stack.pop()) 44 | 45 | def find_digit_position(number, digit_to_find): 46 | original_number = number 47 | position = 1 48 | while number >= 10: 49 | if number % 10 == digit_to_find: 50 | return len(str(original_number)) - position + 1 51 | number //= 10 52 | position += 1 53 | # Check the last digit 54 | return 1 if number == digit_to_find else -1 55 | 56 | # Test the function with the number 9000 and digit 9 57 | find_digit_position_number = 8778890942 58 | find_number = 0 59 | print(f'Position of {find_number} from {find_digit_position_number} is ', find_digit_position(find_digit_position_number, find_number)) 60 | -------------------------------------------------------------------------------- /src/basics/rough.py: -------------------------------------------------------------------------------- 1 | # table = [0] * (7) 2 | # print(table) 3 | 4 | # def using_front_and_back(word): 5 | # mid_point = len(word) // 2 # 5 6 | # last_index = len(word) # 9 7 | 8 | # mid_index = mid_point -1 9 | # first_part = '' 10 | # second_part = '' 11 | # for rest_index in range(last_index - 1, mid_point - 1, -1): 12 | # # print(f'i: {mid_index} {word[mid_index]} and j: {rest_index} {word[rest_index]}') 13 | # first_part += word[rest_index] 14 | # second_part += word[mid_index] 15 | # mid_index -= 1 16 | 17 | # return first_part + second_part 18 | 19 | # print(using_front_and_back('EVIL OLIVE')) 20 | # print(using_front_and_back('RISE SIR')) 21 | 22 | # def is_palindrome(): 23 | # start = 0 24 | # end = 9 25 | # word = 'EVIL OLIVE' 26 | 27 | # while start < end: 28 | # if word[start] != word[end]: 29 | # return False 30 | 31 | # start +=1 32 | # end -=1 33 | 34 | 35 | # print('start: ', start, word[start], ' end: ', end, word[end]); 36 | 37 | # def is_palindrome(s): 38 | # s = s.lower() # Convert to lower case, but keep spaces 39 | # start, end = 0, len(s) - 1 40 | 41 | # while start < end: 42 | # # Skip spaces in the start pointer 43 | # while start < end and s[start] == " ": 44 | # start += 1 45 | 46 | # # Skip spaces in the end pointer 47 | # while end > start and s[end] == " ": 48 | # end -= 1 49 | 50 | # # Compare characters 51 | # if s[start] != s[end]: 52 | # return False 53 | 54 | # start += 1 55 | # end -= 1 56 | 57 | # return True 58 | 59 | # phrases = ["EVIL OLIVE", "TACO CAT", "HUH", "DO GEESE SEE GOD", "BORE ME ROB", "RISE SIR", "MADAM", "DIVE VID"] 60 | # results = {phrase: is_palindrome(phrase) for phrase in phrases} 61 | 62 | # print(results) 63 | 64 | 65 | 66 | ''' 67 | Decrement Iteration (9-5) 68 | Additional Index (4-0) 69 | 70 | 20 - 19 71 | 10 72 | 73 | 19-10 = 9 74 | 10 -1 = 9, 0 75 | === 76 | 9-0 77 | ''' -------------------------------------------------------------------------------- /src/basics/error.md: -------------------------------------------------------------------------------- 1 | 2 | # Errors and Solutions Documentation 3 | 4 | ## 1. SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers 5 | 6 | --- 7 | 8 | ## 2. ModuleNotFoundError: No module named 'utils' 9 | 10 | **Solution:** 11 | ```python 12 | import sys 13 | sys.path.append('../') 14 | ``` 15 | 16 | --- 17 | 18 | ## 3. ImportError: cannot import name 'failure_count' from 'testUtils' 19 | 20 | **Solution:** 21 | Actual issue: the function was missing. 22 | 23 | --- 24 | 25 | ## 4. SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...) ? 26 | 27 | --- 28 | 29 | ## 5. TypeError: can only concatenate str (not "int") to str 30 | 31 | --- 32 | 33 | ## 6. NameError: name 'hoistedVariable' is not defined 34 | 35 | **Solution:** 36 | This occurs due to undefined errors. 37 | 38 | --- 39 | 40 | ## 7. TypeError: greet() missing 1 required positional argument: 'name' 41 | 42 | --- 43 | 44 | ## 8. SyntaxError: non-default argument follows default argument 45 | 46 | --- 47 | 48 | ## 9. TypeError: isEligibleToVote() missing 1 required positional argument: 'aaaa' 49 | 50 | **Solution:** 51 | We should provide a default value, or else it will be considered a required parameter. 52 | 53 | --- 54 | 55 | ## 10. ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5000 digits; use sys.set_int_max_str_digits() to increase the limit 56 | 57 | **Solution:** 58 | You need to set the value like: 59 | ```python 60 | sys.set_int_max_str_digits(10000) 61 | ``` 62 | 63 | --- 64 | 65 | ## 11. SyntaxError: trailing comma not allowed without surrounding parentheses 66 | 67 | **Solution:** 68 | The import statement should not end with a comma. 69 | 70 | --- 71 | 72 | ## 12. AttributeError: 'str' object has no attribute 'reversed' 73 | 74 | **Solution:** 75 | There is no method called `reversed` for strings. 76 | 77 | --- 78 | 79 | ## 13. TypeError: 'palindromSolutions' object is not callable 80 | 81 | **Solution:** 82 | This occurs when you try to call the class as a function. 83 | -------------------------------------------------------------------------------- /src/algorithms/search/binary_search.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | def binary_search_in_recursive(input_array, search_value, left, right): 3 | if(left > right): # Reached the end and unable to search. 4 | return False 5 | 6 | mid_point = (left + right) // 2 # 6 is midpoint first time. 7 | if (input_array[mid_point] == search_value): 8 | return True 9 | elif(input_array[mid_point] > search_value): 10 | return binary_search_in_recursive(input_array, search_value, left, mid_point -1) 11 | 12 | return binary_search_in_recursive(input_array, search_value, mid_point + 1, right) 13 | 14 | 15 | def binary_search_in_iterative(input_array, search_value): 16 | left = 0 17 | right = len(input_array) - 1 18 | 19 | while(left <= right): 20 | mid_point = (left + right) // 2 21 | if (input_array[mid_point] == search_value): 22 | return True 23 | elif (input_array[mid_point] > search_value): 24 | right = mid_point - 1 25 | else: 26 | left = mid_point + 1 27 | 28 | return False 29 | 30 | h3(""" 31 | >>> Sample Problem: Imagine you are working with a dataset of recorded temperatures in a city, logged every hour over a week. 32 | This dataset is sorted by the temperature values. You want to find the first occurrence of a specific temperature, say 15°C, in this dataset. 33 | """) 34 | 35 | h1('>>> Binary Search in Recursive'); 36 | 37 | input_array = [10, 11, 12, 13, 14, 15, 15, 15, 16, 17, 18, 19, 20] 38 | left_index = 0 39 | right_index = len(input_array) - 1 40 | print(f"binary_search_in_recursive(19) is {binary_search_in_recursive(input_array, 19, left_index, right_index)}"); 41 | print(f"binary_search_in_recursive(18) is {binary_search_in_recursive(input_array, 18, left_index, right_index)}"); 42 | 43 | h1('\n\n>>> Binary Search in Recursive'); 44 | 45 | print(f"binary_search_in_iterative(15) is {binary_search_in_iterative(input_array, 15)}"); 46 | print(f"binary_search_in_iterative(21) is {binary_search_in_iterative(input_array, 21)}"); -------------------------------------------------------------------------------- /src/data_types/numeric/float/iteration.py: -------------------------------------------------------------------------------- 1 | # Run command - python -m data_types.float.iteration data_types/float/iteration.py 2 | 3 | import data_types.integer.iterations as iterations 4 | 5 | print('\n >>>> Float Iteration Example') 6 | 7 | mark = 78.88 8 | weight = 68.50 9 | height = 6.3 10 | distance = 10.2 11 | price = 27.50 12 | latitude = 40.741895 13 | longitude = -73.989308 14 | 15 | print('\n >>>> Iterate using for loop with type casting to string') 16 | print(' >>>> Follow this approach on demand and Its not recommended') 17 | def iterateAfterTypeCasting(float_number): 18 | formatted_number = "{:.2f}".format(float_number) 19 | for text in formatted_number: 20 | print(text) 21 | 22 | # iterateAfterTypeCasting(mark) 23 | # iterateAfterTypeCasting(weight) 24 | # iterateAfterTypeCasting(height) 25 | # iterateAfterTypeCasting(distance) 26 | # iterateAfterTypeCasting(price) 27 | print('\n >>>> Iterate using while loop with operators') 28 | number = 78.88 29 | 30 | # Handle the integer part 31 | 32 | # # Handle the fractional part 33 | # fractional_part = (number - int(number)) 34 | # fractional_part = int((number - int(number)) * 100) 35 | # rounded_fractional_part = round(fractional_part, 2) 36 | # rounded_fractional_part_2 = int(fractional_part * 100 + 0.5) / 100.0 37 | 38 | # print('fractional_part', fractional_part) 39 | # print('rounded_fractional_part', rounded_fractional_part) 40 | # print('rounded_fractional_part_2', rounded_fractional_part_2) 41 | 42 | def iterateWithoutTypeCasting(float_number): 43 | i=1 44 | 45 | f = float_number 46 | while True: 47 | if round(f, i) * (10**i) - f*(10**i) ==0: 48 | break 49 | i+=1 50 | num = f*(10**i) 51 | 52 | iterations.iterateInteger(int(num)) 53 | 54 | 55 | # iterateWithoutTypeCasting(mark) 56 | # iterateWithoutTypeCasting(weight) 57 | # iterateWithoutTypeCasting(height) 58 | # iterateWithoutTypeCasting(distance) 59 | # iterateWithoutTypeCasting(price) 60 | # iterateWithoutTypeCasting(latitude) 61 | iterateWithoutTypeCasting(longitude) 62 | 63 | # print('\n >>>> Iterate using for loop with range') -------------------------------------------------------------------------------- /src/bits/data_types_bits.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | from stylepy import ordered_list, bullet_list 3 | 4 | h1('Data Type Bit Sizes') 5 | 6 | h4(''' 7 | | Data Type | Typical Maximum Bits | Notes | 8 | |------------|----------------------------|-------------------------------------------------| 9 | | int | Variable (system-dependent)| Limited by available memory, can be very large. | 10 | | float | 64 | Double-precision float, IEEE 754 standard. | 11 | | complex | 2x64 | Consists of two 64-bit floats. | 12 | | bool | 8 | Typically stored as a byte. | 13 | | str | Variable (system-dependent)| Dependent on length and encoding. | 14 | | bytes | Variable (system-dependent)| Dependent on the length of the sequence. | 15 | | bytearray | Variable (system-dependent)| Similar to bytes, mutable version. | 16 | | list | Variable (system-dependent)| Dependent on the number and types of elements. | 17 | | tuple | Variable (system-dependent)| Dependent on the number and types of elements. | 18 | | set | Variable (system-dependent)| Dependent on the number of elements. | 19 | | dict | Variable (system-dependent)| Dependent on the number of key-value pairs. | 20 | | NoneType | N/A | Represents no value, no associated bit size. | 21 | ''') 22 | 23 | h2('Notes') 24 | ordered_list( 25 | [ 26 | 'The "int" type in Python can handle very large numbers, as its size is dynamic and adjusts based on the value it\'s holding.', 27 | 'For types like "str", "bytes", "bytearray", "list", "tuple", "set", and "dict", the bit size depends on their content and can vary widely.', 28 | '"NoneType" does not represent a data storage type and thus does not have an associated bit size.', 29 | 'The sizes for "float" and "complex" are more standardized due to the use of the IEEE 754 standard for floating-point arithmetic.', 30 | ] 31 | ) 32 | -------------------------------------------------------------------------------- /src/data_types/non_linear/dictionaries/collision.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/dictionaries/collision.py 2 | # python -m data_types.dictionaries.collision data_types/dictionaries/collision.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Hashing Basics') 7 | utils.print_ordered_list([ 8 | 'Hashing concepts have been around since the 1950s and cryptography became prominent in the 1970s.' 9 | 'Process of converting an input (of any length) into a fixed-size string of bytes.', 10 | 'Typically for the purpose of security, indexing, or identification.', 11 | 'Output is known as a hash value or hash code.' 12 | 'Used for Data Retrieval in Hash Map / Dictionary, ', 13 | 'Used for Cryptography Security, hashing creates almost-unique identifiers for data for password storage, digital signatures, and message integrity checks', 14 | 'Used for Caching to identify data with unique hash values', 15 | 'Used for Load Balancing, consistent hashing helps in evenly distributing the load.' 16 | ]) 17 | 18 | utils.print_h2('Collision in') 19 | utils.print_ordered_list([ 20 | 'Even Modern programming languages use sophisticated hashing algorithms but collisions can still occur.', 21 | 'According to the Pigeonhole Principle, collisions (where different keys produce the same hash value) are inevitable.', 22 | 'Efficiency of a hashing algorithm lies in minimizing these collisions and dealing with them effectively when they occur.' 23 | ]) 24 | 25 | print(''' 26 | | Language | Hashing Algorithm | 27 | |------------|-----------------------------| 28 | | Python | SipHash | 29 | | Java | Object.hashCode() method (varies based on object; often a variation of DJB2) | 30 | | JavaScript | V8 (Chrome, Node.js): One-at-a-time (variations) | 31 | | | SpiderMonkey (Firefox): DJB2 (variations) | 32 | | | JavaScriptCore (Safari): Engine-specific implementation | 33 | | C# | .NET Framework: Marvin32 (with modifications) | 34 | | Go | AEAD (AES-GCM) based algorithm | 35 | 36 | '''); 37 | 38 | alamelu.gotara@gmail.com 39 | Code@2050 40 | alamelu-gotara -------------------------------------------------------------------------------- /src/basics/b_variable_scope.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | 3 | # Variable Scope 4 | h1('\n >>>> Variable Scope Example') 5 | 6 | # helloWorld Function with outside variable 7 | h2('\n >>>> helloWorld Function with outside variable') 8 | 9 | type = 'World' 10 | def helloWorld(): 11 | h6('Hello ' + type + ' from helloWorld()') 12 | 13 | # Calling the function 14 | helloWorld() 15 | 16 | # helloWorld Function with hoisting variable throws `NameError: name 'hoistedVariable' is not defined` 17 | h6('\n >>>> helloWorld Function with hoisting variable throws `NameError`') 18 | # def helloWorld(): 19 | # print('Hello ' + hoistedVariable + ' from helloWorld()') 20 | 21 | # helloWorld() 22 | # hoistedVariable = 'hoisted world' 23 | 24 | # Greet Function 25 | h4('\n >>>> Greet Function passed with `name` variable') 26 | def greet(name): 27 | print('Hello ' + name) 28 | 29 | # greet() # will throws TypeError: greet() missing 1 required positional argument: 'name' 30 | # print(" >>>> when no parameter passed throws TypeError: greet() missing 1 required positional argument: 'name'") 31 | 32 | h4(" >>>> passing name parameter returns Hello John") 33 | name = 'John' 34 | greet(name) 35 | 36 | # Global Variable 37 | h4('\n >>>> Global and Local Variable Samples') 38 | myAge = 21 39 | 40 | def afterGraduation(): 41 | myAge = 24 42 | # myAge will be overwritten as 24. 43 | h6(f"inside afterGraduation: I'm {myAge} years old") 44 | 45 | # myAge will return global value 21. 46 | h6(f"outside before afterGraduation call: I'm {myAge} year old") 47 | afterGraduation() 48 | h6(f"outside after afterGraduation call: I'm {myAge} year old") 49 | 50 | # Global Variable with global keyword. 51 | h4('\n >>>> Global Variable with global keyword') 52 | 53 | manhood = "bachelor" 54 | 55 | def afterMarriage(): 56 | global manhood 57 | h6(f"inside afterMarriage before change: I'm {manhood}") 58 | manhood = "Husband" 59 | h6(f"inside afterMarriage after change: I'm {manhood}") 60 | 61 | # manhood will return global value Husband. 62 | h6(f"outside before afterMarriage: I'm {manhood}") 63 | afterMarriage() 64 | h6(f"outside after afterMarriage: I'm {manhood}") -------------------------------------------------------------------------------- /src/math/NumberSystem.md: -------------------------------------------------------------------------------- 1 | ## Number System 2 | 3 | | Serial No. | System | Historical/Modern | Base | Digits | Simple Example | Real-Time Usage or First Known Usage | 4 | |------------|-------------------|----------------------|------|-----------------------------------------------------|---------------------|-----------------------------------------------------------| 5 | | 1 | Binary | Modern | 2 | 0, 1 | 1011 (Binary) | Fundamental in digital computing, electronic circuits | 6 | | 2 | Ternary | Historical | 3 | 0, 1, 2 | 210 (Ternary) | Historical and less common, not widely used in computing | 7 | | 3 | Quaternary | Historical | 4 | 0, 1, 2, 3 | 32 (Quaternary) | Ancient Mayans used a base-4 system in their calendar | 8 | | 4 | Octal | Modern | 8 | 0, 1, 2, 3, 4, 5, 6, 7 | 765 (Octal) | Early computers, Unix file permissions | 9 | | 5 | Decimal | Modern | 10 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | 456 (Decimal) | Everyday arithmetic, used universally | 10 | | 6 | Duodecimal | Historical | 12 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B | 7A (Duodecimal) | Historical, used in ancient cultures | 11 | | 7 | Hexadecimal | Modern | 16 | 0-9, A-F | 1A3 (Hexadecimal) | Memory addressing in computing, color representation | 12 | | 8 | Sexagesimal | Historical | 60 | 0-9, A-Z, a-z | 2J (Sexagesimal) | Time measurement, ancient Babylonian numeral system | 13 | | 9 | Roman Numerals | Historical | - | I, V, X, L, C, D, M | XIV (Roman) | Ancient Rome, used for numbering, timekeeping, inscriptions | 14 | -------------------------------------------------------------------------------- /src/leetcode/__template__.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> 00. ') 5 | print(''' 6 | Desc goes here 7 | ''') 8 | 9 | class ProblemName(object): 10 | def quick(self, s): 11 | pass 12 | def brute_force(self, s): 13 | pass 14 | def sub_optimal(self, s): 15 | pass 16 | def optimal(self, s): 17 | pass 18 | 19 | # Parameters and Expected Values. 20 | param1 = 'param1' 21 | param11 = 'param11' 22 | expect1 = 'expect1' 23 | 24 | param2 = 'param2' 25 | param22 = 'param22' 26 | expect2 = 'expect2' 27 | 28 | param3 = 'param3' 29 | param33 = 'param33' 30 | expect3 = 'expect3' 31 | 32 | solution = ProblemName() 33 | solution_title('ProblemName - Quick One') 34 | print_and_assert_new(solution.quick, param1, param11, expected=expect1) 35 | print_and_assert_new(solution.quick, param2, param22, expected=expect2) 36 | print_and_assert_new(solution.quick, param3, param33, expected=expect3) 37 | getTestResult('ProblemName - Quick One') 38 | 39 | timeComplexity('O(n)', 'desc_goes_here') 40 | spaceComplexity('O(n)', 'desc_goes_here') 41 | 42 | solution_title('ProblemName - Brute Force') 43 | print_and_assert_new(solution.brute_force, param1, param11, expected=expect1) 44 | print_and_assert_new(solution.brute_force, param2, param22, expected=expect2) 45 | print_and_assert_new(solution.brute_force, param3, param33, expected=expect3) 46 | getTestResult('ProblemName - Brute Force') 47 | 48 | timeComplexity('O(n)', 'desc_goes_here') 49 | spaceComplexity('O(n)', 'desc_goes_here') 50 | 51 | solution_title('ProblemName - Sub Optimal') 52 | print_and_assert_new(solution.sub_optimal, param1, param11, expected=expect1) 53 | print_and_assert_new(solution.sub_optimal, param2, param22, expected=expect2) 54 | print_and_assert_new(solution.sub_optimal, param3, param33, expected=expect3) 55 | getTestResult('ProblemName - Sub Optimal') 56 | 57 | timeComplexity('O(n)', 'desc_goes_here') 58 | spaceComplexity('O(n)', 'desc_goes_here') 59 | 60 | solution_title('ProblemName - Optimal') 61 | print_and_assert_new(solution.optimal, param1, param11, expected=expect1) 62 | print_and_assert_new(solution.optimal, param2, param22, expected=expect2) 63 | print_and_assert_new(solution.optimal, param3, param33, expected=expect3) 64 | getTestResult('ProblemName - Optimal') 65 | 66 | timeComplexity('O(n + m)', 'desc_goes_here') 67 | spaceComplexity('O(n + m)', 'desc_goes_here') -------------------------------------------------------------------------------- /src/leetcode/first_unique_character.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | from collections import Counter 3 | 4 | def first_uniq_char_brute1(s: str) -> int: 5 | count_char = {i: s.count(s[i]) for i in range(len(s)) } 6 | for index, count in count_char.items(): 7 | if count == 1: 8 | return index 9 | return -1 10 | 11 | def first_uniq_char_brute2(s: str) -> int: 12 | count_char = Counter(s) 13 | stack = {} 14 | for i in range(len(s)): 15 | if s[i] not in stack: 16 | stack[s[i]] = i 17 | char = next((char for char, count in count_char.items() if count == 1), -1 ) 18 | return stack[char] if char in stack else -1 19 | 20 | def first_uniq_char_optimised(s: str) -> int: 21 | result = next((i for i in range(len(s)) if s.count(s[i])==1), -1 ) 22 | return result 23 | 24 | def first_uniq_char_optimised2(s: str) -> int: 25 | for i in range(len(s)): 26 | if s.count(s[i]) == 1: 27 | return i 28 | return -1 29 | 30 | h1("Brute-force 1") 31 | s = 'leetcode' 32 | index = first_uniq_char_brute1(s) 33 | h3(f"first non repeating character index {index} for {s} ") 34 | 35 | s = 'loveleetcode' 36 | index = first_uniq_char_brute1(s) 37 | h3(f"first non repeating character index {index} for {s} ") 38 | 39 | s = 'aabb' 40 | index = first_uniq_char_brute1(s) 41 | h3(f"first non repeating character index {index} for {s} ") 42 | 43 | h1("Brute-force 2") 44 | s = 'leetcode' 45 | index = first_uniq_char_brute2(s) 46 | h3(f"first non repeating character index {index} for {s} ") 47 | 48 | s = 'loveleetcode' 49 | index = first_uniq_char_brute2(s) 50 | h3(f"first non repeating character index {index} for {s} ") 51 | 52 | s = 'aabb' 53 | index = first_uniq_char_brute2(s) 54 | h3(f"first non repeating character index {index} for {s} ") 55 | 56 | 57 | h1("Optimised") 58 | s = 'leetcode' 59 | index = first_uniq_char_optimised(s) 60 | h3(f"first non repeating character index {index} for {s} ") 61 | 62 | s = 'loveleetcode' 63 | index = first_uniq_char_optimised(s) 64 | h3(f"first non repeating character index {index} for {s} ") 65 | 66 | s = 'aabb' 67 | index = first_uniq_char_optimised(s) 68 | h3(f"first non repeating character index {index} for {s} ") 69 | 70 | 71 | h1("Optimised 2 ") 72 | s = 'leetcode' 73 | index = first_uniq_char_optimised2(s) 74 | h3(f"first non repeating character index {index} for {s} ") 75 | 76 | s = 'loveleetcode' 77 | index = first_uniq_char_optimised2(s) 78 | h3(f"first non repeating character index {index} for {s} ") 79 | 80 | s = 'aabb' 81 | index = first_uniq_char_optimised2(s) 82 | h3(f"first non repeating character index {index} for {s} ") -------------------------------------------------------------------------------- /src/basics/d_data_types.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | from stylepy import blockquote 3 | from stylepy import pretty_json 4 | h1('\n >>>> Data Type Example') 5 | h2('15 Types of Data Types') 6 | h3('>>>> 1st. Text Type') 7 | h4('1. string\n') 8 | h5('>>>> 2nd Numeric Type') 9 | h4('2. int, 3. float, 4. complex\n') 10 | h5('>>>> 3rd Sequence Type') 11 | h4('5. list, 6. tuple, 7. range\n') 12 | h5('>>>> 4th Mapping Type') 13 | h4('8. dict\n') 14 | h5('>>>> 5th Set Type') 15 | h4('9. set, 10. frozenset\n') 16 | h5('>>>> 6th Boolean Type') 17 | h4('11. bool\n') 18 | h5('>>>> 7th Binary Type') 19 | h4('11. bytes, 12. byteArray, 13. memoryView\n') 20 | h5('>>>> 8th None Type') 21 | h4('11. None\n') 22 | 23 | greet = 'welcome' # String 24 | castToString = str(3) 25 | # Find Variable Type 26 | h3(f">>> Type of greet is {type(greet)}") 27 | h4(f">>> Type of castToString is {type(castToString)}") 28 | 29 | # Number Data Type Variables 30 | currentYear = 2024 # int for year 31 | h3(f"\n>>> Type of currentYear is {type(currentYear)}") 32 | castToInteger = int(2024.00) 33 | h4(f">>> Type of castToInteger is {type(castToInteger)}") 34 | 35 | weight = 75.50 # Float for Weight in Kg 36 | h3(f"\n>>> Type of weight is {type(weight)}") 37 | castToFloat = float('75.50') 38 | h4(f">>> Type of castToFloat is {type(castToFloat)}") 39 | 40 | h3("\n>>> List Type") 41 | fruits = ["apple", "banana", "cherry"] # List for fruits 42 | h4(f">>> Type of fruits is {type(fruits)}") 43 | fruits.append("grapes") 44 | h4('Fruits List: ', fruits) 45 | blockquote(fruits) # blockquote 46 | 47 | h3("\n>>> Tuple Type") 48 | configuration = ('2MB','30 Minutes') # Tuple 49 | h6(f">>> Type of configuration is {type(configuration)}") 50 | h6('configuration Tuple: ', configuration) 51 | 52 | h3("\n>>> Dict Type") 53 | employeeDictionary = {"name" : "John", "age" : 36} # Dict 54 | h4(f">>> Type of employeeDictionary is {type(employeeDictionary)}") 55 | h5(employeeDictionary) #pretty json 56 | h6('employee dictionary: ', employeeDictionary) 57 | config = {True : "dummyValue", 1 : "actualConfigValue"} # Dict key value will be same True or 1 so latest value will be overriden. 58 | h6('config dictionary: ', config) 59 | 60 | h3("\n>>> Boolean Type") 61 | eligibleToVote = True # Boolean 62 | h4(f">>> Type of eligibleToVote is {type(eligibleToVote)}") 63 | h5('eligibleToVote: ', eligibleToVote) 64 | 65 | sunRiseToday = 'east' 66 | sunRiseTodayInWest = True if sunRiseToday == 'west' else False 67 | h6(f"\n>>> Type of sunRiseTodayInWest is {sunRiseTodayInWest}") 68 | h6('sunRiseTodayInWest: ', sunRiseTodayInWest) 69 | 70 | # TODO 71 | # Add Bytes 72 | # Add None examples -------------------------------------------------------------------------------- /src/classes/classes_readme.md: -------------------------------------------------------------------------------- 1 | ## Class 2 | 3 | A class should have a properties and methods. 4 | 5 | - Properties are like features 6 | 7 | - Methods are its behaviour or functionalities 8 | 9 | - Class is a back bone of OOP 10 | 11 | keyword: class 12 | 13 | Class is a blue print or skeleton -> assume like there is no physical form 14 | 15 | ## Instance or Object 16 | 17 | Instances should be created to make use of class 18 | 19 | class MyClass: 20 | x=5 21 | 22 | instance_1 = MyClass() 23 | instance_2 = MyClass() 24 | 25 | 26 | ## class built in functions: 27 | 28 | ### \_\_init__() 29 | Built in \_\_init__() Function 30 | 31 | What you want to create when you are creating an object -> All should present inside an \_\_init__() function 32 | -> Assign values to its properties 33 | -> Operations that are necessary to do when the object is created 34 | 35 | ### \_\_str__() 36 | \_\_str__() Function 37 | 38 | It returns how the object can be represented as a string 39 | We can override this by our own 40 | 41 | ## Methods 42 | Behaviour or action: 43 | 44 | Methods: 45 | -> In one line these are object functions, what are all the functions that object can do or it poses 46 | 47 | ## Self 48 | 49 | The self parameter is a refrence to the current instance of the class, 50 | Used to access variables that belongs to the class 51 | 52 | It doesn't have to be named self, we can call it whatever you like 53 | 54 | It should be the first parameter to any function in the class 55 | 56 | ## Delete 57 | Delete the properties of the object 58 | 59 | del p.height 60 | 61 | Delete objects as well 62 | 63 | ## pass 64 | 65 | pass: 66 | class definitions cannot be empty 67 | using pass we can make the content of the class functions can be empty. 68 | 69 | ## Class Internals: 70 | 71 | Programmers can create modular, reusable code that models or represents real-world entities or concepts in an intutive way. 72 | Classes form the backbone object oriented programmingand facilitate the principles of encapsultion, inheritance and polymorphism 73 | 74 | Internals of the class: 75 | 76 | 1. Defining a class: First, you define a class using the 'class' keyword. Python executes the class block, which may contain method definitions, class variables, and other statements 77 | 78 | 2. NameSpace creation: Python creates a namespace where all its attributes and methods are stored. 79 | 3. Class Object Creation: Once the class definition is complete, Python creates a class object and assign it to the name provided after the class, that class allows for object creation 80 | class Creation: First, you define a class using the 'class' keyword. Python 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Basics 2 | Python Basics 3 | 4 | # Data Structure in Python 5 | 6 | | Standard Data Structure | Implementation Note or Python Equivalent | 7 | |-------------------------|----------------------------------------------| 8 | | Array | Implemented as List in Python | 9 | | Stack | Can be implemented using a List with append and pop methods | 10 | | Queue | Can be implemented using collections.deque | 11 | | Priority Queue | Can be implemented using queue.PriorityQueue or heapq | 12 | | Set | Implemented as Set in Python | 13 | | Linked List | No native type; can be implemented using classes with nodes | 14 | | Doubly Linked List | No native type; can be implemented with nodes having previous and next pointers | 15 | | Circular Linked List | No native type; can be implemented with nodes where the last node links to the first | 16 | | Skip List | No native type; can be implemented with multiple levels of linked lists for efficient search | 17 | | Hash Map | Implemented as Dictionary in Python | 18 | | Heap | `heapq` can be used for heap operations in Python | 19 | | Trie | No native type; can be implemented with nodes containing a dictionary of children | 20 | | Binary Tree | No native type; can be implemented using classes with node references | 21 | | Binary Search Tree | No native type; can be implemented with ordered insertion and deletion in a binary tree structure | 22 | | B-Tree | No native type; typically used in databases and file systems; can be implemented using classes with multiple child nodes | 23 | | Red-Black Tree | No native type; can be implemented with self-balancing properties during insertions and deletions | 24 | | AVL Tree | No native type; can be implemented with self-balancing properties based on node heights | 25 | | Graph | No native type; can be implemented with adjacency lists or matrices | 26 | 27 | 28 | 29 | ![python-one-pic](https://github.com/web-slate/python-basics/assets/1652629/b7c0e938-1eab-4259-a098-3cc9cf8d17f2) 30 | 31 | 32 | ## Setup 33 | 34 | ### Setup Virtual Environment 35 | 36 | ``` 37 | python -m venv venv 38 | ``` 39 | 40 | ### Activate Virtual Environment 41 | 42 | | Operating System | Command to Activate Virtual Environment | 43 | |------------------|----------------------------------------| 44 | | Windows | `venv\Scripts\activate` | 45 | | Mac/Linux | `source venv/bin/activate` | 46 | 47 | 48 | ### Install StylePy Module for styling command line output. 49 | 50 | ``` 51 | pip install -r requirements.txt 52 | ``` -------------------------------------------------------------------------------- /src/data_types/string/slicing.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | h1('\n >>>> String Slicing Example') 3 | print('s[start:end] extracts the substring from index start to lesser than end index / end - 1.') 4 | print('s[start:end:step] extracts the substring from index start to lesser than end index / end - 1') 5 | 6 | greet = "welcome" 7 | debit_card = "1234-5678-9012-3456" 8 | slicing_detailed_desc = '''Avul Pakir Jainulabdeen Abdul Kalam BR (/ˈɑːbdəl kəˈlɑːm/ ⓘ; 15 October 1931 – 27 July 2015) was an Indian aerospace scientist and statesman who served as the 11th president of India from 2002 to 2007. He was born and raised in Rameswaram, Tamil Nadu and studied physics and aerospace engineering. He spent the next four decades as a scientist and science administrator, mainly at the Defence Research and Development Organisation (DRDO) and Indian Space Research Organisation (ISRO) and was intimately involved in India's civilian space programme and military missile development efforts.[1] He thus came to be known as the Missile Man of India for his work on the development of ballistic missile and launch vehicle technology.[2][3][4] He also played a pivotal organisational, technical, and political role in India's Pokhran-II nuclear tests in 1998, the first since the original nuclear test by India in 1974.[5]''' 9 | tutorial_site = 'https://webslate.io/blogs/algorithms/big-o-notations' 10 | email_id = 'username@example.com' 11 | phone_number = '+1-800-555-1234' 12 | file_name = 'slicing.pdf' 13 | transaction_timestamp = '2023-01-15 09:30:00' 14 | 15 | h4('\n >>>> Get last four digit of debit card', '[-4:]') 16 | print(debit_card[-4:]) 17 | 18 | h4('\n >>>> Get short description from long string', '[:140]') 19 | print(slicing_detailed_desc[:140], '...') 20 | 21 | h4('\n >>>> Get Mobile Country and Area Code', '[0:6]') 22 | print(phone_number[0:6]) 23 | 24 | h4('\n >>>> Get US Mobile Number without Country Code', '[3:]') 25 | print(phone_number[3:]) 26 | 27 | h4('\n >>>> Get File extension', '[-3]') 28 | print(file_name[-3:]) 29 | 30 | h4('\n >>>> Get Transaction Date', '[0:10]') 31 | print(transaction_timestamp[:10]) 32 | print('\n >>>> Get Transaction Date in DD-MM-YYYY', '[0:10]') 33 | print(f'{transaction_timestamp[8:10]}-{transaction_timestamp[5:7]}-{transaction_timestamp[:4]}') 34 | 35 | h4('\n >>>> Get Transaction Year', '[0:4]') 36 | print(transaction_timestamp[:4]) 37 | 38 | h4('\n >>>> Get Transaction Month', '[5:7]') 39 | print(transaction_timestamp[5:7]) 40 | 41 | h4('\n >>>> Get Transaction Time with seconds', '[-8:] / [11:]') 42 | print(transaction_timestamp[-8:]) 43 | print(transaction_timestamp[11:]) 44 | 45 | h4('\n >>>> Get Transaction hour in Time without seconds', '[-8:-3]') 46 | print(transaction_timestamp[-8:-3]) 47 | 48 | h4('\n >>>> Get Time String Revered', '[::-1]') 49 | print(transaction_timestamp[::-1]) 50 | -------------------------------------------------------------------------------- /src/data_structures/queue/circular.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | print('''''') 3 | h1("Circular Queue") 4 | h2('''A circular queue, also known as a ring buffer, is a data structure that effectively uses an array and operates 5 | like a regular queue with a fixed size. 6 | ''') 7 | class CircularQueue: 8 | def __init__(self, capacity): 9 | self.capacity = capacity 10 | self.queue = [None] * capacity 11 | self.head = 0 12 | self.tail = 0 13 | self.size = 0 14 | 15 | def enqueue(self, item): 16 | if self.size == self.capacity: 17 | #print("Queue is full. Cannot enqueue new item.") - Implementation 1 18 | h4("Queue is full. Overwriting the oldest element.") # Implementation 2 19 | self.dequeue() 20 | self.queue[self.tail] = item 21 | self.tail = (self.tail + 1) % self.capacity # ( 1 % 4 = 1, 2 % 4 = 2, ... 4/4 = 0 ) 22 | self.size += 1 23 | 24 | def dequeue(self): 25 | if self.size == 0: 26 | h4("Queue is empty") 27 | return None 28 | item = self.queue[self.head] 29 | self.head = (self.head + 1) % self.capacity 30 | self.size -= 1 31 | return item 32 | 33 | def peek(self): 34 | if self.size == 0: 35 | h4("Queue is empty") 36 | return None 37 | return self.queue[self.head] 38 | 39 | def display(self): 40 | if self.size == 0: 41 | h4("Queue is empty") 42 | return 43 | temp = self.head 44 | resources = [] 45 | for _ in range(self.size): 46 | resources.append(self.queue[temp]) 47 | temp = (temp + 1) % self.capacity 48 | return resources 49 | 50 | 51 | # Example usage 52 | h3("Database connection pool is initaiated to accommodate 5 resource") 53 | cq = CircularQueue(5) 54 | h4("Resource 1 of 5 is connected") 55 | cq.enqueue("Resource 1") 56 | h4("Resource 2 of 5 is connected") 57 | cq.enqueue("Resource 2") 58 | h4("Resource 3 of 5 is connected") 59 | cq.enqueue("Resource 3") 60 | h4("Resource 4 of 5 is connected") 61 | cq.enqueue("Resource 4") 62 | h4("Resource 5 of 5 is connected") 63 | cq.enqueue("Resource 5") 64 | 65 | h3("Display the pool resource") 66 | h4(cq.display()) # Output: 1 2 3 4 5 67 | 68 | 69 | h3("Which resource will get drop its connect next?") 70 | h4(cq.peek()) 71 | 72 | h3("Resource 6 is trying to connect") 73 | cq.enqueue("Resource 6") # Output: Queue is full. Cannot enqueue new item. 74 | h4(cq.display()) # Output: 1 2 3 4 5 75 | 76 | 77 | h3("Resource 1 is dropped its connection") 78 | cq.dequeue() 79 | h4("Display the pool resource") 80 | h4(cq.display()) # Output: 2 3 4 5 81 | 82 | 83 | h3("Resource 6 is trying to connect") 84 | cq.enqueue("Resource 6") 85 | h4("There is available place for acceting new connection. New resource is connected successfully") 86 | 87 | 88 | h3("Display the pool resource") 89 | h4(cq.display()) # Output: 2 3 4 5 6 90 | -------------------------------------------------------------------------------- /src/basics/variable_scope.md: -------------------------------------------------------------------------------- 1 | # Variable Scope in Python 2 | 3 | ## Variable Scope Example 4 | 5 | ## helloWorld Function with Outside Variable 6 | 7 | The function `helloWorld()` uses an outside variable called `type`. 8 | 9 | ```python 10 | # helloWorld Function with outside variable 11 | type = 'World' 12 | def helloWorld(): 13 | print('Hello ' + type + ' from helloWorld()') 14 | 15 | # Calling the function 16 | helloWorld() 17 | ``` 18 | 19 | ## helloWorld Function with Hoisting Variable 20 | 21 | If we try to access a variable before its declaration within a function, Python will throw a `NameError` because variable hoisting is not supported. 22 | 23 | ```python 24 | # This code throws a NameError due to the use of a hoisted variable 25 | # def helloWorld(): 26 | # print('Hello ' + hoistedVariable + ' from helloWorld()') 27 | 28 | # helloWorld() 29 | # hoistedVariable = 'hoisted world' 30 | ``` 31 | 32 | ## Greet Function with Parameter 33 | 34 | A function that requires an argument throws a `TypeError` if no argument is provided. 35 | 36 | ```python 37 | # Greet Function 38 | name = 'John' 39 | def greet(name): 40 | print('Hello ' + name) 41 | 42 | # Uncommenting this line will throw an error 43 | # greet() # TypeError: greet() missing 1 required positional argument: 'name' 44 | 45 | # Correct usage 46 | greet(name) 47 | ``` 48 | 49 | ## Global and Local Variable Samples 50 | 51 | Python allows functions to define variables that may shadow variables from the outer/global scope. 52 | 53 | ```python 54 | myAge = 21 55 | 56 | def afterGraduation(): 57 | myAge = 24 # myAge will be overwritten locally as 24. 58 | print(f"Inside afterGraduation: I'm {myAge} years old") 59 | 60 | print(f"Outside before afterGraduation call: I'm {myAge} year old") 61 | afterGraduation() 62 | print(f"Outside after afterGraduation call: I'm {myAge} year old") 63 | ``` 64 | 65 | ### Output: 66 | ``` 67 | Outside before afterGraduation call: I'm 21 year old 68 | Inside afterGraduation: I'm 24 years old 69 | Outside after afterGraduation call: I'm 21 year old 70 | ``` 71 | 72 | ## Global Variable with `global` Keyword 73 | 74 | To modify a global variable inside a function, you must use the `global` keyword. 75 | 76 | ```python 77 | manhood = "bachelor" 78 | 79 | def afterMarriage(): 80 | global manhood 81 | print(f"Inside afterMarriage before change: I'm {manhood}") 82 | manhood = "Husband" 83 | print(f"Inside afterMarriage after change: I'm {manhood}") 84 | 85 | print(f"Outside before afterMarriage: I'm {manhood}") 86 | afterMarriage() 87 | print(f"Outside after afterMarriage: I'm {manhood}") 88 | ``` 89 | 90 | ### Output: 91 | ``` 92 | Outside before afterMarriage: I'm bachelor 93 | Inside afterMarriage before change: I'm bachelor 94 | Inside afterMarriage after change: I'm Husband 95 | Outside after afterMarriage: I'm Husband 96 | ``` 97 | 98 | -------------------------------------------------------------------------------- /src/problems/fibonacci.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | import time 3 | 4 | def getMinutes(elapsed_time): 5 | minutes = int(elapsed_time // 60) 6 | return minutes 7 | 8 | def getSeconds(elapsed_time): 9 | seconds = elapsed_time % 60 10 | return seconds 11 | 12 | # recursive_fibonacci Function 13 | h1('\n >>>> recursive_fibonacci Function to return fibonacci until n'); 14 | h3('\n This one time complexity is O(2^n) Exponential and have redundant calculations'); 15 | 16 | def recursive_fibonacci(n): 17 | if (n < 2): 18 | return n; 19 | 20 | return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2); 21 | 22 | start_time = time.time() # Start time 23 | n = 41; 24 | h4('Note: Recursive approach without memoization is highly inefficient for large values of n due to the exponential growth of recursive calls and redundant computations.'); 25 | h5(f"recursive_fibonacci({n}) is {recursive_fibonacci(n)}"); 26 | end_time = time.time() # End time 27 | 28 | print(f"This function took {getMinutes(end_time - start_time)} minutes and {getSeconds(end_time - start_time):.2f} seconds") 29 | 30 | # memoized_recursive_fibonacci Function 31 | h1('\n >>>> memoized_recursive_fibonacci Function to return fibonacci until n') 32 | h4('\n This one optimized now so Time and Space Complexity is O(n)') 33 | 34 | def memoized_recursive_fibonacci(n, memoized={0: 0, 1:1}): 35 | if n not in memoized: 36 | memoized[n] = memoized_recursive_fibonacci(n - 1, memoized) + memoized_recursive_fibonacci(n - 2, memoized) 37 | return memoized[n] 38 | 39 | start_time = time.time() # Start time 40 | n = 41 41 | h4(f"memoized_recursive_fibonacci({n}) is {recursive_fibonacci(n)}") 42 | end_time = time.time() # End time 43 | h5(f"This function took {getMinutes(end_time - start_time)} minutes and {getSeconds(end_time - start_time):.2f} seconds") 44 | 45 | # iterative_fibonacci Function 46 | """ 47 | """ 48 | h1('\n >>>> iterative_fibonacci Function to return fibonacci until n') 49 | def iterative_fibonacci(n): 50 | """ 51 | Calculate the nth Fibonacci number using an iterative approach. 52 | 53 | :param n: The position in the Fibonacci sequence. 54 | :return: The Fibonacci number at position n. 55 | """ 56 | if n <= 1: 57 | return n 58 | 59 | prev, curr = 0, 1 # Start with zero and increment by 1. 60 | for i in range(2, n + 1): # iterate until n + 1 if n is 7 it will be 2 to 8 = 6 times 61 | prev, curr = curr, prev + curr 62 | # print(f"prev: {prev} and curr: {curr}") 63 | 64 | return curr 65 | 66 | start_time = time.time() # Start time 67 | n = 7 68 | h4(f"iterative_fibonacci({n}) is {iterative_fibonacci(n)}") 69 | h5('\n This one optimized now so Time Complexity is O(n) and Space Complexity is O(1)'); 70 | end_time = time.time() # End time 71 | h6(f"This function took {getMinutes(end_time - start_time)} minutes and {getSeconds(end_time - start_time):.2f} seconds") 72 | -------------------------------------------------------------------------------- /src/basics/a_basics.py: -------------------------------------------------------------------------------- 1 | # Basic Statement 2 | from stylepy import h1, h2, h3, h4, h5, h6 3 | 4 | h1('\n # Basic Example') 5 | 6 | # Print Statement without parenthesis. 7 | h2('\n >>>> Print Statement without parenthesis throws SyntaxError') 8 | # SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)? 9 | # print "Concatenation with variable" 10 | 11 | # Print Statement 12 | h3('\n >>>> Print Statement ') 13 | h6('hello venkat, welcome to python') 14 | 15 | # Print Statement support comma separated arguments. 16 | h4('\n >>>> Print Statement support n number of comma separated arguments.') 17 | # Maximum number of parameters you can pass to a function like print() 18 | # It is primarily limited by the amount of memory available on your system. 19 | h4('hello venkat,', 'welcome to ', 'python') 20 | 21 | # Concatenation 22 | h5('\n >>>> Print Statement Simple Concatenation') 23 | h6('hello venkat, welcome to python' + '3') 24 | 25 | # Concatenation with int variable 26 | h6('\n >>>> Concatenation with int variable and string throws TypeError') 27 | version = 3 28 | # Your will get TypeError: unsupported operand type(s) for +: 'int' and 'str' 29 | # print(version + 'hello venkat, welcome to python') 30 | # Your will get TypeError: can only concatenate str (not "int") to str. 31 | # print('hello venkat, welcome to python' + version) 32 | h5('\n >>>> Concatenation of int variable and string Issue fix should be with str() function') 33 | # Fix is below. 34 | h6('hello venkat, welcome to python' + str(version)) 35 | 36 | # Concatenation with string variable 37 | h5('\n >>>> Concatenation with string variable') 38 | version = '3' 39 | print('hello venkat, welcome to python' + version) 40 | 41 | # Concatenation with string variable wrapped in String literal. 42 | h5('\n >>>> String variable wrapped in String literal.') 43 | version = '3' 44 | h6(f"hello venkat, welcome to python{version}") 45 | 46 | 47 | # Simple Hello World Function throws IndentationError when function body statement with zero indentation. 48 | h5('\n >>>> Simple Hello World Function throws IndentationError when function body statement with zero indentation.') 49 | h6(' >>>> Fix is 4 tabs after def statement') 50 | def helloWorld(): 51 | # You will get IndentationError: expected an indented block after function definition on line 47 52 | # In Python, the execution order is typically from top to bottom, line by line. 53 | # Python first compiles your code into bytecode before it executes it. During the compilation phase, it checks for syntax errors. 54 | # if there is an IndentationError during compilation anywhere in your code, Python will not execute any part of the script because the error is caught during the compilation phase. 55 | # print('\nHello World from helloWorld()') 56 | h5('\nHello World from helloWorld()') 57 | 58 | # Calling the function 59 | helloWorld() 60 | 61 | fruits = 'Apple' 62 | 63 | h4('\nReversing fruit value using slicing') 64 | h6(fruits[::-1]) -------------------------------------------------------------------------------- /src/leetcode/680_valid_palindrom_II_remove_one_char.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> 680. Valid Palindrome II By Remove One Char') 5 | print(''' 6 | Given a string s, return true if the s can be palindrome after deleting at most one character from it. 7 | Example 1: 8 | 9 | Input: s = "aba" 10 | Output: true 11 | Example 2: 12 | 13 | Input: s = "abca" 14 | Output: true 15 | Explanation: You could delete the character 'c'. 16 | Example 3: 17 | 18 | Input: s = "abc" 19 | Output: false 20 | ''') 21 | 22 | class ValidPalindrome2ByRemoveOneChar(object): 23 | def quick(self, s): 24 | pass 25 | def brute_force(self, s): 26 | pass 27 | def sub_optimal(self, s): 28 | pass 29 | def optimal(self, s): 30 | pass 31 | 32 | # Parameters and Expected Values. 33 | param1 = 'aba' 34 | expect1 = True 35 | 36 | param2 = 'abca' 37 | expect2 = True 38 | 39 | param3 = 'abc' 40 | expect3 = False 41 | 42 | solution = ValidPalindrome2ByRemoveOneChar() 43 | solution_title('ValidPalindrome2ByRemoveOneChar - Quick One by Initialize two pointers') 44 | print_and_assert_new(solution.quick, param1, expected=expect1) 45 | print_and_assert_new(solution.quick, param2, expected=expect2) 46 | print_and_assert_new(solution.quick, param3, expected=expect3) 47 | getTestResult('ValidPalindrome2ByRemoveOneChar - Quick One') 48 | 49 | timeComplexity('O(n)', 'desc_goes_here') 50 | spaceComplexity('O(n)', 'desc_goes_here') 51 | 52 | # solution_title('ValidPalindrome2ByRemoveOneChar - Brute Force') 53 | # print_and_assert_new(solution.brute_force, param1, expected=expect1) 54 | # print_and_assert_new(solution.brute_force, param2, expected=expect2) 55 | # print_and_assert_new(solution.brute_force, param3, expected=expect3) 56 | # getTestResult('ValidPalindrome2ByRemoveOneChar - Brute Force') 57 | 58 | # timeComplexity('O(n)', 'desc_goes_here') 59 | # spaceComplexity('O(n)', 'desc_goes_here') 60 | 61 | # solution_title('ValidPalindrome2ByRemoveOneChar - Sub Optimal') 62 | # print_and_assert_new(solution.timeOptimized, param1, expected=expect1) 63 | # print_and_assert_new(solution.timeOptimized, param2, expected=expect2) 64 | # print_and_assert_new(solution.timeOptimized, param3, expected=expect3) 65 | # getTestResult('ValidPalindrome2ByRemoveOneChar - Sub Optimal') 66 | 67 | # timeComplexity('O(n)', 'desc_goes_here') 68 | # spaceComplexity('O(n)', 'desc_goes_here') 69 | 70 | # solution_title('ValidPalindrome2ByRemoveOneChar - Optimal') 71 | # print_and_assert_new(solution.timeOptimized, param1, expected=expect1) 72 | # print_and_assert_new(solution.timeOptimized, param2, expected=expect2) 73 | # print_and_assert_new(solution.timeOptimized, param3, expected=expect3) 74 | # getTestResult('ValidPalindrome2ByRemoveOneChar - Optimal') 75 | 76 | # timeComplexity('O(n + m)', 'desc_goes_here') 77 | # spaceComplexity('O(n + m)', 'desc_goes_here') -------------------------------------------------------------------------------- /src/data_structures/queue/queue_priority.py: -------------------------------------------------------------------------------- 1 | print(""" 2 | PriorityQueue Class: 3 | A priority queue, where elements are dequeued based on their priority. Elements must be comparable. 4 | Example: from queue import PriorityQueue 5 | """) 6 | 7 | print(""" 8 | - Elements are popped from the queue based on their priority. Lower values have higher priority. 9 | - The elements are dequeued in ascending order of priority. 10 | - In case of ties in priority, the elements are dequeued in the order they were added. 11 | - The elements in the priority queue are tuples, and the priority is determined by the first element of each tuple. 12 | - The element with the lowest value in the first position will have the highest priority 13 | """) 14 | 15 | print(""" 16 | PriorityQueue uses a heap data structure internally 17 | to efficiently maintain the order of elements based on their priorities 18 | """) 19 | 20 | print(""" 21 | the ordering of strings in the PriorityQueue is based on lexicographical order, 22 | which means it's based on the ASCII values of the characters. 23 | The comparison is done character by character from left to right, 24 | and the first differing character determines the order. 25 | 26 | """) 27 | from queue import PriorityQueue 28 | 29 | class CustomPriorityQueue: 30 | def __init__(self): 31 | self.queue = PriorityQueue() 32 | 33 | def enqueue(self, item, priority): 34 | """Add an item to the queue with a specified priority.""" 35 | self.queue.put((priority, item)) 36 | 37 | def dequeue(self): 38 | """Remove and return the item with the highest priority from the queue.""" 39 | if not self.is_empty(): 40 | return self.queue.get()[1] 41 | else: 42 | print("Queue is empty") 43 | return None 44 | 45 | def is_empty(self): 46 | """Check if the queue is empty.""" 47 | return self.queue.empty() 48 | 49 | def size(self): 50 | """Return the number of items in the queue.""" 51 | return self.queue.qsize() 52 | 53 | def peek(self): 54 | """Return the item with the highest priority in the queue without removing it.""" 55 | if not self.is_empty(): 56 | return self.queue.queue[0][1] 57 | else: 58 | print("Queue is empty") 59 | return None 60 | 61 | # Example usage: 62 | if __name__ == "__main__": 63 | grocery_queue = CustomPriorityQueue() 64 | print("Initial queue:", list(grocery_queue.queue.queue)) 65 | 66 | # Adding people to the queue with priorities 67 | grocery_queue.enqueue("Venkat", 2) 68 | grocery_queue.enqueue("Suba", 1) 69 | grocery_queue.enqueue("Gutti", 3) 70 | print("Queue after adding people:", list(grocery_queue.queue.queue)) 71 | 72 | # Serving people from the queue 73 | serving_person = grocery_queue.dequeue() 74 | print("Serving:", serving_person) 75 | print("Queue after serving:", list(grocery_queue.queue.queue)) 76 | 77 | # Checking the next person to be served 78 | next_person = grocery_queue.peek() 79 | print("Next person to be served:", next_person) 80 | -------------------------------------------------------------------------------- /src/basics/variables.md: -------------------------------------------------------------------------------- 1 | # Variable Examples in Python 2 | 3 | ## Variable Naming Rules 4 | 5 | - Variable names should start with alphanumeric characters, an underscore (`_`), or a string. 6 | - Variable names must not start with numbers or hyphens. 7 | - Variable names are case-sensitive. 8 | 9 | ### Invalid Variable Examples 10 | 11 | ```python 12 | # Throws `SyntaxError: invalid decimal literal` 13 | # 1fruit = 'hello' 14 | 15 | # Throws `SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?` 16 | # -adhi = 'graduated' 17 | # =adhi = 'graduated' 18 | ``` 19 | 20 | ## Multiple Variables 21 | 22 | ### Assigning Multiple Values 23 | 24 | ```python 25 | x, y, z = 1, 2, "Three" 26 | print(f"X is {x}, Y is {y}, Z is {z}") 27 | ``` 28 | 29 | ## Swapping Variables 30 | 31 | ### Using Unpacking 32 | 33 | ```python 34 | a = 'apple' 35 | b = 'bat' 36 | b, a = a, b # Time and Space complexity is O(1) 37 | print(f"After Unpacking: A value is {a}, B value is {b}") 38 | ``` 39 | - **Time Complexity:** `O(1)` - Simply swapping references to the string objects. 40 | - **Space Complexity:** `O(1)` - No additional space is required. 41 | 42 | ### Using Additional Memory 43 | 44 | ```python 45 | c = b 46 | b = a 47 | a = c 48 | print(f"After using additional memory: A value is {a}, B value is {b}") 49 | ``` 50 | - **Time Complexity:** `O(1)` - Each assignment is a constant-time operation. 51 | - **Space Complexity:** `O(1)` - Introduces a single additional variable `c`. 52 | 53 | ### Using Slicing Without Additional Memory 54 | 55 | ```python 56 | a = a + b 57 | b = a[:len(a) - len(b)] 58 | a = a[len(b):] 59 | print(f"After Slicing: A value is {a}, B value is {b}") 60 | ``` 61 | - **Time Complexity:** `O(n + m)` - Where `n` is the length of string `a` and `m` is the length of string `b`. 62 | - **Space Complexity:** `O(n + m)` - Slicing operations create new strings. 63 | 64 | ## Integer Swapping 65 | 66 | ### Using Unpacking 67 | 68 | ```python 69 | a = 1 70 | b = 2 71 | b, a = a, b 72 | print(f"Now Integer A position is {a}, B position is {b}") 73 | ``` 74 | 75 | ### Using Arithmetic Operations 76 | 77 | ```python 78 | a = a + b 79 | b = a - b 80 | a = a - b 81 | print(f"After computation of a+b, a-b, a-b ==== Now Integer A position is {a}, B position is {b}") 82 | ``` 83 | 84 | ### Using XOR Approach 85 | 86 | ```python 87 | a ^= b 88 | b ^= a 89 | a ^= b 90 | print(f"After XOR Approach ==== Now Integer A position is {a}, B position is {b}") 91 | ``` 92 | 93 | ## One Value to Multiple Variables 94 | 95 | ```python 96 | previous = current = next = 1 97 | print(f"previous: {previous}, current: {current}, next: {next}") 98 | ``` 99 | 100 | ## Unpack a Collection 101 | 102 | ### List Example 103 | 104 | ```python 105 | fruits = ["apple", "banana", "cherry"] 106 | firstFruit, secondFruit, thirdFruit = fruits 107 | print(f"firstFruit: {firstFruit}, secondFruit: {secondFruit}, thirdFruit: {thirdFruit}") 108 | ``` 109 | 110 | -------------------------------------------------------------------------------- /src/data_structures/linked_list/linked-list.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1,h2,h3,h4,h5,h6 2 | from testUtils import solution_title, print_and_assert_new, getTestResult 3 | from commonUtils import timeComplexity, spaceComplexity 4 | from stylepy import h1, h2, h3, h4, h5, h6 5 | 6 | h1('\n >>> Linked List Implementation') 7 | h2('>>> 1. Create Node Class with 2 properties 1. data and 2. next property') 8 | h3('>>> 2. Create LinkedList Class with property called head') 9 | h3(''' 10 | Sample Representation of Data 11 | node( 12 | data=1, 13 | next=node( 14 | data=2, 15 | next=node( 16 | data=3, 17 | next=node( 18 | data=4, 19 | next=None 20 | ) 21 | ) 22 | ) 23 | ) 24 | ''') 25 | 26 | class Node: 27 | def __init__(self, data): 28 | self.data = data 29 | self.next = None 30 | 31 | class LinkedListWithoutTail: 32 | def __init__(self): 33 | self.head = None 34 | 35 | def append(self, data): 36 | """ Append a node to the end of the list """ 37 | new_node = Node(data) 38 | if self.head is None: 39 | self.head = new_node 40 | return 41 | last_node = self.head 42 | while last_node.next: 43 | last_node = last_node.next 44 | last_node.next = new_node 45 | 46 | def print_list(self): 47 | """ Print all elements of the list """ 48 | cur_node = self.head 49 | while cur_node: 50 | print(cur_node.data, end=" -> ") 51 | cur_node = cur_node.next 52 | print("None") 53 | 54 | class LinkedListWithTail: 55 | def __init__(self): 56 | self.head = None 57 | self.tail = None # Maintaining a reference to the last node 58 | 59 | def append(self, data): 60 | """ Append a node to the end of the list in O(1) """ 61 | new_node = Node(data) 62 | if not self.head: # If the list is empty 63 | self.head = new_node 64 | self.tail = new_node 65 | else: 66 | self.tail.next = new_node 67 | self.tail = new_node # Update the tail reference 68 | 69 | def print_list(self): 70 | """ Print all elements of the list """ 71 | current = self.head 72 | while current: 73 | print(current.data, end=" -> ") 74 | current = current.next 75 | print("None") 76 | 77 | new_node = Node(1) 78 | 79 | solution_title('Linked List without Tail') 80 | linked_list = LinkedListWithoutTail() 81 | linked_list.append(1) 82 | linked_list.append(2) 83 | linked_list.append(3) 84 | 85 | linked_list.print_list() # Outputs: 1 -> 2 -> 3 -> None 86 | 87 | solution_title('Linked List with Tail') 88 | linked_list_2 = LinkedListWithoutTail() 89 | linked_list_2.append(1) 90 | linked_list_2.append(2) 91 | linked_list_2.append(3) 92 | 93 | linked_list_2.print_list() # Outputs: 1 -> 2 -> 3 -> None 94 | -------------------------------------------------------------------------------- /src/utilities/commonUtils.py: -------------------------------------------------------------------------------- 1 | import pprint 2 | 3 | def timeComplexity(value, desc): 4 | result = f'\n 🕒 Time Complexity: Approximately {value}' 5 | 6 | if (desc): 7 | result += f'\n Description: {desc}' 8 | print(result) 9 | 10 | 11 | def spaceComplexity(value, desc): 12 | result = f' 💾 Space Complexity: Approximately {value}' 13 | 14 | if (desc): 15 | result += f'\n Description: {desc}' 16 | print(result) 17 | 18 | 19 | def print_h1(text): 20 | print(f"\n{'=' * 40}\n{text}\n{'=' * 40}") 21 | 22 | 23 | def print_h2(text): 24 | print(f"\n{'-' * 35}\n{text}\n{'-' * 35}") 25 | 26 | 27 | def print_h3(text): 28 | print(f"\n{text}\n{'-' * 30}") 29 | 30 | 31 | def print_h4(*text): 32 | combined_text = " ".join(str(t) for t in text) # Join all elements of text into one string 33 | print(f"\n{combined_text}\n{'-' * 25}") 34 | 35 | def print_h5(text): 36 | print(f"\n{text}\n{'-' * 20}") 37 | 38 | def print_h6(text): 39 | print(f"\n{text}\n{'-' * 15}") 40 | 41 | def print_span(*text): 42 | combined_text = " ".join(str(t) for t in text) # Join all elements of text into one string 43 | # Using ANSI escape code for bold text 44 | print(f"\033[1m{combined_text}\033[0m") 45 | 46 | def print_ordered_list(items): 47 | for i, item in enumerate(items, start=1): 48 | print(f"{i}. {item}") 49 | 50 | 51 | def print_bullet_list(items, bullet_char='*'): 52 | for item in items: 53 | print(f"{bullet_char} {item}") 54 | 55 | 56 | def print_blockquote(items, indent_char='> ', emoji='💬', new_line = False): 57 | if (new_line): 58 | print('\n') 59 | for item in items: 60 | print(f"{emoji} {indent_char}{item}") 61 | 62 | 63 | def pretty_json(input): 64 | pprint.pprint(input, width=50, indent=2) 65 | 66 | 67 | def print_tabular_list(data, col_widths = [15, 45]): 68 | """ 69 | Print data in a tabular format with horizontal lines, differentiating the header. 70 | 71 | :param data: List of tuples, where each tuple represents a row. 72 | :param col_widths: List of integers representing the width of each column. 73 | """ 74 | def print_divider(): 75 | # Create and print a divider line with '+' 76 | line = "+" + "+".join("-" * width for width in col_widths) + "+" 77 | print(line) 78 | 79 | def print_header_divider(): 80 | # Create and print a simple divider line without '+' for the header 81 | line = "-" * (sum(col_widths) + len(col_widths) - 1) 82 | print(line) 83 | 84 | # Print the header row 85 | print_divider() 86 | header = data[0] 87 | formatted_header = "|".join( 88 | f"{item:<{col_widths[i]}}" for i, item in enumerate(header)) 89 | print("|" + formatted_header + "|") 90 | print_header_divider() 91 | 92 | # Print the rest of the rows 93 | for row in data[1:]: 94 | formatted_row = "|".join( 95 | f"{item:<{col_widths[i]}}" for i, item in enumerate(row)) 96 | print("|" + formatted_row + "|") 97 | print_header_divider() 98 | -------------------------------------------------------------------------------- /src/basics/data_types.md: -------------------------------------------------------------------------------- 1 | # Data Types Example 2 | 3 | ## 15 Types of Data Types 4 | 5 | ### 1. Text Type 6 | - String (`str`) 7 | 8 | ### 2. Numeric Type 9 | - Integer (`int`), Float (`float`), Complex (`complex`) 10 | 11 | ### 3. Sequence Type 12 | - List (`list`), Tuple (`tuple`), Range (`range`) 13 | 14 | ### 4. Mapping Type 15 | - Dictionary (`dict`) 16 | 17 | ### 5. Set Type 18 | - Set (`set`), Frozen Set (`frozenset`) 19 | 20 | ### 6. Boolean Type 21 | - Boolean (`bool`) 22 | 23 | ### 7. Binary Type 24 | - Bytes (`bytes`), ByteArray (`bytearray`), MemoryView (`memoryview`) 25 | 26 | ### 8. None Type 27 | - None (`None`) 28 | 29 | ## Examples 30 | 31 | ### String Data Type 32 | ```python 33 | greet = 'welcome' # String 34 | castToString = str(3) 35 | 36 | print(f"Type of greet is {type(greet)}") # <class 'str'> 37 | print(f"Type of castToString is {type(castToString)}") # <class 'str'> 38 | ``` 39 | 40 | ### Numeric Data Type 41 | #### Integer 42 | ```python 43 | currentYear = 2024 # int for year 44 | print(f"Type of currentYear is {type(currentYear)}") # <class 'int'> 45 | 46 | castToInteger = int(2024.00) 47 | print(f"Type of castToInteger is {type(castToInteger)}") # <class 'int'> 48 | ``` 49 | 50 | #### Float 51 | ```python 52 | weight = 75.50 # Float for weight in kg 53 | print(f"Type of weight is {type(weight)}") # <class 'float'> 54 | 55 | castToFloat = float('75.50') 56 | print(f"Type of castToFloat is {type(castToFloat)}") # <class 'float'> 57 | ``` 58 | 59 | ### Sequence Data Type 60 | #### List 61 | ```python 62 | fruits = ["apple", "banana", "cherry"] # List for fruits 63 | print(f"Type of fruits is {type(fruits)}") # <class 'list'> 64 | 65 | fruits.append("grapes") 66 | print(f"Fruits List: {fruits}") # ['apple', 'banana', 'cherry', 'grapes'] 67 | ``` 68 | 69 | #### Tuple 70 | ```python 71 | configuration = ('2MB', '30 Minutes') # Tuple 72 | print(f"Type of configuration is {type(configuration)}") # <class 'tuple'> 73 | print(f"Configuration Tuple: {configuration}") 74 | ``` 75 | 76 | ### Mapping Data Type 77 | #### Dictionary 78 | ```python 79 | employeeDictionary = {"name": "John", "age": 36} # Dict 80 | print(f"Type of employeeDictionary is {type(employeeDictionary)}") # <class 'dict'> 81 | print(employeeDictionary) # {'name': 'John', 'age': 36} 82 | 83 | config = {True: "dummyValue", 1: "actualConfigValue"} # Dict key conflict example 84 | print(f"Config dictionary: {config}") # {True: 'actualConfigValue'} 85 | ``` 86 | 87 | ### Boolean Data Type 88 | ```python 89 | eligibleToVote = True # Boolean 90 | print(f"Type of eligibleToVote is {type(eligibleToVote)}") # <class 'bool'> 91 | print(f"eligibleToVote: {eligibleToVote}") 92 | 93 | sunRiseToday = 'east' 94 | sunRiseTodayInWest = True if sunRiseToday == 'west' else False 95 | print(f"Type of sunRiseTodayInWest is {type(sunRiseTodayInWest)}") # <class 'bool'> 96 | print(f"sunRiseTodayInWest: {sunRiseTodayInWest}") # False 97 | ``` 98 | 99 | ## TODO 100 | - Add Bytes 101 | - Add None examples 102 | 103 | -------------------------------------------------------------------------------- /src/data_types/commonUtils.py: -------------------------------------------------------------------------------- 1 | import pprint 2 | from stylepy import timeComplexity 3 | from stylepy import spaceComplexity 4 | from stylepy import h1,h2,h3,h4,h5,h5,h6 5 | def timeComplexity(value, desc): 6 | result = f'\n 🕒 Time Complexity: Approximately {value}' 7 | 8 | if (desc): 9 | result += f'\n Description: {desc}' 10 | h4(result) 11 | 12 | 13 | timeComplexity("value", "desc") 14 | 15 | def spaceComplexity(value, desc): 16 | result = f' 💾 Space Complexity: Approximately {value}' 17 | 18 | if (desc): 19 | result += f'\n Description: {desc}' 20 | h4(result) 21 | 22 | spaceComplexity("value", "desc") 23 | 24 | def print_h1(text): 25 | h1(f"\n{'=' * 40}\n{text}\n{'=' * 40}") 26 | 27 | 28 | def print_h2(text): 29 | h2(f"\n{'-' * 35}\n{text}\n{'-' * 35}") 30 | 31 | 32 | def print_h3(text): 33 | h3(f"\n{text}\n{'-' * 30}") 34 | 35 | 36 | def print_h4(*text): 37 | combined_text = " ".join(str(t) for t in text) # Join all elements of text into one string 38 | h4(f"\n{combined_text}\n{'-' * 25}") 39 | 40 | def print_h5(text): 41 | h5(f"\n{text}\n{'-' * 20}") 42 | 43 | def print_h6(*text): 44 | combined_text = " ".join(str(t) for t in text) # Join all elements of text into one string 45 | h6(f"\n{combined_text}\n{'-' * 15}") 46 | 47 | def print_span(*text): 48 | combined_text = " ".join(str(t) for t in text) # Join all elements of text into one string 49 | # Using ANSI escape code for bold text 50 | h4(f"> \033[1m{combined_text}\033[0m") 51 | 52 | def print_ordered_list(items): 53 | for i, item in enumerate(items, start=1): 54 | h5(f"{i}. {item}") 55 | 56 | 57 | def print_bullet_list(items, bullet_char='*'): 58 | for item in items: 59 | print(f"{bullet_char} {item}") 60 | 61 | 62 | def print_blockquote(items, indent_char='> ', emoji='💬', new_line = False): 63 | if (new_line): 64 | print('\n') 65 | for item in items: 66 | h6(f"{emoji} {indent_char}{item}") 67 | 68 | 69 | def pretty_json(input): 70 | pprint.pprint(input, width=50, indent=2) 71 | 72 | def print_tabular_list(data, col_widths=None): 73 | # Calculate column widths based on the data if not provided 74 | if col_widths is None: 75 | col_widths = [max(len(str(item)) for item in column) for column in zip(*data)] 76 | 77 | def print_divider(): 78 | line = "+" + "+".join("-" * width for width in col_widths) + "+" 79 | h4(line) 80 | 81 | def print_header_divider(): 82 | line = "-" * (sum(col_widths) + len(col_widths) - 1) 83 | h5(line) 84 | 85 | # Print the header row 86 | print_divider() 87 | header = data[0] 88 | formatted_header = "|".join( 89 | f"{item:<{col_widths[i]}}" for i, item in enumerate(header)) 90 | h6("|" + formatted_header + "|") 91 | print_header_divider() 92 | 93 | # Print the rest of the rows 94 | for row in data[1:]: 95 | formatted_row = "|".join( 96 | f"{item:<{col_widths[i]}}" for i, item in enumerate(row)) 97 | h5("|" + formatted_row + "|") 98 | print_header_divider() 99 | -------------------------------------------------------------------------------- /src/leetcode/arrays/283_move_zeroes_easy.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_reference, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> 283. Move Zeroes') 5 | print(''' 6 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 7 | 8 | Note that you must do this in-place without making a copy of the array. 9 | 10 | Example 1: 11 | 12 | Input: nums = [0,1,0,3,12] 13 | Output: [1,3,12,0,0] 14 | Example 2: 15 | 16 | Input: nums = [0] 17 | Output: [0] 18 | ''') 19 | 20 | class MoveZeroesItemInArrayToLast(object): 21 | def quick(self, nums): 22 | j = 0 23 | for num in nums: 24 | if num != 0: 25 | nums[j] = num 26 | j += 1 27 | for i in range(j, len(nums)): 28 | nums[i] = 0 29 | def brute_force(self, s): 30 | pass 31 | def sub_optimal(self, s): 32 | pass 33 | def optimal(self, s): 34 | pass 35 | 36 | # Parameters and Expected Values. 37 | param1 = [0,1,0,3,12] 38 | expect1 = [1,3,12,0,0] 39 | 40 | param2 = [0] 41 | expect2 = [0] 42 | 43 | param3 = [0,1,0] 44 | expect3 = [1,0,0] 45 | 46 | solution = MoveZeroesItemInArrayToLast() 47 | solution_title('MoveZeroesItemInArrayToLast - Quick One') 48 | print_and_assert_reference(solution.quick, param1, expected=expect1) 49 | print_and_assert_reference(solution.quick, param2, expected=expect2) 50 | print_and_assert_reference(solution.quick, param3, expected=expect3) 51 | getTestResult('MoveZeroesItemInArrayToLast - Quick One') 52 | 53 | timeComplexity('O(n)', 'desc_goes_here') 54 | spaceComplexity('O(n)', 'desc_goes_here') 55 | 56 | # solution_title('MoveZeroesItemInArrayToLast - Brute Force') 57 | # print_and_assert_reference(solution.brute_force, param1, expected=expect1) 58 | # print_and_assert_reference(solution.brute_force, param2, expected=expect2) 59 | # print_and_assert_reference(solution.brute_force, param3, expected=expect3) 60 | # getTestResult('MoveZeroesItemInArrayToLast - Brute Force') 61 | 62 | # timeComplexity('O(n)', 'desc_goes_here') 63 | # spaceComplexity('O(n)', 'desc_goes_here') 64 | 65 | # solution_title('MoveZeroesItemInArrayToLast - Sub Optimal') 66 | # print_and_assert_reference(solution.timeOptimized, param1, expected=expect1) 67 | # print_and_assert_reference(solution.timeOptimized, param2, expected=expect2) 68 | # print_and_assert_reference(solution.timeOptimized, param3, expected=expect3) 69 | # getTestResult('MoveZeroesItemInArrayToLast - Sub Optimal') 70 | 71 | # timeComplexity('O(n)', 'desc_goes_here') 72 | # spaceComplexity('O(n)', 'desc_goes_here') 73 | 74 | # solution_title('MoveZeroesItemInArrayToLast - Optimal') 75 | # print_and_assert_reference(solution.timeOptimized, param1, expected=expect1) 76 | # print_and_assert_reference(solution.timeOptimized, param2, expected=expect2) 77 | # print_and_assert_reference(solution.timeOptimized, param3, expected=expect3) 78 | # getTestResult('MoveZeroesItemInArrayToLast - Optimal') 79 | 80 | # timeComplexity('O(n + m)', 'desc_goes_here') 81 | # spaceComplexity('O(n + m)', 'desc_goes_here') -------------------------------------------------------------------------------- /src/functions/lambda.py: -------------------------------------------------------------------------------- 1 | text = """ 2 | 3 | What is lambda in python? 4 | 5 | It is anonymous function 6 | It can take many number of arguments 7 | It can only have one expression 8 | It is written as a single line of execution 9 | It does not support type annotations 10 | It can be immediately invoked (IIFE) 11 | 12 | 13 | Lambda functions are frequently used with 14 | higher-order functions, which take one or more functions as arguments 15 | or return one or more functions. 16 | filter(), sort(), sorted(), min(), and max() 17 | 18 | A lambda function can't contain any statements. 19 | Statements like return, pass, assert, or 20 | raise will raise a Syntax Error exception 21 | """ 22 | 23 | # SyntaxError: Lambda expression parameters cannot be parenthesized 24 | # greet = lambda (name, greeting) : f'Hi Mr. {name}, Good {greeting}!' 25 | 26 | # greet = lambda name, greeting : f'Hi Mr. {name}, Good {greeting}!' 27 | # greet = (lambda name: str, greeting: str)(f'Hi Mr. {name}, Good {greeting}!') 28 | # print(greet('Venkat', 'Morning')) 29 | 30 | # Throws type_annotation = (lambda x: int, y: int ,z: int : x + y + z)(2, 5, 7) 31 | # ^ 32 | # SyntaxError: invalid syntax 33 | 34 | print(text) 35 | print(""" """ ) 36 | print("anonymous function") 37 | print("--------------------------------") 38 | add_value = lambda x : x + 10 39 | print("Add Value", add_value(2)) 40 | 41 | print(""" """ ) 42 | print("More than one arguments for lambda") 43 | print("--------------------------------") 44 | add_value_more_arguments = (lambda x, y ,z : x + y + z)(2, 5, 7) 45 | print("Add Value(more arguments)", add_value_more_arguments) 46 | 47 | print(""" """ ) 48 | print("Type annotation is not supported") 49 | print("--------------------------------") 50 | # type_annotation = (lambda x: int, y: int ,z: int : x + y + z)(2, 5, 7) 51 | # print("Type annotation is not supported", type_annotation) 52 | print(""" """ ) 53 | print("Square number without lambda") 54 | print("--------------------------------") 55 | def square(a): 56 | return a**2 57 | 58 | print(' square(7): ', square(7)) 59 | 60 | numbers = [1, 2, 3, 4, 5,] 61 | squared = list(map(square, numbers)) 62 | print("Numbers: ", numbers,) 63 | print("Squared Numbers", squared) 64 | 65 | print(""" """ ) 66 | print("Square number with lambda") 67 | print("--------------------------------") 68 | numbers = [1, 2, 3, 4, 5,] 69 | squared = list(map((lambda x: x**2), numbers)) 70 | print("Squared numbers", squared) 71 | 72 | print(""" """ ) 73 | print("Exception traceback with lamda") 74 | print("--------------------------------") 75 | # div_by_zero = (lambda x: x / 0)(10) 76 | # print("Lambda: Divide by Zero", div_by_zero) 77 | # Throws ZeroDivisionError: division by zero 78 | 79 | print(""" """ ) 80 | print("Exception traceback with function") 81 | print("--------------------------------") 82 | def div_by_zero_func(x): 83 | return x / 0 84 | # print("Function: Divide by Zero", div_by_zero_func(10)) 85 | # Throws ZeroDivisionError: division by zero 86 | 87 | print(""" """ ) 88 | print("A lambda function can't contain any statements") 89 | print("--------------------------------") 90 | 91 | test = lambda x: x + 10 92 | print("Test ", test(2)) 93 | 94 | -------------------------------------------------------------------------------- /src/basics/strings.md: -------------------------------------------------------------------------------- 1 | 2 | # String Type Example 3 | 4 | ## What is the maximum value that can be stored inside a Python string variable? 5 | 6 | ### Below is the Max size 7 | 8 | Max size: 8.00 TB 9 | 10 | #### Single line using single quote 11 | 12 | Single quote is same as double quote for string data type 13 | 14 | #### Single line using double quote 15 | 16 | Single quote is same as double quote for string data type 17 | 18 | #### Multi line using single quote 19 | 20 | Multi line statement can be 21 | created using 3 single quotes. 22 | 23 | #### Multi line using double quote 24 | 25 | Multi line statement can be 26 | created using 3 double quotes. 27 | 28 | greet = 'welcome'; 29 | 30 | ## Slicing Example 31 | 32 | ### Accessing one specific character in string variable 33 | 34 | #### Find the 3rd character from 0th index 35 | 36 | c 37 | 38 | #### Number after colon executed with `-1` which will be considered as start:stop 39 | 40 | #### Accessing 3rd to 5th specific character in the string variable 41 | 42 | Find the characters from 0th index to 5th index 43 | 44 | com 45 | 46 | #### Accessing from 0 to 5th specific character in the string variable 47 | 48 | Find the characters from 0th index to 5th index 49 | 50 | welcom 51 | 52 | #### Accessing from 3rd to end of the string variable 53 | 54 | Find the characters from 0th index to last index 55 | 56 | come 57 | 58 | #### Accessing from last to 4 characters in the string variable 59 | 60 | Find the characters from last index to 4 characters 61 | 62 | come 63 | 64 | #### Accessing from last to 4 characters but skip last character in the string variable 65 | 66 | Find the characters from last index to 4 characters with skipping last character 67 | 68 | come 69 | 70 | ## Iteration Example 71 | 72 | #### Iterate the Greet String and print each character 73 | 74 | character: w 75 | character: e 76 | character: l 77 | character: c 78 | character: o 79 | character: m 80 | character: e 81 | 82 | ## Find Length Example 83 | 84 | #### Find a Length of greet String 85 | 86 | greet length 7 87 | 88 | ## `in / not in` Exist Check Example 89 | 90 | #### Find whether `w` string exists in greet variable using `in` keyword 91 | 92 | Time Complexity: O(n). In Python, strings are typically implemented as arrays of characters. The operation 'w' in greet is essentially a search operation where Python checks each character in the string greet to see if it matches 'w'. 93 | 94 | True 95 | 96 | #### Use `in` statement in `if` statement as well 97 | 98 | w exists in greet variable 99 | 100 | #### Use `in` statement in `if` statement as well 101 | 102 | u Not exist in greet variable 103 | 104 | ## Format Example 105 | 106 | #### format() method takes an unlimited number of arguments. Example 107 | 108 | I am currently Full Stack engineer at Meta Inc and working in Singapore. 109 | 110 | #### format() with index numbers 111 | 112 | hey i work for Meta Inc in Singapore as Full Stack engineer 113 | 114 | #### format() with missing index numbers, meaning not giving all the index 115 | 116 | #### Error: cannot switch from manual field specification to automatic field numbering 117 | 118 | -------------------------------------------------------------------------------- /src/basics/basics.md: -------------------------------------------------------------------------------- 1 | # Python Basic Statement Examples 2 | 3 | ## 1. Print Statement without Parenthesis 4 | ### Issue 5 | Using a print statement without parentheses throws a **SyntaxError**: 6 | ```python 7 | # print "Concatenation with variable" 8 | ``` 9 | **Error Message:** 10 | ``` 11 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)? 12 | ``` 13 | 14 | --- 15 | 16 | ## 2. Print Statement 17 | ### Correct Usage 18 | ```python 19 | print('hello venkat, welcome to python') 20 | ``` 21 | 22 | --- 23 | 24 | ## 3. Print Statement with Comma-Separated Arguments 25 | The `print()` statement supports multiple comma-separated arguments. The maximum number depends on the available system memory. 26 | ```python 27 | print('hello venkat,', 'welcome to', 'python') 28 | ``` 29 | 30 | --- 31 | 32 | ## 4. Print Statement Simple Concatenation 33 | Concatenation of string literals can be done using the `+` operator: 34 | ```python 35 | print('hello venkat, welcome to python' + '3') 36 | ``` 37 | 38 | --- 39 | 40 | ## 5. Concatenation with Integer Variable 41 | ### Issue 42 | Using `+` between an integer and a string throws a **TypeError**: 43 | ```python 44 | version = 3 45 | # print(version + 'hello venkat, welcome to python') # Throws TypeError 46 | # print('hello venkat, welcome to python' + version) # Throws TypeError 47 | ``` 48 | **Error Message:** 49 | ``` 50 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 51 | ``` 52 | 53 | ### Fix 54 | Use the `str()` function to convert the integer to a string: 55 | ```python 56 | print('hello venkat, welcome to python' + str(version)) 57 | ``` 58 | 59 | --- 60 | 61 | ## 6. Concatenation with String Variable 62 | Concatenation works without any issues when both variables are strings: 63 | ```python 64 | version = '3' 65 | print('hello venkat, welcome to python' + version) 66 | ``` 67 | 68 | --- 69 | 70 | ## 7. String Variable Wrapped in String Literal 71 | Using **f-strings** for clean and readable string interpolation: 72 | ```python 73 | version = '3' 74 | print(f"hello venkat, welcome to python{version}") 75 | ``` 76 | 77 | --- 78 | 79 | ## 8. Simple Hello World Function and IndentationError 80 | ### Issue 81 | A function body statement without proper indentation throws **IndentationError**: 82 | ```python 83 | def helloWorld(): 84 | # print('Hello World from helloWorld()') # IndentationError 85 | ``` 86 | **Error Message:** 87 | ``` 88 | IndentationError: expected an indented block after function definition 89 | ``` 90 | 91 | ### Explanation 92 | In Python, the execution order is from top to bottom, line by line. Python compiles the code into bytecode before execution. If there is an **IndentationError**, the compilation phase fails, and the code is not executed. 93 | 94 | ### Fix 95 | Indent the function body correctly: 96 | ```python 97 | def helloWorld(): 98 | print('Hello World from helloWorld()') 99 | ``` 100 | 101 | ### Function Call 102 | ```python 103 | helloWorld() 104 | ``` 105 | 106 | --- 107 | 108 | ## 9. Reversing String Value Using Slicing 109 | Reversing a string using slicing: 110 | ```python 111 | fruits = 'Apple' 112 | print(fruits[::-1]) # Output: elppA 113 | ``` 114 | 115 | -------------------------------------------------------------------------------- /src/interview/find_sum_of_integer_array.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> Find Sum of Duplicated Integer Array') 5 | print(''' 6 | ############################################## 7 | # 8 | # Given an array nums, write a function to calculate the sum of distinct elements in the array. 9 | # 10 | # Example 11 | # Input: [7,8,1,7,1,7] Output: 16 12 | # why: Because the distinct numbers in the array are 1,7,8, the sum of which is 16 13 | # 14 | ############################################## 15 | ''') 16 | 17 | class FindSumOfIntegerArray(object): 18 | def quick(self, numbers_list): 19 | unique_numbers = set(numbers_list) 20 | sum = 0 21 | for number in unique_numbers: 22 | sum += number 23 | return sum 24 | def brute_force(self, numbers_list): 25 | unique_number_keys = {} 26 | sum = 0 27 | for number in numbers_list: 28 | if number not in unique_number_keys: 29 | unique_number_keys[number] = 1 30 | sum += number 31 | return sum 32 | def sub_optimal(self, numbers_list): 33 | pass 34 | def optimal(self, numbers_list): 35 | pass 36 | 37 | # Parameters and Expected Values. 38 | param1 = [7,8,1,7,1,7] 39 | expect1 = 16 40 | 41 | param2 = [7,8,1,7,1,7,4,5] 42 | expect2 = 25 43 | 44 | param3 = [7,8,1,7,1,7,9,6,3] 45 | expect3 = 34 46 | 47 | solution = FindSumOfIntegerArray() 48 | solution_title('FindSumOfIntegerArray - Using Set') 49 | print_and_assert_new(solution.quick, param1, expected=expect1) 50 | print_and_assert_new(solution.quick, param2, expected=expect2) 51 | print_and_assert_new(solution.quick, param3, expected=expect3) 52 | getTestResult('FindSumOfIntegerArray - Using Set') 53 | 54 | timeComplexity('O(n)', 'Creating Set and Iterating over the elements for sum') 55 | spaceComplexity('O(n)', 'In worst case (all elements are unique), the set will contain as many elements as the original list.') 56 | 57 | solution_title('FindSumOfIntegerArray - Using Hash Table') 58 | print_and_assert_new(solution.brute_force, param1, expected=expect1) 59 | print_and_assert_new(solution.brute_force, param2, expected=expect2) 60 | print_and_assert_new(solution.brute_force, param3, expected=expect3) 61 | getTestResult('FindSumOfIntegerArray - Using Hash Table') 62 | 63 | # timeComplexity('O(n)', 'desc_goes_here') 64 | # spaceComplexity('O(n)', 'desc_goes_here') 65 | 66 | # solution_title('FindSumOfIntegerArray - Sub Optimal') 67 | # print_and_assert_new(solution.timeOptimized, param1, expected=expect1) 68 | # print_and_assert_new(solution.timeOptimized, param2, expected=expect2) 69 | # print_and_assert_new(solution.timeOptimized, param3, expected=expect3) 70 | # getTestResult('FindSumOfIntegerArray - Sub Optimal') 71 | 72 | # timeComplexity('O(n)', 'desc_goes_here') 73 | # spaceComplexity('O(n)', 'desc_goes_here') 74 | 75 | # solution_title('FindSumOfIntegerArray - Optimal') 76 | # print_and_assert_new(solution.timeOptimized, param1, expected=expect1) 77 | # print_and_assert_new(solution.timeOptimized, param2, expected=expect2) 78 | # print_and_assert_new(solution.timeOptimized, param3, expected=expect3) 79 | # getTestResult('FindSumOfIntegerArray - Optimal') 80 | 81 | # timeComplexity('O(n + m)', 'desc_goes_here') 82 | # spaceComplexity('O(n + m)', 'desc_goes_here') -------------------------------------------------------------------------------- /src/basics/b_variables.py: -------------------------------------------------------------------------------- 1 | 2 | from stylepy import h1, h2, h3, h4, h5, h6 3 | from stylepy import spaceComplexity 4 | from stylepy import timeComplexity 5 | h1('\n >>>> Variable Example'); 6 | h2("Variable name should start with alpha-numeric characters, _ or string") 7 | h3("Variable name should not start with numbers, hyphen") 8 | h4("Variable names are case sensitive"); 9 | 10 | # Below code throws `SyntaxError: invalid decimal literal`. 11 | # 1fruit = 'hello' 12 | 13 | # Below code throws `SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?` 14 | # -adhi = 'graduated' 15 | # SyntaxError: invalid syntax 16 | # =adhi = 'graduated' 17 | 18 | # Multiple Variables 19 | h5("\n>>>> Multiple Variables with String literal"); 20 | x, y, z = 1, 2, "Three" 21 | h5(f"X is {x}, Y is {y}, Z is {z}") 22 | 23 | # Swapping example 24 | h6("\n>>>> Swapping String Variables Using unpacking return with String literal"); 25 | a = 'apple' 26 | b = 'bat' 27 | b, a = a, b # Time and Space complexity is O(1), Constant Time, which is faster. 28 | timeComplexity("O(1)", "Because the operation is simply swapping references to the string objects") 29 | spaceComplexity("O(1)", "No additional space is needed to perform the swap.") 30 | 31 | h4(f"After Unpacking: A value is {a}, B value is {b}") 32 | # Alternative solution using Additional memory 33 | h5("\n>>>> Alternative solution using Additional memory with String literal"); 34 | c = b 35 | b = a 36 | a = c 37 | h4(f"After using additional memory: A value is {a}, B value is {b}") 38 | timeComplexity('O(1)', 'Each of the assignments (c = b, b = a, a = c) is a constant-time operation.') 39 | spaceComplexity('O(1)', 'This method introduces a single additional variable c. The space used by c does not depend on the size of the strings a and b') 40 | # Alternative solution without using Additional memory 41 | h5("\n>>>> Alternative solution without using Additional memory which is slicing and return in String literal"); 42 | a = a + b 43 | b = a[:len(a) - len(b)] # which is :5, so start from begining and stop before 5th position. 44 | a = a[len(b):] # which is start from 5: and the rest. 45 | h4(f"After Slicing: A value is {a}, B value is {b}") 46 | timeComplexity('O(n + m)', 'where N is the length of string a and M is the length of string b.') 47 | spaceComplexity('O(n + m)', 'slicing operations also create new strings that require additional space.') 48 | 49 | 50 | # How about in integer swapping values? 51 | h4("\n>>>> Swapping Integer Variables Using unpacking return in String literal"); 52 | a = 1 53 | b = 2 54 | b, a = a, b # Unpacking in Python and Destruction in JS 55 | h4(f"Now Integer A position is {a}, B position is {b}") 56 | a = a + b 57 | b = a - b 58 | a = a - b 59 | h4(f"\n>>>> After computation of a+b, a-b, a-b ==== Now Integer A position is {a}, B position is {b}") 60 | a ^= b 61 | b ^= a 62 | a ^= b 63 | h5(f"\n>>>> After XOR Approach of a ^= b; b ^= a; a ^= b ==== Now Integer A position is {a}, B position is {b}") 64 | 65 | # One Value to Multiple Variables 66 | h4("\n>>>> One Value to Multiple Variables"); 67 | previous = current = next = 1 68 | h5(f"previous: {previous}, current: {current}, next: {next}") 69 | 70 | # Unpack a Collection 71 | h4("\n>>>> Unpack a Collection: list, tuple") 72 | fruits = ["apple", "banana", "cherry"] 73 | firstFruit, secondFruit, thirdFruit = fruits 74 | h5(f"firstFruit: {firstFruit}, secondFruit: {secondFruit}, thirdFruit: {thirdFruit}") 75 | -------------------------------------------------------------------------------- /src/controls/if.py: -------------------------------------------------------------------------------- 1 | from stylepy import h1, h2, h3, h4, h5, h6 2 | text = """ 3 | Conditional operators 4 | 1. Equality: 5 | ==: Equal to 6 | !=: Not equal to 7 | 8 | 2. Comparison: 9 | <: Less than 10 | >: Greater than 11 | <=: Less than or equal to 12 | >=: Greater than or equal to 13 | 14 | 3. Membership: 15 | in: Checks if a value exists in a sequence (e.g., list, tuple, string) 16 | not in: Checks if a value does not exist in a sequence 17 | 18 | 4. Identity: 19 | is: Checks if two variables refer to the same object 20 | is not: Checks if two variables do not refer to the same object 21 | 22 | """ 23 | 24 | h1(text) 25 | 26 | #simple if and else 27 | 28 | if 10 > 20 : 29 | h2("10 is greater than 20 ") 30 | elif 10 > 15: 31 | h3("10 is greater than 15") 32 | else : 33 | h4("10 is neither greater than 20 and 15") 34 | 35 | 36 | h4("do we have ternary operator like a > b ? True : False ") 37 | h4("Answer is No. However python has implemented ternary condition expression through if ") 38 | 39 | #Ternary expression 40 | result = True if 0 > 1 else False 41 | h5("Ternary result: ", result) 42 | 43 | h6("Do we have === in python? ") 44 | h6("Answer is No") 45 | # === operator 46 | # if 10 === 10 : 47 | # print("true with type check") 48 | # else: 49 | # print("Flase with type check") 50 | 51 | h1("What is alterate to do type check? ") 52 | 53 | def is_number(x): 54 | result = 'number' if isinstance(x, (int, float, complex)) else 'Not a number' 55 | h2(f"given {x} is {result}") 56 | 57 | is_number(42) # True 58 | is_number(3.14) # True 59 | is_number(5 + 2j) # True 60 | is_number("Hello") 61 | 62 | h3("Another way to check is type(variable) == data_tyep ") 63 | 64 | if type(10) == int: 65 | h4("10 in integer") 66 | else: 67 | h5("10 is not an integer") 68 | 69 | h6("check the value is in the list, tuple, string or not") 70 | a = 10 71 | item_list = [10, 20, 30] 72 | item_tuple = (20, 10, 30) 73 | item_string = "welcome" 74 | b = "come" 75 | if a in item_list: 76 | h3(f"{a} is in the item_list") 77 | else: 78 | h4(f"{a} is not in the item_list") 79 | 80 | if a in item_tuple: 81 | h3(f"{a} is in the item_tuple") 82 | else: 83 | h4(f"{a} is not in the item_tuple") 84 | 85 | if b in item_string: 86 | h3(f"{b} is in the item_string") 87 | else: 88 | h4(f"{b} is not in the item_string") 89 | 90 | h5("are we able to check the dictonary since it is key value pair") 91 | dict_item = {"suba": "Back end dev", 'venkat': "Front end dev", 'Gutti': 'ML dev'} 92 | key = "suba" 93 | if key in dict_item: 94 | h5(f"{key} is in the dict_item") 95 | key = "test" 96 | if key not in dict_item: 97 | h6(f"{key} is not in the dict_item") 98 | 99 | 100 | value = "Front end dev" 101 | if value in dict_item.values(): 102 | h5(f"{value} is in the dict_item") 103 | value = "developer" 104 | if value not in dict_item.values(): 105 | h6(f"{value} is not in the dict_item") 106 | 107 | if 10 not in [1, 2, 4 ,5 ]: 108 | h2(f"10 is not in the list") 109 | 110 | # indendity check (is and not is ) 111 | list1 = [1, 2 , 3 ] 112 | list2 = [1, 2, 3] 113 | list3 = list1 114 | 115 | def check_same_object(obj1, obj2): 116 | if obj1 is obj2: 117 | h3(f"obj1 and obj2 are in the same object") 118 | if obj1 is not obj2: 119 | h4(f"obj1 and obj2 are not in the same object") 120 | 121 | check_same_object(list1, list2) 122 | check_same_object(list1, list3) 123 | -------------------------------------------------------------------------------- /src/data_types/non_linear/dictionaries/basics.py: -------------------------------------------------------------------------------- 1 | # python module.py data_types/dictionaries/basics.py 2 | # python -m data_types.dictionaries.basics data_types/dictionaries/basics.py 3 | 4 | import data_types.commonUtils as utils 5 | 6 | utils.print_h1('Dictionary Basics') 7 | utils.print_ordered_list([ 8 | 'Dictionary is Key pair values, Ordered (order will not be changed)', 9 | 'Dictionary is Changeable', 10 | 'Dictionary will not contain duplicate key', 11 | 'In Python 3.6, is unordered Python 3.7 is Ordered', 12 | 'Its good for fast lookups', 13 | 'Insertions, and deletions by using keys', 14 | 'Every Keys will be hashed using Hashing Algorithm' 15 | ]) 16 | 17 | utils.print_h3('Hashing Algorithm by Data Types') 18 | hashing_algorithm_by_data_types = [ 19 | (" Key Type", " Hashing Algorithm/Method"), 20 | (" String", " SipHash variant"), 21 | (" Integer", " Identity hash (value itself with exceptions)"), 22 | (" Float", " Based on internal representation"), 23 | (" Boolean", " Same as Integer (True is 1, False is 0)"), 24 | (" Tuple", " Combination of hashes of contents"), 25 | (" Custom Object", " Defined by `__hash__` method (if implemented)"), 26 | (" None", " Fixed hash value") 27 | ] 28 | 29 | # Print the table 30 | utils.print_tabular_list(hashing_algorithm_by_data_types) 31 | 32 | employee = { 33 | 'name': 'Alice', 34 | 'age': 30, 35 | 'items': ['book', 'pen', 'notebook'], 36 | 'nested_dict': { 37 | 'key1': 'value1', 38 | 'key2': 'value2' 39 | } 40 | } 41 | 42 | utils.print_blockquote([ 43 | 'Lets take a example of below dictionary for employee.' 44 | ]) 45 | 46 | utils.pretty_json(employee) 47 | 48 | utils.print_blockquote([ 49 | 'Lets add list and tuple as key and printing the employee again' 50 | ]) 51 | 52 | marks = [100,70,90] 53 | subjects = ('english', 70) 54 | # employee[marks] = 10 #throws TypeError: unhashable type: 'list' 55 | employee[subjects] = 20 56 | 57 | utils.pretty_json(employee) 58 | 59 | utils.print_h1('Access') 60 | utils.print_blockquote([ 61 | 'By Key: employee[\'name\']: ' + employee['name'], 62 | 63 | 'By get method: employee.get(\'name\'): ' + employee.get('name') 64 | ]) 65 | 66 | 67 | utils.print_h1('Exist Check / Search') 68 | 69 | name_key_exist = 'Yes' if('name' in employee) else 'No' 70 | name_key_exist_key_list = 'Yes' if('not_exist_key' in employee.keys()) else 'No' 71 | 72 | try_catch_block_exist_check = '' 73 | 74 | try: 75 | value = employee['not_exist_key'] 76 | try_catch_block_exist_check = 'Yes' 77 | # Key exists 78 | except KeyError: 79 | try_catch_block_exist_check = 'No, got Key Error' 80 | # Key doesn't exist 81 | 82 | utils.print_blockquote([ 83 | 'By IN Operator: (\'name\' in employee): ' + name_key_exist, 84 | 'By keys() Method: (\'notname\' in employee.keys()): ' + name_key_exist_key_list, 85 | 'By Try Catch Block (not recommended): ' + try_catch_block_exist_check 86 | ]) 87 | 88 | utils.print_h1('Add / Insert') 89 | 90 | employee['designation'] = 'Software Engineer' 91 | employee.update({ 92 | 'age': '34' 93 | }) 94 | utils.print_blockquote([ 95 | 'By key-value assignment: employee[\'designation\'] = \'Software Engineer\': ' + employee['designation'], 96 | 'By key-value assignment: employee.update({\'age\': \'34\'}): ' + employee['age'], 97 | ]) 98 | 99 | 100 | utils.print_h1('Remove / Delete') 101 | utils.print_h1('Iteration') 102 | -------------------------------------------------------------------------------- /src/leetcode/valid_number.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> 65. Valid Number') 5 | print(''' 6 | A valid number can be split up into these components (in order): 7 | 8 | A decimal number or an integer. 9 | (Optional) An 'e' or 'E', followed by an integer. 10 | 11 | A decimal number can be split up into these components (in order): 12 | 13 | (Optional) A sign character (either '+' or '-'). 14 | One of the following formats: 15 | One or more digits, followed by a dot '.'. 16 | One or more digits, followed by a dot '.', followed by one or more digits. 17 | A dot '.', followed by one or more digits. 18 | An integer can be split up into these components (in order): 19 | 20 | (Optional) A sign character (either '+' or '-'). 21 | One or more digits. 22 | For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. 23 | 24 | Given a string s, return true if s is a valid number. 25 | 26 | Example 1: 27 | 28 | Input: s = "0" 29 | Output: true 30 | Example 2: 31 | 32 | Input: s = "e" 33 | Output: false 34 | Example 3: 35 | 36 | Input: s = "." 37 | Output: false 38 | ''') 39 | 40 | class problemName(object): 41 | def quick(self, s): 42 | pass 43 | def brute_force(self, s): 44 | pass 45 | def sub_optimal(self, s): 46 | pass 47 | def optimal(self, s): 48 | pass 49 | 50 | # Parameters and Expected Values. 51 | param1 = '0' 52 | param11 = 'param11' 53 | expect1 = True 54 | 55 | param2 = 'e' 56 | param22 = 'param22' 57 | expect2 = False 58 | 59 | param3 = '.' 60 | param33 = 'param33' 61 | expect3 = False 62 | 63 | solution = problemName() 64 | solution_title('ProblemName - Quick One') 65 | print_and_assert_new(solution.quick, param1, expected=expect1) 66 | print_and_assert_new(solution.quick, param2, expected=expect2) 67 | print_and_assert_new(solution.quick, param3, expected=expect3) 68 | getTestResult('ProblemName - Quick One') 69 | 70 | timeComplexity('O(n)', 'desc_goes_here') 71 | spaceComplexity('O(n)', 'desc_goes_here') 72 | 73 | solution_title('ProblemName - Brute Force') 74 | print_and_assert_new(solution.brute_force, param1, expected=expect1) 75 | print_and_assert_new(solution.brute_force, param2, expected=expect2) 76 | print_and_assert_new(solution.brute_force, param3, expected=expect3) 77 | getTestResult('ProblemName - Brute Force') 78 | 79 | timeComplexity('O(n)', 'desc_goes_here') 80 | spaceComplexity('O(n)', 'desc_goes_here') 81 | 82 | solution_title('ProblemName - Sub Optimal') 83 | print_and_assert_new(solution.timeOptimized, param1, expected=expect1) 84 | print_and_assert_new(solution.timeOptimized, param2, expected=expect2) 85 | print_and_assert_new(solution.timeOptimized, param3, expected=expect3) 86 | getTestResult('ProblemName - Sub Optimal') 87 | 88 | timeComplexity('O(n)', 'desc_goes_here') 89 | spaceComplexity('O(n)', 'desc_goes_here') 90 | 91 | solution_title('ProblemName - Optimal') 92 | print_and_assert_new(solution.timeOptimized, param1, expected=expect1) 93 | print_and_assert_new(solution.timeOptimized, param2, expected=expect2) 94 | print_and_assert_new(solution.timeOptimized, param3, expected=expect3) 95 | getTestResult('ProblemName - Optimal') 96 | 97 | timeComplexity('O(n + m)', 'desc_goes_here') 98 | spaceComplexity('O(n + m)', 'desc_goes_here') -------------------------------------------------------------------------------- /src/leetcode/add_strings.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> 415. Add Two Strings') 5 | print(''' 6 | Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. 7 | 8 | You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. 9 | ''') 10 | 11 | class addTwoStrings(object): 12 | def quick(self, num1, num2): 13 | result = str(int(num1) + int(num2)) 14 | return result 15 | def brute_force(self, num1, num2): 16 | result, carry = '', 0 17 | num1_index, num2_index = len(num1) - 1, len(num2) - 1 18 | 19 | while(num1_index >= 0 or num2_index >= 0): 20 | first_num = int(num1[num1_index]) if num1_index >= 0 else 0 21 | second_num = int(num2[num2_index]) if num2_index >= 0 else 0 22 | value = (first_num + second_num + carry) % 10 23 | carry = (first_num + second_num + carry) // 10 24 | result = f'{value}{result}' 25 | num1_index -= 1 26 | num2_index -= 1 27 | 28 | if (carry != 0): 29 | result = f'{carry}{result}' 30 | 31 | return result 32 | def timeOptimized(self, num1, num2): 33 | result_list = [] 34 | carry = 0 35 | num1_index, num2_index = len(num1) - 1, len(num2) - 1 36 | 37 | while num1_index >= 0 or num2_index >= 0 or carry: 38 | first_num = int(num1[num1_index]) if num1_index >= 0 else 0 39 | second_num = int(num2[num2_index]) if num2_index >= 0 else 0 40 | 41 | total = first_num + second_num + carry 42 | carry = total // 10 43 | result_list.append(str(total % 10)) 44 | 45 | num1_index -= 1 46 | num2_index -= 1 47 | 48 | return ''.join(reversed(result_list)) 49 | 50 | 51 | solution = addTwoStrings() 52 | solution_title('Add Two Strings - Quick One') 53 | print_and_assert_new(solution.quick, '11', '123', expected='134') 54 | print_and_assert_new(solution.quick, '456', '77', expected='533') 55 | print_and_assert_new(solution.quick, '0', '0', expected='0') 56 | getTestResult('Add Two Strings - Quick One') 57 | 58 | timeComplexity('O(n)', 'Near Linear but + Operators can be expensive for larger numbers') 59 | spaceComplexity('O(n)', 'Linear for storing the result string.') 60 | 61 | solution_title('Add Two Strings - Brute Force') 62 | print_and_assert_new(solution.brute_force, '11', '123', expected='134') 63 | print_and_assert_new(solution.brute_force, '456', '77', expected='533') 64 | print_and_assert_new(solution.brute_force, '0', '0', expected='0') 65 | getTestResult('Add Two Strings - Brute Force') 66 | 67 | solution_title('Add Two Strings - Time Optimized') 68 | print_and_assert_new(solution.timeOptimized, '11', '123', expected='134') 69 | print_and_assert_new(solution.timeOptimized, '456', '77', expected='533') 70 | print_and_assert_new(solution.timeOptimized, '0', '0', expected='0') 71 | getTestResult('Add Two Strings - Time Optimized') 72 | 73 | timeComplexity('O(n + m)', 'Linear by doing key changes like Using a List (result_list), reversed and joined into a single string.\n Reversing a list is O(n), and joining is also O(n), resulting in an overall O(n)') 74 | spaceComplexity('O(n + m)', 'Linear due to primary space consumption is from result_list, which grows to size O(n + m). ') -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | /docs 141 | 142 | # mypy 143 | .mypy_cache/ 144 | .dmypy.json 145 | dmypy.json 146 | 147 | # Pyre type checker 148 | .pyre/ 149 | 150 | # pytype static type analyzer 151 | .pytype/ 152 | 153 | # Cython debug symbols 154 | cython_debug/ 155 | 156 | # PyCharm 157 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 158 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 159 | # and can be added to the global gitignore or merged into this file. For a more nuclear 160 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 161 | #.idea/ 162 | 163 | .DS_Store 164 | 165 | rough-notes 166 | 167 | git_hub_commands 168 | -------------------------------------------------------------------------------- /src/interview/string_substitute.py: -------------------------------------------------------------------------------- 1 | # python module.py interview/string_substitute.py 2 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 3 | #from utilities.commonUtils import timeComplexity, spaceComplexity 4 | 5 | print('\n >>> Substituting character') 6 | print(''' 7 | * Encodes text by substituting character with another one provided in the pair. 8 | * For example pair "ab" defines all "a" chars will be replaced with "b" and all "b" chars will be replaced with "a" 9 | * Examples: 10 | * substitutions = ["ab"], input = "aabbcc", output = "bbaacc" 11 | * substitutions = ["ab", "cd"], input = "adam", output = "bcbm" 12 | * substitutions = ['ab', 'cd'], input = 'AdAm', output = 'BcBm' 13 | * 14 | * @param list substitutions 15 | * @param string text 16 | * @return string 17 | * NOTE: substitutions is lowercase but input can be mix char. So output must follow same case as input 18 | ''') 19 | 20 | class StringSubstitute(object): 21 | def quick(self, sub, text): 22 | def ucase(s): 23 | if 'a' <= s <= 'z': # Check if the character is lowercase 24 | return chr(ord(s) - 32) 25 | return s 26 | 27 | def lcase(s): 28 | if 'A' <= s <= 'Z': # Check if the character is uppercase 29 | return chr(ord(s) + 32) 30 | return s 31 | 32 | swapper = {} 33 | for char in sub: 34 | swapper[char[0]] = char[1] 35 | swapper[char[1]] = char[0] 36 | op = '' 37 | 38 | for s in text: 39 | if ord(s) < 96 and lcase(s) in swapper: 40 | op += ucase(swapper[lcase(s)]) 41 | elif s in swapper: 42 | op += swapper[s] 43 | else: 44 | op += s 45 | return op 46 | def brute_force(self, s): 47 | pass 48 | def sub_optimal(self, s): 49 | pass 50 | def optimal(self, s): 51 | pass 52 | 53 | # Parameters and Expected Values. 54 | param1 = ["ab"] 55 | param11 = "aabbcc" 56 | expect1 = "bbaacc" 57 | 58 | param2 = ["ab", "cd"] 59 | param22 = "adam" 60 | expect2 = "bcbm" 61 | 62 | param3 = ['ab', 'cd'] 63 | param33 = 'AdAm' 64 | expect3 = 'BcBm' 65 | 66 | solution = StringSubstitute() 67 | solution_title('StringSubstitute - Quick One') 68 | print_and_assert_new(solution.quick, param1, param11, expected=expect1) 69 | print_and_assert_new(solution.quick, param2, param22, expected=expect2) 70 | print_and_assert_new(solution.quick, param3, param33, expected=expect3) 71 | # getTestResult('StringSubstitute - Quick One') 72 | 73 | # timeComplexity('O(n)', 'desc_goes_here') 74 | # spaceComplexity('O(n)', 'desc_goes_here') 75 | 76 | # solution_title('StringSubstitute - Brute Force') 77 | # print_and_assert_new(solution.brute_force, param1, param11, expected=expect1) 78 | # print_and_assert_new(solution.brute_force, param2, param22, expected=expect2) 79 | # print_and_assert_new(solution.brute_force, param3, param33, expected=expect3) 80 | # getTestResult('StringSubstitute - Brute Force') 81 | 82 | # timeComplexity('O(n)', 'desc_goes_here') 83 | # spaceComplexity('O(n)', 'desc_goes_here') 84 | 85 | # solution_title('StringSubstitute - Sub Optimal') 86 | # print_and_assert_new(solution.timeOptimized, param1, param11, expected=expect1) 87 | # print_and_assert_new(solution.timeOptimized, param2, param22, expected=expect2) 88 | # print_and_assert_new(solution.timeOptimized, param3, param33, expected=expect3) 89 | # getTestResult('StringSubstitute - Sub Optimal') 90 | 91 | # timeComplexity('O(n)', 'desc_goes_here') 92 | # spaceComplexity('O(n)', 'desc_goes_here') 93 | 94 | # solution_title('StringSubstitute - Optimal') 95 | # print_and_assert_new(solution.timeOptimized, param1, param11, expected=expect1) 96 | # print_and_assert_new(solution.timeOptimized, param2, param22, expected=expect2) 97 | # print_and_assert_new(solution.timeOptimized, param3, param33, expected=expect3) 98 | # getTestResult('StringSubstitute - Optimal') 99 | 100 | # timeComplexity('O(n + m)', 'desc_goes_here') 101 | # spaceComplexity('O(n + m)', 'desc_goes_here') -------------------------------------------------------------------------------- /src/leetcode/strings/67_Add_Binary.py: -------------------------------------------------------------------------------- 1 | from utilities.testUtils import solution_title, print_and_assert_new, getTestResult 2 | from utilities.commonUtils import timeComplexity, spaceComplexity 3 | 4 | print('\n >>> 67. Add Binary') 5 | print(''' 6 | Given two binary strings a and b, return their sum as a binary string. 7 | 8 | Example 1: 9 | 10 | Input: a = "11", b = "1" 11 | Output: "100" 12 | Example 2: 13 | 14 | Input: a = "1010", b = "1011" 15 | Output: "10101" 16 | 17 | Constraints: 18 | 1 <= a.length, b.length <= 104 19 | a and b consist only of '0' or '1' characters. 20 | Each string does not contain leading zeros except for the zero itself. 21 | ''') 22 | 23 | class AddBinary(object): 24 | def quick(self, a, b): 25 | sum = int(a, 2) + int(b, 2) 26 | return bin(sum)[2:] 27 | def brute_force(self, a, b): 28 | result, carry, i, j = "", 0, len(a) - 1, len(b) - 1 29 | 30 | while i >= 0 or j >= 0 or carry: 31 | total = carry 32 | if i >= 0: 33 | total += int(a[i]) 34 | i -= 1 35 | if j >= 0: 36 | total += int(b[j]) 37 | j -= 1 38 | carry = total // 2 39 | result = str(total % 2) + result 40 | 41 | return result 42 | def sub_optimal(self, a, b): 43 | x, y = int(a, 2), int(b, 2) 44 | while y: 45 | answer = x ^ y 46 | carry = (x & y) << 1 47 | x, y = answer, carry 48 | return bin(x)[2:] 49 | def optimal(self, a, b): 50 | result, carry = "", 0 51 | p1, p2 = len(a) - 1, len(b) - 1 52 | 53 | while p1 >= 0 or p2 >= 0 or carry: 54 | if p1 >= 0: 55 | carry += int(a[p1]) 56 | p1 -= 1 57 | if p2 >= 0: 58 | carry += int(b[p2]) 59 | p2 -= 1 60 | carry, bit = divmod(carry, 2) 61 | result = str(bit) + result 62 | 63 | return result 64 | 65 | # Parameters and Expected Values. 66 | param1 = '11' 67 | param11 = '1' 68 | expect1 = '100' 69 | 70 | param2 = '1010' 71 | param22 = '1011' 72 | expect2 = '10101' 73 | 74 | param3 = '0' 75 | param33 = '0' 76 | expect3 = '0' 77 | 78 | solution = AddBinary() 79 | solution_title('AddBinary - Quick One') 80 | print_and_assert_new(solution.quick, param1, param11, expected=expect1) 81 | print_and_assert_new(solution.quick, param2, param22, expected=expect2) 82 | print_and_assert_new(solution.quick, param3, param33, expected=expect3) 83 | getTestResult('AddBinary - Quick One') 84 | 85 | timeComplexity('O(N + M)', 'where N and M are the lengths of strings a and b, respectively. The conversion functions (int and bin) run in linear time relative to the length of the input strings.') 86 | spaceComplexity('O(1)', 'as we only use a fixed amount of extra space.') 87 | 88 | solution_title('AddBinary - Brute Force') 89 | print_and_assert_new(solution.brute_force, param1, param11, expected=expect1) 90 | print_and_assert_new(solution.brute_force, param2, param22, expected=expect2) 91 | print_and_assert_new(solution.brute_force, param3, param33, expected=expect3) 92 | getTestResult('AddBinary - Brute Force') 93 | 94 | timeComplexity('O(max(N, M))', 'where N and M are the lengths of strings a and b.') 95 | spaceComplexity('O(max(N, M))', 'as we store the result which can be as long as the longer string plus one for the carry bit.') 96 | 97 | solution_title('AddBinary - Sub Optimal using Bit Manipulation') 98 | print_and_assert_new(solution.sub_optimal, param1, param11, expected=expect1) 99 | print_and_assert_new(solution.sub_optimal, param2, param22, expected=expect2) 100 | print_and_assert_new(solution.sub_optimal, param3, param33, expected=expect3) 101 | getTestResult('AddBinary - Sub Optimal using Bit Manipulation') 102 | 103 | timeComplexity('O(N + M)', 'depends on the lengths of the binary representations.') 104 | spaceComplexity('O(1)', 'space used does not depend on the input size.') 105 | 106 | solution_title('AddBinary - Optimal using Two-Pointer Approach') 107 | print_and_assert_new(solution.optimal, param1, param11, expected=expect1) 108 | print_and_assert_new(solution.optimal, param2, param22, expected=expect2) 109 | print_and_assert_new(solution.optimal, param3, param33, expected=expect3) 110 | getTestResult('AddBinary - Optimal using Two-Pointer Approach') 111 | 112 | timeComplexity('O(max(N, M))', 'optimal because we have to inspect each character of both strings in the worst case.') 113 | spaceComplexity('O(max(N, M))', 'resulting string size will be at most max(N, M) + 1') -------------------------------------------------------------------------------- /src/data_structures/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Data Structures Types. 2 | 3 | ## Linear 4 | 5 | | Data Structure | Types | Operation Types | Real-time Examples | 6 | | -------------- | ------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------ | 7 | | Array | Fixed-size, Dynamic Array | Access, Insert, Delete (fixed size) | 1. Days in a week: ["Mon", "Tue", ...] | 8 | | | | | 2. Temperature readings: [72, 68, ...] | 9 | | Linked List | Single, Doubly, Circular | Access, Insert, Delete in Head (First Item) | 1. Music playlist (each song to the next) | 10 | | | | Access, Insert, Delete in Tail (Last Item) | 2. Treasure hunt (each clue to the next location)| 11 | | | | Access, Insert, Delete in Middle Node | | 12 | | | | Search for a Value | | 13 | | Stack | Array-based, Linked List-based | Push, Pop, Peek | 1. Pile of plates (last on, first off) | 14 | | | | | 2. Undo in software (last action reversed first) | 15 | | Queue | Simple Queue, Circular Queue, Priority Queue | Enqueue, Dequeue, Peek | 1. Line at a bank counter | 16 | | | | | 2. Call center queue | 17 | 18 | 19 | 20 | ## Non Linear 21 | 22 | | Data Structure | Types | Operation Types | Real-time Examples | 23 | | -------------- | --------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------ | 24 | | Tree | Binary Tree, AVL Tree, Red-Black Tree | Insert, Delete, Traversal | 1. Organizational chart of a company | 25 | | | B-Tree, Binary Search Tree, N-ary Tree | | 2. Family tree showing genealogical relationships| 26 | | Graph | Directed, Undirected, Weighted | Add/Remove Vertex, Add/Remove Edge, Search, Path Finding | 1. Road network (intersections and roads) | 27 | | | Graph, Tree, Acyclic Graph | | 2. Facebook's friend network | 28 | | Heap | Binary Heap, Fibonacci Heap | Insert, Delete, Find Max/Min | 1. Priority scheduling (higher priority first) | 29 | | | Min Heap, Max Heap | | 2. Finding the largest/smallest element quickly | 30 | | Hash Table | Chaining, Open Addressing | Insert, Delete, Access | 1. Book indexing (word and page number) | 31 | | | Linear Probing, Quadratic Probing | | 2. User info on website by username | 32 | | Set | Hash Set, Tree Set | Add, Remove, Contains | 1. Unique collection of items (tags in a blog) | 33 | | | | | 2. Filtering duplicates from a list | 34 | | Trie | Basic Trie, Compressed Trie | Insert, Search, Delete | 1. Auto-complete in search engines | 35 | | | Radix Trie, Suffix Trie | | 2. Spell checker in word processors | 36 | 37 | 38 | --------------------------------------------------------------------------------