├── .github └── workflows │ ├── code_formatter.yml │ └── python.yml ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── basics ├── __init__.py ├── boolean_example.py ├── call_external_command.py ├── class_exmaple.py ├── datetime_example.py ├── deque_example.py ├── do_while_example.py ├── exception_example.py ├── file_example.py ├── for_example.py ├── function_example.py ├── input_example.py ├── iterator_example.py ├── json_example.py ├── lambda_example.py ├── log_example.py ├── math_example.py ├── module_example.py ├── regex_example.py ├── sets_example.py ├── string_example.py ├── variable.py └── while_example.py ├── ciphers ├── __init__.py └── caesar.py ├── conversions ├── __init__.py ├── binary_to_decimal.py └── temperature_conversion.py ├── data_structures ├── __init__.py ├── graph │ └── __init__.py ├── heap │ └── __init__.py ├── linked_list │ └── __init__.py ├── matrix │ └── __init__.py ├── queue │ ├── __init__.py │ └── queue.py ├── stack │ ├── __init__.py │ └── stack.py └── tree │ └── __init__.py ├── dynamicprogramming ├── __init__.py └── fibonacci_dp.py ├── maths ├── __init__.py ├── absolute.py ├── absolute_max.py ├── absolute_min.py ├── addition.py ├── aliquot_sum.py ├── area.py ├── average.py ├── ceil.py ├── count_digits.py ├── count_digits_recursion.py ├── cube_number.py ├── even_check.py ├── factorial.py ├── factorial_recursion.py ├── fibonacci.py ├── fibonacci_recursion.py ├── fibonacci_with_list.py ├── first_digit.py ├── first_digit_by_str.py ├── first_digit_recursion.py ├── floor.py ├── leap_year.py ├── median.py ├── mode.py ├── odd_check.py ├── subtract.py ├── sum_big_numbers.py ├── sum_of_factorial.py ├── sum_to_n.py ├── sum_to_n_formula.py ├── sum_to_n_recursion.py ├── to_integer.py └── tower_of_hanio.py ├── searches ├── __init__.py ├── binary_search.py ├── binary_search_recursion.py ├── linear_search.py └── linear_search_recursion.py ├── sorts ├── bubble_sort.py ├── bubble_sort_recursion.py ├── insertion_sort.py ├── merge_sort.py ├── quick_sort.py ├── selection_sort.py └── shell_sort.py └── strings ├── __init__.py ├── contains.py ├── palindrome.py ├── remove_whitespace.py └── reverse.py /.github/workflows/code_formatter.yml: -------------------------------------------------------------------------------- 1 | name: Code Formatter 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | lint: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions/setup-python@v2 11 | - run: pip install black 12 | - run: black --check . 13 | - name: Commit black changes 14 | if: failure() 15 | run: | 16 | black . 17 | git config --global user.name github-actions 18 | git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' 19 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY 20 | git commit -am "Formatted with psf/black" 21 | git push --force origin HEAD:$GITHUB_REF -------------------------------------------------------------------------------- /.github/workflows/python.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python application 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up Python 3.8 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: 3.8 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | pip install flake8 pytest 27 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 28 | - name: Lint with flake8 29 | run: | 30 | # stop the build if there are Python syntax errors or undefined names 31 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 32 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 33 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 34 | - name: Test with pytest 35 | run: | 36 | pytest --doctest-modules 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | venv -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | script: 3 | - pytest --doctest-modules 4 | 5 | notifications: 6 | webhooks: https://www.travisbuddy.com/ 7 | on_success: never 8 | on_failure: always -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing guidelines 2 | 3 | ## Before contributing 4 | 5 | 👏👏 Welcome to [examplehub/Python](https://github.com/examplehub/Python) ! Before sending your pull requests. Please make sure that you **read the whole guidelines**. 6 | 7 | ## Contributing 8 | 9 | #### How to contribute 10 | 1. Fork the project to your github account & clone locally computer. 11 | 2. Create an upstream remote and sync your local copy before you branch. 12 | 3. Branch for each separate piece of work. 13 | 4. Do the work, write good commit messages, and read the `CONTRIBUTING.md`. 14 | 5. Push to your origin repository. 15 | 6. Create a new PR in GitHub. 16 | 7. Waiting to be review by the maintainers. 17 | 18 | #### Code Style 19 | * Please follow [PEP 8](https://www.python.org/dev/peps/pep-0008/) Coding Style. 20 | * Single letter variable names are old school so please avoid them unless their life only spans a few lines. 21 | * Expand acronyms because `gcd()` is hard to understand but `greatest_common_divisor()` is not. 22 | * Write `test unit` to test all your functions. 23 | * [More details](https://docs.python.org/3/tutorial/controlflow.html#intermezzo-coding-style) about Code Style. 24 | 25 | ### Thanks for your contribution 😊 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Programming Examples 2 | 3 | [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/examplehub/Python) 4 | [![Build Status](https://img.shields.io/travis/examplehub/Python.svg?label=Travis%20CI&logo=travis&style=flat-square)](https://travis-ci.com/examplehub/Python)  5 | [![LGTM](https://img.shields.io/lgtm/alerts/github/examplehub/Python.svg?label=LGTM&logo=LGTM&style=flat-square)](https://lgtm.com/projects/g/examplehub/Python/alerts)  6 | [![code style: black](https://img.shields.io/static/v1?label=code%20style&message=black&color=black&style=flat-square)](https://github.com/psf/black) 7 | [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/examplehub/Python/blob/master/CONTRIBUTING.md)  8 | [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?logo=paypal&style=flat-square)](https://paypal.me/duyuanchao?locale.x=en_US)  9 | ![](https://img.shields.io/github/repo-size/examplehub/Python.svg?label=Repo%20size&style=flat-square)  10 | 11 | Python programming examples for educational purpose. 12 | 13 | ## Contribution Guidelines 14 | Please read our [Contribution Guidelines](https://github.com/examplehub/Python/blob/master/CONTRIBUTING.md) before you contribute. 15 | 16 | ## List of Examples 17 | See our [directory](https://github.com/examplehub/Python/blob/master/DIRECTORY.md) -------------------------------------------------------------------------------- /basics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/basics/__init__.py -------------------------------------------------------------------------------- /basics/boolean_example.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | """ 3 | Boolean example. 4 | 5 | >>> 3 > 4 6 | False 7 | >>> 3 == 4 8 | False 9 | >>> 3 < 4 10 | True 11 | >>> 3 < 4 < 5 12 | True 13 | >>> 3 < 4 > 5 14 | False 15 | 16 | >>> name = "Python" 17 | >>> age = 29 18 | >>> name == "Python" and age == 29 19 | True 20 | 21 | >>> 'a' in 'abc' 22 | True 23 | >>> 'd' in 'abc' 24 | False 25 | >>> 'd' not in 'abc' 26 | True 27 | 28 | >>> isinstance(False, bool) 29 | True 30 | >>> isinstance(True, bool) 31 | True 32 | >>> isinstance(5, int) 33 | True 34 | >>> isinstance(3.14, float) 35 | True 36 | 37 | >>> bool('') 38 | False 39 | >>> bool(0) 40 | False 41 | >>> bool(None) 42 | False 43 | >>> bool(' ') 44 | True 45 | >>> bool(1) 46 | True 47 | >>> bool("hi") 48 | True 49 | >>> bool([]) 50 | False 51 | >>> bool(['']) 52 | True 53 | """ 54 | 55 | 56 | if __name__ == "__main__": 57 | from doctest import testmod 58 | 59 | testmod() 60 | -------------------------------------------------------------------------------- /basics/call_external_command.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> import subprocess 4 | >>> _ = subprocess.run(["ls", "-l"]) 5 | """ 6 | 7 | 8 | if __name__ == "__main__": 9 | from doctest import testmod 10 | 11 | testmod() 12 | -------------------------------------------------------------------------------- /basics/class_exmaple.py: -------------------------------------------------------------------------------- 1 | class People: 2 | """ 3 | >>> jack = People("Jack", 23) 4 | >>> jack.name 5 | 'Jack' 6 | >>> jack.age 7 | 23 8 | >>> jack.print_info() 9 | my name is Jack, my age is 23 10 | >>> jack.age += 1 11 | >>> jack.age 12 | 24 13 | >>> del jack.age 14 | >>> hasattr(jack, "age") 15 | False 16 | >>> del jack 17 | >>> "jack" in locals() 18 | False 19 | """ 20 | 21 | def __init__(self, name, age): 22 | self.name = name 23 | self.age = age 24 | 25 | def print_info(self): 26 | print(f"my name is {self.name}, my age is {self.age}") 27 | 28 | 29 | class Student(People): 30 | """ 31 | >>> stu = Student("Tom", 19, 99) 32 | >>> stu.print_info() 33 | my name is Tom, my age is 19, my grade is 99 34 | """ 35 | 36 | def __init__(self, name, age, grade): 37 | super().__init__(name, age) 38 | self.grade = grade 39 | 40 | def print_info(self): 41 | print(f"my name is {self.name}, my age is {self.age}, my grade is {self.grade}") 42 | 43 | 44 | class TodoClass: 45 | pass 46 | 47 | 48 | if __name__ == "__main__": 49 | from doctest import testmod 50 | 51 | testmod() 52 | -------------------------------------------------------------------------------- /basics/datetime_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> import datetime 4 | >>> year = datetime.datetime.now().year 5 | >>> year >= 2020 6 | True 7 | 8 | >>> time = datetime.datetime(2100, 10, 5) 9 | >>> str(time) 10 | '2100-10-05 00:00:00' 11 | """ 12 | pass 13 | 14 | 15 | if __name__ == "__main__": 16 | from doctest import testmod 17 | 18 | testmod() 19 | -------------------------------------------------------------------------------- /basics/deque_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> from collections import deque 4 | >>> queue = deque(["Python", "Java", "C"]) 5 | >>> len(queue) 6 | 3 7 | >>> queue 8 | deque(['Python', 'Java', 'C']) 9 | >>> queue.popleft() 10 | 'Python' 11 | >>> queue.popleft() 12 | 'Java' 13 | >>> queue.clear() 14 | >>> len(queue) 15 | 0 16 | >>> queue 17 | deque([]) 18 | >>> queue.popleft() 19 | Traceback (most recent call last): 20 | ... 21 | IndexError: pop from an empty deque 22 | """ 23 | 24 | 25 | if __name__ == "__main__": 26 | from doctest import testmod 27 | 28 | testmod() 29 | -------------------------------------------------------------------------------- /basics/do_while_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | do-while example. 4 | 5 | >>> i = 1 6 | >>> while True: 7 | ... print(i, end='') 8 | ... i += 1 9 | ... if i == 6: 10 | ... break 11 | 12345 12 | 13 | >>> i = 5 14 | >>> while True: 15 | ... print(i, end='') 16 | ... i -= 1 17 | ... if i == 0: 18 | ... break 19 | 54321 20 | """ 21 | 22 | 23 | if __name__ == "__main__": 24 | from doctest import testmod 25 | 26 | testmod() 27 | -------------------------------------------------------------------------------- /basics/exception_example.py: -------------------------------------------------------------------------------- 1 | def divide(a: int, b: int) -> int: 2 | """ 3 | >>> divide(10, 2) 4 | 5 5 | >>> divide(10, 0) 6 | Traceback (most recent call last): 7 | ... 8 | ValueError: divisor can't be zero 9 | """ 10 | try: 11 | return a // b 12 | except ArithmeticError: 13 | raise ValueError("divisor can't be zero") 14 | finally: 15 | pass # do anything you want. 16 | 17 | 18 | if __name__ == "__main__": 19 | from doctest import testmod 20 | 21 | testmod() 22 | -------------------------------------------------------------------------------- /basics/file_example.py: -------------------------------------------------------------------------------- 1 | def open_file(filename: str): 2 | """ 3 | >>> open_file("hello.txt") 4 | No such file or directory: hello.txt 5 | 6 | >>> import os 7 | >>> if os.path.exists("../LICENSE"): 8 | ... f = open_file("../LICENSE") 9 | ... _ = f is not None 10 | ... _ = f.readline().strip() == "Apache License" 11 | ... _ = f.readline().strip() == "Version 2.0, January 2004" 12 | ... f.close() 13 | ... _ = f.closed 14 | ... with open("../LICENSE") as f: 15 | ... _ = f.readline().strip() == "Apache License" 16 | ... _ = f.readline().strip() == "Version 2.0, January 2004" 17 | """ 18 | try: 19 | f = open(filename) 20 | return f 21 | except FileNotFoundError: 22 | print(f"No such file or directory: {filename}") 23 | 24 | 25 | def writefile_append() -> None: 26 | """ 27 | >>> f = open("temp_file1.txt", "a") 28 | >>> f is not None 29 | True 30 | >>> f.writelines("ExampleHub\\n") 31 | >>> f.writelines("Python\\n") 32 | >>> f.close() 33 | >>> f.closed 34 | True 35 | >>> 36 | """ 37 | pass 38 | 39 | 40 | def writefile_override() -> None: 41 | """ 42 | >>> f = open("temp_file2.txt", "w") 43 | >>> f is not None 44 | True 45 | >>> f.writelines("ExampleHub\\n") 46 | >>> f.writelines("Python\\n") 47 | >>> f.close() 48 | >>> f.closed 49 | True 50 | """ 51 | pass 52 | 53 | 54 | def delete_file() -> None: 55 | """ 56 | >>> import os 57 | >>> os.path.exists("hello.txt") == False 58 | True 59 | 60 | >>> if os.path.exists("example_file.txt"): 61 | ... os.remove("example_file.txt") 62 | 63 | >>> if os.path.exists("folder_path"): 64 | ... os.rmdir("folder_path") 65 | """ 66 | pass 67 | 68 | 69 | if __name__ == "__main__": 70 | from doctest import testmod 71 | 72 | testmod() 73 | -------------------------------------------------------------------------------- /basics/for_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | for example. 4 | 5 | >>> for item in ["Python", "Java", "Google"]: 6 | ... print(item) 7 | Python 8 | Java 9 | Google 10 | 11 | >>> for char in "Python": 12 | ... print(char, end='') 13 | Python 14 | 15 | >>> for i in range(0, 6): 16 | ... print(i, end='') 17 | 012345 18 | 19 | >>> for i in range(1, 10, 2): 20 | ... print(i, end='') 21 | 13579 22 | 23 | >>> for i in range(0, 6): 24 | ... print(i, end='') 25 | ... else: 26 | ... print(6, end='') 27 | 0123456 28 | 29 | >>> for i in range(0, 3): 30 | ... for j in range(0, 3): 31 | ... print(f"i={i}, j={j}") 32 | i=0, j=0 33 | i=0, j=1 34 | i=0, j=2 35 | i=1, j=0 36 | i=1, j=1 37 | i=1, j=2 38 | i=2, j=0 39 | i=2, j=1 40 | i=2, j=2 41 | 42 | >>> for _ in range(0, 100): 43 | ... pass 44 | 45 | >>> sum(i for i in range(1, 101)) 46 | 5050 47 | 48 | >>> for i in range(1, 6): 49 | ... for _ in range(1, i + 1): 50 | ... print("*", end='') 51 | ... print() 52 | * 53 | ** 54 | *** 55 | **** 56 | ***** 57 | """ 58 | 59 | 60 | if __name__ == "__main__": 61 | from doctest import testmod 62 | 63 | testmod() 64 | -------------------------------------------------------------------------------- /basics/function_example.py: -------------------------------------------------------------------------------- 1 | def my_function() -> None: 2 | """ 3 | No argument, No Returns function. 4 | >>> my_function() 5 | hi 6 | """ 7 | print("hi") 8 | 9 | 10 | def add(a: int, b: int) -> int: 11 | """ 12 | Add of a and b. 13 | >>> add(3, 3) 14 | 6 15 | >>> add(3, -3) 16 | 0 17 | >>> add(99, 1) 18 | 100 19 | """ 20 | return a + b 21 | 22 | 23 | def add_more(*args): 24 | """ 25 | Arbitrary Arguments 26 | 27 | >>> add_more(1, 2, 3) 28 | 6 29 | """ 30 | return sum(args) 31 | 32 | 33 | def calculate(a: int, operator: str, b: int) -> int: 34 | """ 35 | Simple calculator. 36 | 37 | >>> calculate(a = 3, operator = "+", b = 4) 38 | 7 39 | >>> calculate(a = 3, operator = "-", b = 4) 40 | -1 41 | >>> calculate(a = 3, operator = "*", b = 4) 42 | 12 43 | >>> calculate(a = 3, operator = "/", b = 4) 44 | 0 45 | >>> calculate(a = 3, operator = "!", b = 4) 46 | Traceback (most recent call last): 47 | ... 48 | ValueError: Invalid operator 49 | """ 50 | if operator == "+": 51 | return a + b 52 | elif operator == "-": 53 | return a - b 54 | elif operator == "*": 55 | return a * b 56 | elif operator == "/": 57 | return a // b 58 | else: 59 | raise ValueError("Invalid operator") 60 | 61 | 62 | def intro(**kwargs): 63 | """ 64 | >>> intro(name="Python", age = 29) 65 | key=name, value=Python 66 | key=age, value=29 67 | """ 68 | for ( 69 | key, 70 | value, 71 | ) in kwargs.items(): 72 | print(f"key={key}, value={value}") 73 | 74 | 75 | def print_number(number: int = 5) -> int: 76 | """ 77 | Default parameter. 78 | 79 | >>> print_number(100) 80 | 100 81 | >>> print_number() 82 | 5 83 | """ 84 | print(number) 85 | 86 | 87 | def get_max(array): 88 | """ 89 | Pass list as parameter. 90 | 91 | >>> get_max([1, 3, 5, 7, 9]) 92 | 9 93 | """ 94 | max_value = array[0] 95 | for item in array: 96 | if item > max_value: 97 | max_value = item 98 | return max_value 99 | 100 | 101 | def pass_function(): 102 | """ 103 | >>> pass_function() 104 | """ 105 | pass # do anything. 106 | 107 | 108 | def factorial(n: int) -> int: 109 | """ 110 | Recursion function. 111 | 112 | >>> factorial(0) 113 | 1 114 | >>> factorial(1) 115 | 1 116 | >>> factorial(5) 117 | 120 118 | >>> factorial(6) 119 | 720 120 | """ 121 | return 1 if n == 0 or n == 1 else n * factorial(n - 1) 122 | 123 | 124 | if __name__ == "__main__": 125 | from doctest import testmod 126 | 127 | testmod() 128 | -------------------------------------------------------------------------------- /basics/input_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | name = input("Please input your name:") 3 | age = int(input("Please input your age:").strip()) 4 | print(f"You name is {name}, age is {age}") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /basics/iterator_example.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | """ 3 | >>> array = range(0, 5) 4 | >>> iterator = iter(array) 5 | >>> for item in iterator: 6 | ... print(item, end='') 7 | 01234 8 | 9 | >>> iterator = iter(array) 10 | >>> next(iterator) 11 | 0 12 | >>> next(iterator) 13 | 1 14 | >>> next(iterator) 15 | 2 16 | >>> next(iterator) 17 | 3 18 | >>> next(iterator) 19 | 4 20 | >>> next(iterator) 21 | Traceback (most recent call last): 22 | ... 23 | StopIteration 24 | """ 25 | 26 | 27 | class Counter: 28 | """ 29 | >>> counter = Counter(5) 30 | >>> iterator = iter(counter) 31 | >>> for item in iterator: 32 | ... print(item) 33 | 1 34 | 2 35 | 3 36 | 4 37 | 5 38 | """ 39 | 40 | def __init__(self, count): 41 | self.count = count 42 | 43 | def __iter__(self): 44 | self.num = 1 45 | return self 46 | 47 | def __next__(self): 48 | if self.num <= self.count: 49 | temp = self.num 50 | self.num += 1 51 | return temp 52 | else: 53 | raise StopIteration 54 | 55 | 56 | class InfiniteCounter: 57 | def __init__(self): 58 | self.num = 0 59 | 60 | def __iter__(self): 61 | return self 62 | 63 | def __next__(self): 64 | self.num += 1 65 | return self.num 66 | 67 | 68 | if __name__ == "__main__": 69 | from doctest import testmod 70 | 71 | testmod() 72 | 73 | # counter = InfiniteCounter() 74 | # for item in iter(counter): 75 | # print(item) 76 | -------------------------------------------------------------------------------- /basics/json_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> import json 4 | >>> json_data = '{ "name":"Jack", "age":23}' 5 | >>> data = json.loads(json_data) 6 | >>> data["name"] 7 | 'Jack' 8 | >>> data["age"] 9 | 23 10 | 11 | >>> student = {"name": "Jack", "age":23, "id": "2020101039"} 12 | >>> data = json.dumps(student) 13 | >>> data 14 | '{"name": "Jack", "age": 23, "id": "2020101039"}' 15 | """ 16 | 17 | 18 | if __name__ == "__main__": 19 | from doctest import testmod 20 | 21 | testmod() 22 | -------------------------------------------------------------------------------- /basics/lambda_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | Lambda example. 4 | 5 | >>> my_pow = lambda n : n * n 6 | >>> my_pow(3) 7 | 9 8 | 9 | >>> add = lambda a, b : a + b 10 | >>> add(3, 4) 11 | 7 12 | """ 13 | 14 | 15 | if __name__ == "__main__": 16 | from doctest import testmod 17 | 18 | testmod() 19 | -------------------------------------------------------------------------------- /basics/log_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | import logging 3 | 4 | logging.debug("Debugging information") 5 | logging.info("Informational message") 6 | logging.warning("Warning:config file %s not found", "server.conf") 7 | logging.error("Error occurred") 8 | logging.critical("Critical error -- shutting down") 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /basics/math_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> max(range(0, 10)) 4 | 9 5 | >>> min(range(0, 10)) 6 | 0 7 | >>> abs(-3.14) 8 | 3.14 9 | >>> pow(3, 3) 10 | 27 11 | >>> pow(2, 10) 12 | 1024 13 | 14 | >>> import math 15 | >>> math.sqrt(9) 16 | 3.0 17 | >>> math.sqrt(100) 18 | 10.0 19 | >>> math.floor(2.5) 20 | 2 21 | >>> math.floor(2.6) 22 | 2 23 | >>> math.floor(-2.4) 24 | -3 25 | >>> math.floor(-2.5) 26 | -3 27 | >>> math.floor(-2.9) 28 | -3 29 | >>> math.ceil(2.4) 30 | 3 31 | >>> math.ceil(2.9) 32 | 3 33 | >>> math.ceil(-2.4) 34 | -2 35 | >>> math.ceil(-2.9) 36 | -2 37 | >>> math.pi 38 | 3.141592653589793 39 | """ 40 | 41 | 42 | if __name__ == "__main__": 43 | from doctest import testmod 44 | 45 | testmod() 46 | -------------------------------------------------------------------------------- /basics/module_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> import math 4 | >>> math.pow(2, 3) == 8 5 | True 6 | 7 | >>> from sorts.bubble_sort import bubble_sort 8 | >>> bubble_sort([1, 3, 5, 2, 4]) == sorted([1, 3, 5, 2, 4]) 9 | True 10 | 11 | >>> from sorts.selection_sort import selection_sort as sort 12 | >>> sort(['a', 'c', 'd', 'b']) 13 | ['a', 'b', 'c', 'd'] 14 | 15 | """ 16 | 17 | 18 | if __name__ == "__main__": 19 | from doctest import testmod 20 | 21 | testmod() 22 | -------------------------------------------------------------------------------- /basics/regex_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> import re 4 | >>> text = "ExampleHub - Python" 5 | >>> print(re.findall("[A-Z]", text)) 6 | ['E', 'H', 'P'] 7 | 8 | >>> text = "a1b2c3" 9 | >>> re.findall("\\d", text) 10 | ['1', '2', '3'] 11 | 12 | >>> text = "abc123abd" 13 | >>> re.findall("a.d", text) 14 | ['abd'] 15 | 16 | >>> text = "abcABabc123abd123" 17 | >>> re.findall("^abc", text) 18 | ['abc'] 19 | 20 | >>> text = "ExampleHub" 21 | >>> re.search("Hub$", text) is not None 22 | True 23 | 24 | >>> text = "ExampleHub Python" 25 | >>> re.search("Pp*", text) is not None 26 | True 27 | """ 28 | 29 | 30 | if __name__ == "__main__": 31 | from doctest import testmod 32 | 33 | testmod() 34 | -------------------------------------------------------------------------------- /basics/sets_example.py: -------------------------------------------------------------------------------- 1 | def main() -> None: 2 | """ 3 | >>> languages = {"Python", "Java", "C", "JavaScript", "Python", "C"} 4 | >>> len(languages) 5 | 4 6 | >>> "Java" in languages 7 | True 8 | >>> "Python" in languages 9 | True 10 | >>> "c" in languages 11 | False 12 | >>> my_langs = {"Python", "Golang", "C"} 13 | >>> sorted(list(my_langs & languages)) 14 | ['C', 'Python'] 15 | >>> sorted(list(my_langs | languages)) 16 | ['C', 'Golang', 'Java', 'JavaScript', 'Python'] 17 | >>> sorted(list(my_langs ^ languages)) 18 | ['Golang', 'Java', 'JavaScript'] 19 | >>> sorted(list(my_langs - languages)) 20 | ['Golang'] 21 | >>> sorted(list(languages - my_langs)) 22 | ['Java', 'JavaScript'] 23 | """ 24 | 25 | 26 | if __name__ == "__main__": 27 | from doctest import testmod 28 | 29 | testmod() 30 | -------------------------------------------------------------------------------- /basics/string_example.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | """ 3 | >>> print("ExampleHub") 4 | ExampleHub 5 | 6 | >>> my_str = "ExampleHub" 7 | >>> print(my_str) 8 | ExampleHub 9 | 10 | >>> my_str = "abc" 11 | >>> my_str[0] 12 | 'a' 13 | >>> my_str[1] 14 | 'b' 15 | >>> my_str[2] 16 | 'c' 17 | >>> my_str[-1] 18 | 'c' 19 | 20 | >>> my_str = "123456" 21 | >>> for i in range(0, 6): 22 | ... assert my_str[i] == str(i + 1) 23 | >>> for char in my_str: 24 | ... print(char, end='') 25 | 123456 26 | 27 | >>> my_str = "abc123456" 28 | >>> my_str[0:3] 29 | 'abc' 30 | >>> my_str[:3] 31 | 'abc' 32 | >>> my_str[3:9] 33 | '123456' 34 | >>> my_str[3:] 35 | '123456' 36 | >>> my_str[-3:-1] 37 | '45' 38 | >>> my_str[-3:] 39 | '456' 40 | >>> my_str[::-1] 41 | '654321cba' 42 | 43 | >>> len("") 44 | 0 45 | >>> my_str = "abc123" 46 | >>> len(my_str) 47 | 6 48 | 49 | >>> my_str = " I love python. " 50 | >>> my_str.strip() 51 | 'I love python.' 52 | >>> my_str.strip().lower() 53 | 'i love python.' 54 | >>> my_str.strip().upper() 55 | 'I LOVE PYTHON.' 56 | >>> my_str.strip().replace("python", "u") 57 | 'I love u.' 58 | >>> my_str.split() 59 | ['I', 'love', 'python.'] 60 | >>> "love" in my_str 61 | True 62 | >>> "LOVE" not in my_str 63 | True 64 | 65 | >>> first_name = "Example" 66 | >>> last_name = "Hub" 67 | >>> name = first_name + last_name 68 | >>> name 69 | 'ExampleHub' 70 | >>> name = first_name + last_name + "/Python" 71 | >>> name 72 | 'ExampleHub/Python' 73 | >>> my_str = "6" * 3 74 | >>> my_str 75 | '666' 76 | 77 | >>> name = "Python" 78 | >>> age = 29 79 | >>> intro = "My name is {}. I'am {}.".format(name, age) 80 | >>> intro 81 | "My name is Python. I'am 29." 82 | 83 | >>> import math 84 | >>> pi_str = "pi = {:.2f}" 85 | >>> pi_str = pi_str.format(math.pi) 86 | >>> pi_str 87 | 'pi = 3.14' 88 | 89 | >>> pi_str = f"pi = {math.pi}" 90 | >>> pi_str 91 | 'pi = 3.141592653589793' 92 | 93 | >>> pi_str = f"pi = {math.pi:.2f}" 94 | >>> pi_str 95 | 'pi = 3.14' 96 | 97 | >>> my_str = "abc" 98 | >>> del my_str 99 | >>> 'my_str' not in locals() 100 | True 101 | """ 102 | 103 | 104 | if __name__ == "__main__": 105 | from doctest import testmod 106 | 107 | testmod() 108 | -------------------------------------------------------------------------------- /basics/variable.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | """ 3 | >>> a = 3 4 | >>> b = 4 5 | >>> a + b 6 | 7 7 | >>> a - b 8 | -1 9 | >>> a * b 10 | 12 11 | >>> a / b 12 | 0.75 13 | >>> a // b 14 | 0 15 | >>> a % b 16 | 3 17 | >>> 3 ** 4 18 | 81 19 | 20 | >>> type(3) 21 | 22 | >>> type(3.14) 23 | 24 | >>> type('a') 25 | 26 | >>> type("abc") 27 | 28 | >>> type(True) 29 | 30 | >>> type(None) 31 | 32 | >>> type(3 + 4j) 33 | 34 | 35 | >>> int(3.14) 36 | 3 37 | >>> int(-3) 38 | -3 39 | >>> float("3.14") 40 | 3.14 41 | >>> str(3.14) 42 | '3.14' 43 | >>> str(3 + 4j) 44 | '(3+4j)' 45 | >>> chr(65) 46 | 'A' 47 | >>> chr(97) 48 | 'a' 49 | >>> ord("a") 50 | 97 51 | >>> ord("A") 52 | 65 53 | >>> chr(ord('a') - 32) 54 | 'A' 55 | >>> chr(ord('A') + 32) 56 | 'a' 57 | """ 58 | 59 | 60 | if __name__ == "__main__": 61 | from doctest import testmod 62 | 63 | testmod() 64 | -------------------------------------------------------------------------------- /basics/while_example.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | """ 3 | While example. 4 | 5 | >>> i = 1 6 | >>> while i <= 5: 7 | ... print(i, end='') 8 | ... i += 1 9 | 12345 10 | 11 | >>> i = 5 12 | >>> while i >= 1: 13 | ... print(i, end='') 14 | ... i -= 1 15 | 54321 16 | """ 17 | 18 | 19 | if __name__ == "__main__": 20 | from doctest import testmod 21 | 22 | testmod() 23 | -------------------------------------------------------------------------------- /ciphers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/ciphers/__init__.py -------------------------------------------------------------------------------- /ciphers/caesar.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Caesar_cipher 3 | """ 4 | 5 | 6 | def encrypt(original: str, steps: int = 3) -> str: 7 | """ 8 | >>> encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 9 | 'DEFGHIJKLMNOPQRSTUVWXYZABC' 10 | >>> encrypt("abcdefghijklmnopqrstuvwxyz") 11 | 'defghijklmnopqrstuvwxyzabc' 12 | """ 13 | original = list(original) 14 | for i in range(0, len(original)): 15 | if original[i].isupper(): 16 | original[i] = chr(65 + (ord(original[i]) - 65 + steps) % 26) 17 | elif original[i].islower(): 18 | original[i] = chr(97 + (ord(original[i]) - 97 + steps) % 26) 19 | return "".join(original) 20 | 21 | 22 | def decrypt(password: str, steps: int = 3) -> str: 23 | """ 24 | >>> decrypt("DEFGHIJKLMNOPQRSTUVWXYZABC") 25 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 26 | >>> decrypt(("defghijklmnopqrstuvwxyzabc")) 27 | 'abcdefghijklmnopqrstuvwxyz' 28 | """ 29 | password = list(password) 30 | for i in range(0, len(password)): 31 | if password[i].isupper(): 32 | password[i] = chr(65 + (ord(password[i]) - 65 - steps + 26) % 26) 33 | elif password[i].islower(): 34 | password[i] = chr(97 + (ord(password[i]) - 97 - steps + 26) % 26) 35 | return "".join(password) 36 | 37 | 38 | if __name__ == "__main__": 39 | from doctest import testmod 40 | 41 | testmod() 42 | -------------------------------------------------------------------------------- /conversions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/conversions/__init__.py -------------------------------------------------------------------------------- /conversions/binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Binary_number 3 | https://en.wikipedia.org/wiki/Decimal 4 | """ 5 | 6 | 7 | def binary_to_decimal(binary: str) -> int: 8 | """ 9 | >>> binary_to_decimal("0") 10 | 0 11 | >>> binary_to_decimal("1") 12 | 1 13 | >>> binary_to_decimal("1010") 14 | 10 15 | >>> binary_to_decimal("-11101") 16 | -29 17 | """ 18 | is_negative = binary[0] == "-" 19 | binary = binary[1:] if is_negative else binary 20 | decimal = 0 21 | for i in range(0, len(binary)): 22 | decimal += int(binary[i]) * (2 ** (len(binary) - i - 1)) 23 | return -decimal if is_negative else decimal 24 | 25 | 26 | if __name__ == "__main__": 27 | from doctest import testmod 28 | 29 | testmod() 30 | -------------------------------------------------------------------------------- /conversions/temperature_conversion.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Fahrenheit 3 | https://en.wikipedia.org/wiki/Celsius 4 | """ 5 | 6 | 7 | def fahrenheit_to_celsius(temperature: float) -> float: 8 | """ 9 | >>> fahrenheit_to_celsius(32) 10 | 0.0 11 | >>> fahrenheit_to_celsius(39) 12 | 3.89 13 | """ 14 | return round(5 * (temperature - 32) / 9, 2) 15 | 16 | 17 | def celsius_to_fahrenheit(temperature: float) -> float: 18 | """ 19 | >>> celsius_to_fahrenheit(0) 20 | 32.0 21 | >>> celsius_to_fahrenheit(30.5) 22 | 86.9 23 | """ 24 | return round((temperature * 9 / 5) + 32, 2) 25 | 26 | 27 | if __name__ == "__main__": 28 | from doctest import testmod 29 | 30 | testmod() 31 | -------------------------------------------------------------------------------- /data_structures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/__init__.py -------------------------------------------------------------------------------- /data_structures/graph/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/graph/__init__.py -------------------------------------------------------------------------------- /data_structures/heap/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/heap/__init__.py -------------------------------------------------------------------------------- /data_structures/linked_list/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/linked_list/__init__.py -------------------------------------------------------------------------------- /data_structures/matrix/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/matrix/__init__.py -------------------------------------------------------------------------------- /data_structures/queue/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/queue/__init__.py -------------------------------------------------------------------------------- /data_structures/queue/queue.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Queue_(abstract_data_type) 3 | """ 4 | from typing import Any 5 | 6 | 7 | class Queue: 8 | def __init__(self) -> None: 9 | self.queue = [] 10 | 11 | def __len__(self) -> int: 12 | """ 13 | >>> queue = Queue() 14 | >>> len(queue) 15 | 0 16 | >>> for i in range(0, 5): 17 | ... assert len(queue) == i 18 | ... queue.enqueue(i) 19 | >>> len(queue) 20 | 5 21 | """ 22 | return len(self.queue) 23 | 24 | def __str__(self) -> str: 25 | """ 26 | >>> queue = Queue() 27 | >>> str(queue) 28 | '' 29 | >>> for i in range(1, 6): 30 | ... queue.enqueue(i) 31 | >>> str(queue) 32 | '1 <- 2 <- 3 <- 4 <- 5' 33 | """ 34 | return " <- ".join([str(item) for item in self.queue]) 35 | 36 | def size(self) -> int: 37 | """ 38 | >>> queue = Queue() 39 | >>> queue.size() 40 | 0 41 | >>> for i in range(0, 5): 42 | ... assert queue.size() == i 43 | ... queue.enqueue(i) 44 | >>> queue.size() 45 | 5 46 | """ 47 | return len(self) 48 | 49 | def is_empty(self) -> bool: 50 | """ 51 | >>> queue = Queue() 52 | >>> queue.is_empty() 53 | True 54 | >>> queue.enqueue('a') 55 | >>> queue.enqueue('b') 56 | >>> queue.is_empty() 57 | False 58 | """ 59 | return len(self) == 0 60 | 61 | def enqueue(self, item: Any) -> None: 62 | """ 63 | >>> queue = Queue() 64 | >>> str(queue) 65 | '' 66 | >>> for i in range(0, 5): 67 | ... queue.enqueue(i) 68 | >>> str(queue) 69 | '0 <- 1 <- 2 <- 3 <- 4' 70 | """ 71 | self.queue.append(item) 72 | 73 | def dequeue(self) -> Any: 74 | """ 75 | >>> queue = Queue() 76 | >>> for i in range(0, 5): 77 | ... queue.enqueue(i) 78 | >>> str(queue) 79 | '0 <- 1 <- 2 <- 3 <- 4' 80 | >>> queue.dequeue() 81 | 0 82 | >>> queue.dequeue() 83 | 1 84 | >>> str(queue) 85 | '2 <- 3 <- 4' 86 | >>> for i in range(2, 5): 87 | ... assert queue.dequeue() == i 88 | >>> str(queue) 89 | '' 90 | """ 91 | if self.is_empty(): 92 | raise IndexError("dequeue from empty queue") 93 | ret_item = self.queue[0] 94 | self.queue = self.queue[1:] 95 | return ret_item 96 | 97 | def peek(self) -> Any: 98 | """ 99 | >>> queue = Queue() 100 | >>> queue.enqueue("Python") 101 | >>> queue.enqueue("Java") 102 | >>> queue.enqueue("C") 103 | >>> queue.peek() 104 | 'Python' 105 | >>> queue.dequeue() 106 | 'Python' 107 | >>> queue.dequeue() 108 | 'Java' 109 | """ 110 | if self.is_empty(): 111 | raise IndexError("dequeue from empty queue") 112 | return self.queue[0] 113 | 114 | def clear(self) -> None: 115 | """ 116 | >>> queue = Queue() 117 | >>> for i in range(1, 6): 118 | ... queue.enqueue(i) 119 | >>> str(queue) 120 | '1 <- 2 <- 3 <- 4 <- 5' 121 | >>> queue.clear() 122 | >>> str(queue) 123 | '' 124 | """ 125 | self.queue = [] 126 | 127 | 128 | if __name__ == "__main__": 129 | from doctest import testmod 130 | 131 | testmod() 132 | -------------------------------------------------------------------------------- /data_structures/stack/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/stack/__init__.py -------------------------------------------------------------------------------- /data_structures/stack/stack.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | 4 | class Stack: 5 | def __init__(self, capacity: int = 10) -> None: 6 | self.stack = [] 7 | self.capacity = capacity 8 | 9 | def __len__(self): 10 | """ 11 | >>> stack = Stack() 12 | >>> for i in range(0, 10): 13 | ... stack.push(i) 14 | >>> len(stack) 15 | 10 16 | """ 17 | return len(self.stack) 18 | 19 | def size(self) -> int: 20 | """ 21 | >>> stack = Stack() 22 | >>> for i in range(0, 10): 23 | ... assert len(stack) == i 24 | ... stack.push(i) 25 | >>> stack.size() 26 | 10 27 | """ 28 | return len(self) 29 | 30 | def is_full(self) -> bool: 31 | """ 32 | >>> stack = Stack() 33 | >>> for i in range(0, 10): 34 | ... stack.push(i) 35 | >>> stack.is_full() 36 | True 37 | """ 38 | return len(self) == self.capacity 39 | 40 | def is_empty(self) -> bool: 41 | """ 42 | >>> stack = Stack() 43 | >>> stack.is_empty() 44 | True 45 | >>> stack.push(666) 46 | >>> stack.push(999) 47 | >>> stack.is_empty() 48 | False 49 | """ 50 | return len(self) == 0 51 | 52 | def push(self, item: Any) -> None: 53 | """ 54 | >>> stack = Stack() 55 | >>> for i in range(0, 10): 56 | ... stack.push(i) 57 | >>> stack.push(666) 58 | Traceback (most recent call last): 59 | ... 60 | ValueError: stack is full 61 | """ 62 | if self.is_full(): 63 | raise ValueError("stack is full") 64 | self.stack.append(item) 65 | 66 | def pop(self) -> Any: 67 | """ 68 | >>> stack = Stack() 69 | >>> stack.pop() 70 | Traceback (most recent call last): 71 | ... 72 | ValueError: stack is empty 73 | >>> for i in range(0, 10): 74 | ... stack.push(i) 75 | >>> for i in range(9, -1, -1): 76 | ... assert stack.pop() == i 77 | """ 78 | if self.is_empty(): 79 | raise ValueError("stack is empty") 80 | return self.stack.pop() 81 | 82 | def peek(self) -> Any: 83 | """ 84 | >>> stack = Stack() 85 | >>> stack.peek() 86 | Traceback (most recent call last): 87 | ... 88 | ValueError: stack is empty 89 | >>> stack.push('a') 90 | >>> stack.push('b') 91 | >>> stack.push('c') 92 | >>> stack.peek() 93 | 'c' 94 | """ 95 | if self.is_empty(): 96 | raise ValueError("stack is empty") 97 | return self.stack[-1] 98 | 99 | 100 | if __name__ == "__main__": 101 | from doctest import testmod 102 | 103 | testmod() 104 | -------------------------------------------------------------------------------- /data_structures/tree/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/data_structures/tree/__init__.py -------------------------------------------------------------------------------- /dynamicprogramming/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/dynamicprogramming/__init__.py -------------------------------------------------------------------------------- /dynamicprogramming/fibonacci_dp.py: -------------------------------------------------------------------------------- 1 | def fibonacci(nth: int) -> int: 2 | """ 3 | >>> fibonacci(0) 4 | 0 5 | >>> fibonacci(1) 6 | 1 7 | >>> fibonacci(2) 8 | 1 9 | >>> fibonacci(9) 10 | 34 11 | """ 12 | fibs = [0] * (nth + 2) 13 | fibs[0] = 0 14 | fibs[1] = 1 15 | 16 | for i in range(2, nth + 1): 17 | fibs[i] = fibs[i - 1] + fibs[i - 2] 18 | return fibs[nth] 19 | 20 | 21 | if __name__ == "__main__": 22 | from doctest import testmod 23 | 24 | testmod() 25 | -------------------------------------------------------------------------------- /maths/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/maths/__init__.py -------------------------------------------------------------------------------- /maths/absolute.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Absolute_value 3 | """ 4 | 5 | 6 | def absolute(number): 7 | """Return the absolute value of the argument. 8 | >>> absolute(-3.14) == abs(-3.14) and absolute(3.14) == abs(3.14) 9 | True 10 | >>> absolute(0) == abs(0) 11 | True 12 | >>> absolute(50) == abs(50) 13 | True 14 | >>> import random 15 | >>> all(absolute(number) == abs(number) for number in random.sample(range(-50, 50), 100)) 16 | True 17 | """ 18 | return -number if number < 0 else number 19 | 20 | 21 | if __name__ == "__main__": 22 | from doctest import testmod 23 | 24 | testmod() 25 | -------------------------------------------------------------------------------- /maths/absolute_max.py: -------------------------------------------------------------------------------- 1 | def absolute_max(array): 2 | """ 3 | Returns absolute max value of a array. 4 | :param array: the array. 5 | :return: absolute max value 6 | 7 | >>> absolute_max([1, -2, 5, -8, 7]) 8 | -8 9 | >>> absolute_max([1, -2, 3, -4, 5]) 10 | 5 11 | """ 12 | return max(array, key=abs) 13 | 14 | 15 | if __name__ == "__main__": 16 | from doctest import testmod 17 | 18 | testmod() 19 | -------------------------------------------------------------------------------- /maths/absolute_min.py: -------------------------------------------------------------------------------- 1 | def absolute_min(array): 2 | """ 3 | Returns absolute min value of a array. 4 | :param array: the array. 5 | :return: absolute min value 6 | 7 | >>> absolute_min([1, -2, 5, -8, 7]) 8 | 1 9 | >>> absolute_min([1, -2, 3, -4, 5]) 10 | 1 11 | """ 12 | return min(array, key=abs) 13 | 14 | 15 | if __name__ == "__main__": 16 | from doctest import testmod 17 | 18 | testmod() 19 | -------------------------------------------------------------------------------- /maths/addition.py: -------------------------------------------------------------------------------- 1 | def add(first_number, second_number): 2 | """ 3 | >>> add(1, 2) 4 | 3 5 | >>> add(1.1, 2.2) 6 | 3.3000000000000003 7 | >>> add(-1.1, 1.1) 8 | 0.0 9 | """ 10 | return first_number + second_number 11 | 12 | 13 | if __name__ == "if __name__ == ''": 14 | from doctest import testmod 15 | 16 | testmod() 17 | -------------------------------------------------------------------------------- /maths/aliquot_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Aliquot_sum 3 | """ 4 | 5 | 6 | def aliquot_sum(number: int) -> int: 7 | """ 8 | Calculate aliquot sum of a number. 9 | :param number: the number. 10 | :return: aliquot sum of given number. 11 | >>> aliquot_sum(1) 12 | 0 13 | >>> aliquot_sum(2) 14 | 1 15 | >>> aliquot_sum(3) 16 | 1 17 | >>> aliquot_sum(15) 18 | 9 19 | >>> aliquot_sum(21) 20 | 11 21 | >>> aliquot_sum(0) 22 | Traceback (most recent call last): 23 | ... 24 | ValueError: number must be positive 25 | >>> aliquot_sum(-10) 26 | Traceback (most recent call last): 27 | ... 28 | ValueError: number must be positive 29 | >>> aliquot_sum(10.50) 30 | Traceback (most recent call last): 31 | ... 32 | ValueError: number must be positive 33 | """ 34 | if number <= 0 or not isinstance(number, int): 35 | raise ValueError("number must be positive") 36 | return sum( 37 | divisor for divisor in range(1, number // 2 + 1) if number % divisor == 0 38 | ) 39 | 40 | 41 | if __name__ == "__main__": 42 | from doctest import testmod 43 | 44 | testmod() 45 | -------------------------------------------------------------------------------- /maths/area.py: -------------------------------------------------------------------------------- 1 | def circle_area(radius: float) -> float: 2 | """ 3 | >>> circle_area(10) 4 | 314.1592653589793 5 | >>> circle_area(0) 6 | 0.0 7 | """ 8 | import math 9 | 10 | return math.pi * radius * radius 11 | 12 | 13 | def rectangle_area(length: float, width: float) -> float: 14 | """ 15 | >>> rectangle_area(3, 4) 16 | 12 17 | >>> rectangle_area(3, 0) 18 | 0 19 | >>> rectangle_area(0, 4) 20 | 0 21 | """ 22 | return length * width 23 | 24 | 25 | def square_area(length: float) -> float: 26 | """ 27 | >>> square_area(4) 28 | 16 29 | >>> square_area(0) 30 | 0 31 | """ 32 | return length ** 2 33 | 34 | 35 | def triangle_area(length: float, height: float) -> float: 36 | """ 37 | >>> triangle_area(3, 4) 38 | 6.0 39 | >>> triangle_area(3, 0) 40 | 0.0 41 | >>> triangle_area(0, 4) 42 | 0.0 43 | """ 44 | return length * height / 2 45 | 46 | 47 | if __name__ == "__main__": 48 | from doctest import testmod 49 | 50 | testmod() 51 | -------------------------------------------------------------------------------- /maths/average.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Average 3 | """ 4 | 5 | 6 | def average(numbers): 7 | """ 8 | Calculate average of a list numbers. 9 | :param numbers: the number to be calculated. 10 | :return: average of a list number. 11 | 12 | >>> average([1, 2, 2, 3, 4, 7, 9]) 13 | 4.0 14 | >>> average(range(1, 11)) 15 | 5.5 16 | >>> average(range(1, 101)) 17 | 50.5 18 | """ 19 | return sum(numbers) / len(numbers) 20 | 21 | 22 | if __name__ == "__main__": 23 | from doctest import testmod 24 | 25 | testmod() 26 | -------------------------------------------------------------------------------- /maths/ceil.py: -------------------------------------------------------------------------------- 1 | def ceil(number) -> int: 2 | """ 3 | >>> import math 4 | >>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567] 5 | >>> all(math.ceil(num) == ceil(num) for num in numbers) 6 | True 7 | """ 8 | return int(number) if number - int(number) <= 0 else int(number) + 1 9 | 10 | 11 | if __name__ == "__main__": 12 | from doctest import testmod 13 | 14 | testmod() 15 | -------------------------------------------------------------------------------- /maths/count_digits.py: -------------------------------------------------------------------------------- 1 | def count_digits(number: int) -> int: 2 | """ 3 | >>> count_digits(-123) 4 | 3 5 | >>> count_digits(-1) 6 | 1 7 | >>> count_digits(0) 8 | 1 9 | >>> count_digits(123) 10 | 3 11 | >>> count_digits(123456) 12 | 6 13 | """ 14 | number = abs(number) 15 | count = 0 16 | while True: 17 | number = number // 10 18 | count = count + 1 19 | if number == 0: 20 | break 21 | return count 22 | 23 | 24 | if __name__ == "__main__": 25 | from doctest import testmod 26 | 27 | testmod() 28 | -------------------------------------------------------------------------------- /maths/count_digits_recursion.py: -------------------------------------------------------------------------------- 1 | def count_digits_recursion(number: int) -> int: 2 | """ 3 | >>> count_digits_recursion(-123) 4 | 3 5 | >>> count_digits_recursion(-1) 6 | 1 7 | >>> count_digits_recursion(0) 8 | 1 9 | >>> count_digits_recursion(123) 10 | 3 11 | >>> count_digits_recursion(123456) 12 | 6 13 | """ 14 | number = abs(number) 15 | return 1 if number < 10 else 1 + count_digits_recursion(number // 10) 16 | 17 | 18 | if __name__ == "__main__": 19 | from doctest import testmod 20 | 21 | testmod() 22 | -------------------------------------------------------------------------------- /maths/cube_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Cube_(algebra) 3 | """ 4 | 5 | 6 | def is_cube_number(number: int) -> bool: 7 | """ 8 | >>> all(is_cube_number(num) for num in [-8, -1, 0, 1, 8, 27, 64, 8000, 216_000]) 9 | True 10 | >>> is_cube_number(4) 11 | False 12 | >>> is_cube_number(11) 13 | False 14 | >>> is_cube_number(2**20) 15 | False 16 | """ 17 | number = abs(number) 18 | for i in range(0, number + 1): 19 | if i ** 3 == number: 20 | return True 21 | if i ** 3 > number: 22 | return False 23 | return False 24 | 25 | 26 | if __name__ == "__main__": 27 | from doctest import testmod 28 | 29 | testmod() 30 | -------------------------------------------------------------------------------- /maths/even_check.py: -------------------------------------------------------------------------------- 1 | def is_even(number: int) -> bool: 2 | """ 3 | Test if a number is a even number. 4 | :param number: the number to be checked. 5 | :return: True if the number is even, otherwise False. 6 | 7 | >>> is_even(-1) 8 | False 9 | >>> is_even(-2) 10 | True 11 | >>> is_even(0) 12 | True 13 | >>> is_even(3) 14 | False 15 | >>> is_even(4) 16 | True 17 | >>> all([is_even(i) for i in range(0, 100, 2)]) 18 | True 19 | """ 20 | return number % 2 == 0 21 | 22 | 23 | def is_even_faster(number: int) -> bool: 24 | """ 25 | Test if a number is a even number using bit operator. 26 | :param number: the number to be checked. 27 | :return: True if the number is even, otherwise False. 28 | 29 | >>> is_even_faster(-1) 30 | False 31 | >>> is_even_faster(-2) 32 | True 33 | >>> is_even_faster(0) 34 | True 35 | >>> is_even_faster(3) 36 | False 37 | >>> is_even_faster(4) 38 | True 39 | >>> all([is_even_faster(i) for i in range(0, 100, 2)]) 40 | True 41 | """ 42 | return number & 1 == 0 43 | 44 | 45 | if __name__ == "__main__": 46 | from doctest import testmod 47 | 48 | testmod() 49 | -------------------------------------------------------------------------------- /maths/factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(number: int) -> int: 2 | """ 3 | >>> factorial(5) 4 | 120 5 | >>> factorial(0) 6 | 1 7 | >>> import random 8 | >>> import math 9 | >>> numbers = list(range(0, 50)) 10 | >>> for num in numbers: 11 | ... assert factorial(num) == math.factorial(num) 12 | >>> factorial(-1) 13 | Traceback (most recent call last): 14 | ... 15 | ValueError: factorial() not defined for negative values 16 | """ 17 | if number < 0: 18 | raise ValueError("factorial() not defined for negative values") 19 | fact = 1 20 | for i in range(1, number + 1): 21 | fact *= i 22 | return fact 23 | 24 | 25 | if __name__ == "__main__": 26 | from doctest import testmod 27 | 28 | testmod() 29 | -------------------------------------------------------------------------------- /maths/factorial_recursion.py: -------------------------------------------------------------------------------- 1 | def factorial_recursion(number: int) -> int: 2 | """ 3 | >>> factorial_recursion(5) 4 | 120 5 | >>> factorial_recursion(0) 6 | 1 7 | >>> import random 8 | >>> import math 9 | >>> numbers = list(range(0, 50)) 10 | >>> for num in numbers: 11 | ... assert factorial_recursion(num) == math.factorial(num) 12 | >>> factorial_recursion(-1) 13 | Traceback (most recent call last): 14 | ... 15 | ValueError: factorial() not defined for negative values 16 | """ 17 | if number < 0: 18 | raise ValueError("factorial() not defined for negative values") 19 | return 1 if number == 0 or number == 1 else number * factorial_recursion(number - 1) 20 | 21 | 22 | if __name__ == "__main__": 23 | from doctest import testmod 24 | 25 | testmod() 26 | -------------------------------------------------------------------------------- /maths/fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci(number: int) -> int: 2 | """ 3 | >>> fibonacci(0) 4 | 0 5 | >>> fibonacci(1) 6 | 1 7 | >>> fibonacci(2) 8 | 1 9 | >>> fibonacci(3) 10 | 2 11 | >>> fibonacci(4) 12 | 3 13 | >>> fibonacci(5) 14 | 5 15 | >>> fibonacci(6) 16 | 8 17 | >>> fibonacci(7) 18 | 13 19 | >>> fibonacci(8) 20 | 21 21 | """ 22 | first_item = 0 23 | second_item = 1 24 | for i in range(0, number): 25 | temp = first_item + second_item 26 | first_item = second_item 27 | second_item = temp 28 | return first_item 29 | 30 | 31 | if __name__ == "__main__": 32 | from doctest import testmod 33 | 34 | testmod() 35 | -------------------------------------------------------------------------------- /maths/fibonacci_recursion.py: -------------------------------------------------------------------------------- 1 | def fibonacci(number: int) -> int: 2 | """ 3 | >>> fibonacci(0) 4 | 0 5 | >>> fibonacci(1) 6 | 1 7 | >>> fibonacci(2) 8 | 1 9 | >>> fibonacci(3) 10 | 2 11 | >>> fibonacci(4) 12 | 3 13 | >>> fibonacci(5) 14 | 5 15 | >>> fibonacci(6) 16 | 8 17 | >>> fibonacci(7) 18 | 13 19 | >>> fibonacci(8) 20 | 21 21 | """ 22 | return ( 23 | number 24 | if number == 0 or number == 1 25 | else fibonacci(number - 1) + fibonacci(number - 2) 26 | ) 27 | 28 | 29 | if __name__ == "__main__": 30 | from doctest import testmod 31 | 32 | testmod() 33 | -------------------------------------------------------------------------------- /maths/fibonacci_with_list.py: -------------------------------------------------------------------------------- 1 | def fibonacci(number: int) -> int: 2 | """ 3 | >>> fibonacci(0) 4 | 0 5 | >>> fibonacci(1) 6 | 1 7 | >>> fibonacci(2) 8 | 1 9 | >>> fibonacci(3) 10 | 2 11 | >>> fibonacci(4) 12 | 3 13 | >>> fibonacci(5) 14 | 5 15 | >>> fibonacci(6) 16 | 8 17 | >>> fibonacci(7) 18 | 13 19 | >>> fibonacci(8) 20 | 21 21 | """ 22 | fibs = [0] * (number + 2) 23 | fibs[0] = 0 24 | fibs[1] = 1 25 | for i in range(2, number + 1): 26 | fibs[i] = fibs[i - 1] + fibs[i - 2] 27 | return fibs[number] 28 | 29 | 30 | if __name__ == "__main__": 31 | from doctest import testmod 32 | 33 | testmod() 34 | -------------------------------------------------------------------------------- /maths/first_digit.py: -------------------------------------------------------------------------------- 1 | def first_digit(number: int) -> int: 2 | """ 3 | >>> first_digit(-123) 4 | 1 5 | >>> first_digit(0) 6 | 0 7 | >>> first_digit(123) 8 | 1 9 | >>> first_digit(123456789) 10 | 1 11 | """ 12 | number = abs(number) 13 | while number >= 10: 14 | number //= 10 15 | return number 16 | 17 | 18 | if __name__ == "__main__": 19 | from doctest import testmod 20 | 21 | testmod() 22 | -------------------------------------------------------------------------------- /maths/first_digit_by_str.py: -------------------------------------------------------------------------------- 1 | def first_digit(number: int) -> int: 2 | """ 3 | >>> first_digit(-123) 4 | 1 5 | >>> first_digit(0) 6 | 0 7 | >>> first_digit(123) 8 | 1 9 | >>> first_digit(123456789) 10 | 1 11 | """ 12 | return int(str(abs(number))[0]) 13 | 14 | 15 | if __name__ == "__main__": 16 | from doctest import testmod 17 | 18 | testmod() 19 | -------------------------------------------------------------------------------- /maths/first_digit_recursion.py: -------------------------------------------------------------------------------- 1 | def first_digit_recursion(number: int) -> int: 2 | """ 3 | >>> first_digit_recursion(-123) 4 | 1 5 | >>> first_digit_recursion(0) 6 | 0 7 | >>> first_digit_recursion(123) 8 | 1 9 | >>> first_digit_recursion(123456789) 10 | 1 11 | """ 12 | number = abs(number) 13 | return number if number < 10 else first_digit_recursion(number // 10) 14 | 15 | 16 | if __name__ == "__main__": 17 | from doctest import testmod 18 | 19 | testmod() 20 | -------------------------------------------------------------------------------- /maths/floor.py: -------------------------------------------------------------------------------- 1 | def floor(number) -> int: 2 | """ 3 | >>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567] 4 | >>> import math 5 | >>> all(math.floor(num) == floor(num) for num in numbers) 6 | True 7 | """ 8 | return int(number) if number - int(number) >= 0 else int(number) - 1 9 | 10 | 11 | if __name__ == "__main__": 12 | from doctest import testmod 13 | 14 | testmod() 15 | -------------------------------------------------------------------------------- /maths/leap_year.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Leap_year 3 | """ 4 | 5 | 6 | def is_leap_year(year: int) -> bool: 7 | """ 8 | >>> all(is_leap_year(year) for year in [1600, 2000, 24000]) 9 | True 10 | >>> all(is_leap_year(year) for year in [1999, 2001, 2002]) 11 | False 12 | """ 13 | return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 14 | 15 | 16 | if __name__ == "__main__": 17 | from doctest import testmod 18 | 19 | testmod() 20 | -------------------------------------------------------------------------------- /maths/median.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Median 3 | """ 4 | 5 | 6 | def median(numbers): 7 | """ 8 | Calculate median of a list numbers. 9 | :param numbers: the numbers to be calculated. 10 | :return: median value of numbers. 11 | 12 | >>> median([1, 3, 3, 6, 7, 8, 9]) 13 | 6 14 | >>> median([1, 2, 3, 4, 5, 6, 8, 9]) 15 | 4.5 16 | >>> import statistics 17 | >>> import random 18 | >>> numbers = random.sample(range(-50, 50), k=100) 19 | >>> statistics.median(numbers) == median(numbers) 20 | True 21 | """ 22 | numbers = sorted(numbers) 23 | mid_index = len(numbers) // 2 24 | return ( 25 | (numbers[mid_index] + numbers[mid_index - 1]) / 2 26 | if mid_index % 2 == 0 27 | else numbers[mid_index] 28 | ) 29 | 30 | 31 | if __name__ == "__main__": 32 | from doctest import testmod 33 | 34 | testmod() 35 | -------------------------------------------------------------------------------- /maths/mode.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Mode_(statistics) 3 | """ 4 | 5 | 6 | def mode(numbers): 7 | """ 8 | Calculate mode of a list numbers. 9 | :param numbers: the numbers 10 | :return: mode number of the numbers. 11 | 12 | >>> mode([1, 2, 2, 3, 4, 7, 9]) 13 | 2 14 | """ 15 | max_count = 1 16 | mode_number = numbers[0] 17 | 18 | for number in numbers: 19 | count = 0 20 | for temp in numbers: 21 | if temp == number: 22 | count += 1 23 | if count > max_count: 24 | max_count = count 25 | mode_number = number 26 | 27 | return mode_number 28 | 29 | 30 | if __name__ == "__main__": 31 | from doctest import testmod 32 | 33 | testmod() 34 | -------------------------------------------------------------------------------- /maths/odd_check.py: -------------------------------------------------------------------------------- 1 | def is_odd(number: int) -> bool: 2 | """ 3 | Test if a number is a odd number. 4 | :param number: the number to be checked. 5 | :return: True if the number is odd, otherwise False. 6 | 7 | >>> is_odd(-1) 8 | True 9 | >>> is_odd(-2) 10 | False 11 | >>> is_odd(0) 12 | False 13 | >>> is_odd(3) 14 | True 15 | >>> is_odd(4) 16 | False 17 | >>> all([is_odd(i) for i in range(1, 100, 2)]) 18 | True 19 | """ 20 | return number % 2 != 0 21 | 22 | 23 | def is_odd_faster(number: int) -> bool: 24 | """ 25 | Test if a number is a odd number using bit operator. 26 | :param number: the number to be checked. 27 | :return: True if the number is odd, otherwise False. 28 | 29 | >>> is_odd_faster(-1) 30 | True 31 | >>> is_odd_faster(-2) 32 | False 33 | >>> is_odd_faster(0) 34 | False 35 | >>> is_odd_faster(3) 36 | True 37 | >>> is_odd_faster(4) 38 | False 39 | >>> all([is_odd_faster(i) for i in range(1, 100, 2)]) 40 | True 41 | """ 42 | return number & 1 != 0 43 | 44 | 45 | if __name__ == "__main__": 46 | from doctest import testmod 47 | 48 | testmod() 49 | -------------------------------------------------------------------------------- /maths/subtract.py: -------------------------------------------------------------------------------- 1 | def subtract(first_number, second_number): 2 | """ 3 | >>> subtract(1.1, 1.1) 4 | 0.0 5 | >>> subtract(10, 5) 6 | 5 7 | >>> subtract(3.14159, 3) 8 | 0.14158999999999988 9 | """ 10 | return first_number - second_number 11 | 12 | 13 | if __name__ == "__main__": 14 | from doctest import testmod 15 | 16 | testmod() 17 | -------------------------------------------------------------------------------- /maths/sum_big_numbers.py: -------------------------------------------------------------------------------- 1 | def sum_big_numbers(first_number: int, second_number: int): 2 | """ 3 | >>> sum_big_numbers(1234567891011121314151617181920, 2019181716151413121110987654321) 4 | 3253749607162534435262604836241 5 | """ 6 | return first_number + second_number 7 | 8 | 9 | if __name__ == "__main__": 10 | from doctest import testmod 11 | 12 | testmod() 13 | -------------------------------------------------------------------------------- /maths/sum_of_factorial.py: -------------------------------------------------------------------------------- 1 | def sum_of_factorial(number: int) -> int: 2 | """ 3 | >>> sum_of_factorial(0) 4 | 0 5 | >>> sum_of_factorial(1) 6 | 1 7 | >>> sum_of_factorial(2) 8 | 3 9 | >>> sum_of_factorial(5) 10 | 153 11 | """ 12 | sum_factorial = 0 13 | factorial = 1 14 | for i in range(1, number + 1): 15 | factorial *= i 16 | sum_factorial = sum_factorial + factorial 17 | 18 | return sum_factorial 19 | 20 | 21 | def sum_of_factorial_circle_plus_recursion(number: int) -> int: 22 | """ 23 | >>> sum_of_factorial_circle_plus_recursion(0) 24 | 0 25 | >>> sum_of_factorial_circle_plus_recursion(1) 26 | 1 27 | >>> sum_of_factorial_circle_plus_recursion(2) 28 | 3 29 | >>> sum_of_factorial_circle_plus_recursion(5) 30 | 153 31 | """ 32 | sum_factorial = 0 33 | from math import factorial 34 | 35 | for i in range(1, number + 1): 36 | sum_factorial += factorial(i) 37 | return sum_factorial 38 | 39 | 40 | def sum_of_factorial_pure_recursion(number: int) -> int: 41 | """ 42 | >>> sum_of_factorial_pure_recursion(0) 43 | 0 44 | >>> sum_of_factorial_pure_recursion(1) 45 | 1 46 | >>> sum_of_factorial_pure_recursion(2) 47 | 3 48 | >>> sum_of_factorial_pure_recursion(5) 49 | 153 50 | """ 51 | if number == 1 or number == 0: 52 | return number # 1! or 0! 53 | elif number == 2: 54 | return 3 # 1! + 2! 55 | else: 56 | return ( 57 | sum_of_factorial_pure_recursion(number - 1) 58 | + ( 59 | sum_of_factorial_pure_recursion(number - 1) 60 | - sum_of_factorial_pure_recursion(number - 2) 61 | ) 62 | * number 63 | ) 64 | 65 | 66 | if __name__ == "__main__": 67 | from doctest import testmod 68 | 69 | testmod() 70 | -------------------------------------------------------------------------------- /maths/sum_to_n.py: -------------------------------------------------------------------------------- 1 | def sum_to_n(n: int) -> int: 2 | """ 3 | >>> sum_to_n(100) 4 | 5050 5 | >>> sum_to_n(10) 6 | 55 7 | """ 8 | return sum(i for i in range(1, n + 1)) 9 | 10 | 11 | if __name__ == "__main__": 12 | from doctest import testmod 13 | 14 | testmod() 15 | -------------------------------------------------------------------------------- /maths/sum_to_n_formula.py: -------------------------------------------------------------------------------- 1 | def sum_to_n(n: int) -> int: 2 | """ 3 | >>> sum_to_n(0) 4 | 0 5 | >>> sum_to_n(1) 6 | 1 7 | >>> sum_to_n(2) 8 | 3 9 | >>> sum_to_n(10) 10 | 55 11 | >>> sum_to_n(100) 12 | 5050 13 | """ 14 | return (1 + n) * n // 2 15 | 16 | 17 | if __name__ == "__main__": 18 | from doctest import testmod 19 | 20 | testmod() 21 | -------------------------------------------------------------------------------- /maths/sum_to_n_recursion.py: -------------------------------------------------------------------------------- 1 | def sum_to_n_recursion(number: int) -> int: 2 | """ 3 | >>> sum_to_n_recursion(0) 4 | 0 5 | >>> sum_to_n_recursion(10) 6 | 55 7 | >>> sum_to_n_recursion(100) 8 | 5050 9 | """ 10 | return 0 if number == 0 else number + sum_to_n_recursion(number - 1) 11 | 12 | 13 | if __name__ == "__main__": 14 | from doctest import testmod 15 | 16 | testmod() 17 | -------------------------------------------------------------------------------- /maths/to_integer.py: -------------------------------------------------------------------------------- 1 | def to_integer(number_str: str) -> int: 2 | """ 3 | >>> to_integer("123") 4 | 123 5 | >>> to_integer("3.14") 6 | 3 7 | >>> to_integer("-123") 8 | -123 9 | >>> to_integer("-3.14") 10 | -3 11 | >>> to_integer("123a") 12 | Traceback (most recent call last): 13 | ... 14 | ValueError: could not convert string to float: '123a' 15 | """ 16 | return int(float(number_str)) 17 | 18 | 19 | if __name__ == "__main__": 20 | from doctest import testmod 21 | 22 | testmod() 23 | -------------------------------------------------------------------------------- /maths/tower_of_hanio.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Tower_of_Hanoi 3 | """ 4 | 5 | 6 | def move(number_of_tower: int, a_place: str, b_place: str, c_place: str) -> None: 7 | """ 8 | >>> move(0, "A", "B", "C") 9 | >>> move(1, "A", "B", "C") 10 | move from A to B 11 | >>> move(2, "A", "B", "C") 12 | move from A to C 13 | move from A to B 14 | move from C to B 15 | >>> move(3, "A", "B", "C") 16 | move from A to B 17 | move from A to C 18 | move from B to C 19 | move from A to B 20 | move from C to A 21 | move from C to B 22 | move from A to B 23 | >>> move(4, "A", "B", "C") 24 | move from A to C 25 | move from A to B 26 | move from C to B 27 | move from A to C 28 | move from B to A 29 | move from B to C 30 | move from A to C 31 | move from A to B 32 | move from C to B 33 | move from C to A 34 | move from B to A 35 | move from C to B 36 | move from A to C 37 | move from A to B 38 | move from C to B 39 | """ 40 | if number_of_tower != 0: 41 | move(number_of_tower - 1, a_place, c_place, b_place) 42 | print(f"move from {a_place} to {b_place}") 43 | move(number_of_tower - 1, c_place, b_place, a_place) 44 | 45 | 46 | if __name__ == "__main__": 47 | from doctest import testmod 48 | 49 | testmod() 50 | -------------------------------------------------------------------------------- /searches/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/searches/__init__.py -------------------------------------------------------------------------------- /searches/binary_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Binary_search_algorithm 3 | """ 4 | 5 | 6 | def binary_search_recursion(array, key, left: int = 0, right: int = None) -> int: 7 | """ 8 | Binary search algorithm using recursion. 9 | :param array: the sorted array to be searched. 10 | :param key: the key value to be searched. 11 | :param left: the left index of sub array. 12 | :param right: the right index of sub array. 13 | :return: index of key value if found, otherwise -1. 14 | 15 | >>> array = list(range(10)) 16 | >>> for index, item in enumerate(array): 17 | ... assert index == binary_search_recursion(array, item) 18 | >>> binary_search_recursion(array, 10) == -1 19 | True 20 | >>> binary_search_recursion(array, -1) == -1 21 | True 22 | """ 23 | if right is None: 24 | right = len(array) - 1 25 | if left > right: 26 | return -1 27 | mid = (left + right) >> 1 28 | if key == array[mid]: 29 | return mid 30 | elif key > array[mid]: 31 | return binary_search_recursion(array, key, mid + 1, right) 32 | else: 33 | return binary_search_recursion(array, key, left, mid - 1) 34 | 35 | 36 | if __name__ == "__main__": 37 | from doctest import testmod 38 | 39 | testmod() 40 | -------------------------------------------------------------------------------- /searches/binary_search_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Binary_search_algorithm 3 | """ 4 | 5 | 6 | def binary_search(array, key) -> int: 7 | """ 8 | Binary search algorithm. 9 | :param array: the sorted array to be searched. 10 | :param key: the key value to be searched. 11 | :return: index of key value if found, otherwise -1. 12 | 13 | >>> array = list(range(10)) 14 | >>> for index, item in enumerate(array): 15 | ... assert index == binary_search(array, item) 16 | >>> binary_search(array, 10) == -1 17 | True 18 | >>> binary_search(array, -1) == -1 19 | True 20 | """ 21 | left = 0 22 | right = len(array) - 1 23 | while left <= right: 24 | mid = (left + right) >> 1 25 | if key == array[mid]: 26 | return mid 27 | elif key > array[mid]: 28 | left = mid + 1 29 | else: 30 | right = mid - 1 31 | return -1 32 | 33 | 34 | if __name__ == "__main__": 35 | from doctest import testmod 36 | 37 | testmod() 38 | -------------------------------------------------------------------------------- /searches/linear_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Linear_search 3 | """ 4 | 5 | 6 | def linear_search(array, key) -> int: 7 | """ 8 | Linear search algorithm. 9 | :param array: the array to be searched. 10 | :param key: the key value to be searched. 11 | :return: index of key value if found, otherwise -1. 12 | 13 | >>> array = list(range(0, 10)) 14 | >>> for index, key in enumerate(range(0, 10)): 15 | ... assert index == linear_search(array, key) 16 | >>> linear_search(array, 10) == -1 17 | True 18 | >>> linear_search(array, -1) == -1 19 | True 20 | """ 21 | for index, value in enumerate(array): 22 | if value == key: 23 | return index 24 | return -1 25 | 26 | 27 | if __name__ == "__main__": 28 | from doctest import testmod 29 | 30 | testmod() 31 | -------------------------------------------------------------------------------- /searches/linear_search_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Linear_search 3 | """ 4 | 5 | 6 | def linear_search_recursion( 7 | array, 8 | key, 9 | length: int = None, 10 | ) -> int: 11 | """ 12 | Linear search algorithm using recursion. 13 | :param array: the array to be searched. 14 | :param length: the length of sub array. 15 | :param key: the key value to be searched. 16 | :return: index of key value if found, otherwise -1. 17 | 18 | >>> array = list(range(0, 10)) 19 | >>> for index, key in enumerate(range(0, 10)): 20 | ... assert index == linear_search_recursion(array, key) 21 | >>> linear_search_recursion(array, 10) == -1 22 | True 23 | >>> linear_search_recursion(array, -1) == -1 24 | True 25 | """ 26 | if length is None: 27 | length = len(array) 28 | if length == 0: 29 | return -1 30 | elif array[length - 1] == key: 31 | return length - 1 32 | else: 33 | return linear_search_recursion(array, key, length - 1) 34 | 35 | 36 | if __name__ == "__main__": 37 | from doctest import testmod 38 | 39 | testmod() 40 | -------------------------------------------------------------------------------- /sorts/bubble_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Bubble_sort 3 | """ 4 | 5 | 6 | def bubble_sort(array): 7 | """ 8 | :param array: the array to be sorted. 9 | :return: sorted array. 10 | >>> import random 11 | >>> array = random.sample(range(-50, 50), 100) 12 | >>> bubble_sort(array) == sorted(array) 13 | True 14 | >>> import string 15 | >>> array = random.choices(string.ascii_letters + string.digits, k = 100) 16 | >>> bubble_sort(array) == sorted(array) 17 | True 18 | >>> array = [random.uniform(-50.0, 50.0) for i in range(100)] 19 | >>> bubble_sort(array) == sorted(array) 20 | True 21 | """ 22 | length = len(array) 23 | for i in range(0, length - 1): 24 | swapped = False 25 | for j in range(0, length - 1 - i): 26 | if array[j] > array[j + 1]: 27 | array[j], array[j + 1] = array[j + 1], array[j] 28 | swapped = True 29 | if not swapped: 30 | break 31 | return array 32 | 33 | 34 | if __name__ == "__main__": 35 | from doctest import testmod 36 | 37 | testmod() 38 | -------------------------------------------------------------------------------- /sorts/bubble_sort_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Bubble_sort 3 | """ 4 | 5 | 6 | def bubble_sort(array, length: int = 0): 7 | """ 8 | :param array: the array to be sorted. 9 | :param length: the length of array. 10 | :return: sorted array. 11 | >>> import random 12 | >>> array = random.sample(range(-50, 50), 100) 13 | >>> bubble_sort(array) == sorted(array) 14 | True 15 | >>> import string 16 | >>> array = random.choices(string.ascii_letters + string.digits, k = 100) 17 | >>> bubble_sort(array) == sorted(array) 18 | True 19 | >>> array = [random.uniform(-50.0, 50.0) for i in range(100)] 20 | >>> bubble_sort(array) == sorted(array) 21 | True 22 | """ 23 | length = length or len(array) 24 | swapped = False 25 | for i in range(length - 1): 26 | if array[i] > array[i + 1]: 27 | array[i], array[i + 1] = ( 28 | array[i + 1], 29 | array[i], 30 | ) 31 | swapped = True 32 | return array if not swapped else bubble_sort(array, length - 1) 33 | 34 | 35 | if __name__ == "__main__": 36 | from doctest import testmod 37 | 38 | testmod() 39 | -------------------------------------------------------------------------------- /sorts/insertion_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Insertion_sort 3 | """ 4 | 5 | 6 | def insertion_sort(array): 7 | """ 8 | Bubble sort algorithm. 9 | :param array: the array to be sorted. 10 | :return: sorted array. 11 | >>> import random 12 | >>> array = random.sample(range(-50, 50), 100) 13 | >>> insertion_sort(array) == sorted(array) 14 | True 15 | >>> import string 16 | >>> array = random.choices(string.ascii_letters + string.digits, k = 100) 17 | >>> insertion_sort(array) == sorted(array) 18 | True 19 | >>> array = [random.uniform(-50.0, 50.0) for i in range(100)] 20 | >>> insertion_sort(array) == sorted(array) 21 | True 22 | """ 23 | for i in range(1, len(array)): 24 | j = i - 1 25 | key = array[i] 26 | while j >= 0 and key < array[j]: 27 | array[j + 1] = array[j] 28 | j -= 1 29 | if j != i - 1: 30 | array[j + 1] = key 31 | return array 32 | 33 | 34 | if __name__ == "__main__": 35 | from doctest import testmod 36 | 37 | testmod() 38 | -------------------------------------------------------------------------------- /sorts/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Merge_sort 3 | """ 4 | 5 | 6 | def merge_sort(array, left: int = 0, right: int = None): 7 | """ 8 | Merge sort algorithm. 9 | :param array: the array to be sorted. 10 | :param left: the left index of sub array. 11 | :param right: the right index of sub array. 12 | :return: sorted array. 13 | 14 | >>> import random 15 | >>> array = random.sample(range(-50, 50), 10) 16 | >>> merge_sort(array) == sorted(array) 17 | True 18 | >>> import string 19 | >>> array = random.choices(string.ascii_letters + string.digits, k = 10) 20 | >>> merge_sort(array) == sorted(array) 21 | True 22 | >>> array = [random.uniform(-50.0, 50.0) for i in range(10)] 23 | >>> merge_sort(array) == sorted(array) 24 | True 25 | """ 26 | if right is None: 27 | right = len(array) - 1 28 | if left < right: 29 | middle = (left + right) >> 1 30 | merge_sort(array, left, middle) 31 | merge_sort(array, middle + 1, right) 32 | 33 | # merge two sub sorted array 34 | i = left 35 | j = middle + 1 36 | k = left 37 | while i <= middle and j <= right: 38 | if array[i] <= array[j]: 39 | array[k] = array[i] 40 | i += 1 41 | else: 42 | array[k] = array[j] 43 | j += 1 44 | k += 1 45 | 46 | while i <= middle: 47 | array[k] = array[i] 48 | i += 1 49 | k += 1 50 | 51 | while j <= right: 52 | array[k] = array[j] 53 | j += 1 54 | k += 1 55 | return array 56 | 57 | 58 | if __name__ == "__main__": 59 | from doctest import testmod 60 | 61 | testmod() 62 | -------------------------------------------------------------------------------- /sorts/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Quicksort 3 | """ 4 | 5 | 6 | def quick_sort(array, left: int = 0, right: int = None): 7 | """ 8 | Quick sort algorithm. 9 | :param array: the array to be sorted. 10 | :param left: the left index of sub array. 11 | :param right: the right index of sub array. 12 | :return: sorted array 13 | 14 | >>> import random 15 | >>> array = random.sample(range(-50, 50), 10) 16 | >>> quick_sort(array) == sorted(array) 17 | True 18 | >>> import string 19 | >>> array = random.choices(string.ascii_letters + string.digits, k = 10) 20 | >>> quick_sort(array) == sorted(array) 21 | True 22 | >>> array = [random.uniform(-50.0, 50.0) for i in range(10)] 23 | >>> quick_sort(array) == sorted(array) 24 | True 25 | """ 26 | if right is None: 27 | right = len(array) - 1 28 | if left >= right: 29 | return 30 | pivot = array[right] # pick last element as pivot 31 | i = left 32 | j = right - 1 33 | while i <= j: 34 | while array[i] < pivot: 35 | i += 1 36 | while j >= 0 and array[j] >= pivot: 37 | j -= 1 38 | if i < j: 39 | array[i], array[j] = array[j], array[i] 40 | i += 1 41 | j -= 1 42 | array[i], array[right] = array[right], array[i] 43 | quick_sort(array, left, i - 1) 44 | quick_sort(array, i + 1, right) 45 | return array 46 | 47 | 48 | if __name__ == "__main__": 49 | from doctest import testmod 50 | 51 | testmod() 52 | -------------------------------------------------------------------------------- /sorts/selection_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Selection_sort 3 | """ 4 | 5 | 6 | def selection_sort(array): 7 | """ 8 | Selection sort algorithm. 9 | :param array: the array to be sorted. 10 | :return: sorted array 11 | >>> import random 12 | >>> array = random.sample(range(-50, 50), 100) 13 | >>> selection_sort(array) == sorted(array) 14 | True 15 | """ 16 | for i in range(0, len(array) - 1): 17 | min_index = i 18 | for j in range(i + 1, len(array)): 19 | if array[j] < array[min_index]: 20 | min_index = j 21 | if min_index != i: 22 | array[i], array[min_index] = array[min_index], array[i] 23 | return array 24 | 25 | 26 | if __name__ == "__main__": 27 | from doctest import testmod 28 | 29 | testmod() 30 | -------------------------------------------------------------------------------- /sorts/shell_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Shellsort 3 | """ 4 | 5 | 6 | def shell_sort(array): 7 | """ 8 | Shell Sort algorithm 9 | :param array: the array to be sorted. 10 | :return: sorted array. 11 | >>> import random 12 | >>> array = random.sample(range(-50, 50), 100) 13 | >>> shell_sort(array) == sorted(array) 14 | True 15 | >>> import string 16 | >>> array = random.choices(string.ascii_letters + string.digits, k = 100) 17 | >>> shell_sort(array) == sorted(array) 18 | True 19 | >>> array = [random.uniform(-50.0, 50.0) for i in range(100)] 20 | >>> shell_sort(array) == sorted(array) 21 | True 22 | """ 23 | gap = len(array) >> 1 24 | while gap > 0: 25 | for i in range(gap, len(array)): 26 | insert_value = array[i] 27 | j = i - gap 28 | while j >= 0 and insert_value < array[j]: 29 | array[j + gap] = array[j] 30 | j -= gap 31 | if j != i - gap: 32 | array[j + gap] = insert_value 33 | gap >>= 1 34 | return array 35 | 36 | 37 | if __name__ == "__main__": 38 | from doctest import testmod 39 | 40 | testmod() 41 | -------------------------------------------------------------------------------- /strings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/examplehub/Python/cd9dd9feb6dd65c2e0d545b5154a0f684e5c1e17/strings/__init__.py -------------------------------------------------------------------------------- /strings/contains.py: -------------------------------------------------------------------------------- 1 | def contains(main_str: str, sub_str: str) -> bool: 2 | """ 3 | >>> "a" in "abc" 4 | True 5 | >>> "bc" in "abc" 6 | True 7 | >>> "ac" in "abc" 8 | False 9 | >>> "" in "abc" 10 | True 11 | >>> "" in "" 12 | True 13 | """ 14 | return sub_str in main_str 15 | 16 | 17 | if __name__ == "__main__": 18 | from doctest import testmod 19 | 20 | testmod() 21 | -------------------------------------------------------------------------------- /strings/palindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Palindrome 3 | """ 4 | 5 | 6 | def is_palindrome(s: str) -> bool: 7 | """ 8 | Test if a string is palindrome string. 9 | :param s: the string to be check. 10 | :return: True if the string is palindrome, otherwise False. 11 | >>> is_palindrome("Able was I ere I saw Elba") 12 | True 13 | >>> is_palindrome("A man, a plan, a canal – Panama") 14 | True 15 | >>> is_palindrome("Madam, I'm Adam") 16 | True 17 | >>> is_palindrome("Never odd or even") 18 | True 19 | >>> is_palindrome("") 20 | True 21 | >>> is_palindrome(" ") 22 | True 23 | """ 24 | s = "".join(char for char in s.lower() if s.isalnum()) 25 | i, j = 0, len(s) - 1 26 | while i < j: 27 | if s[i] == s[j]: 28 | i += 1 29 | j -= 1 30 | else: 31 | return False 32 | return True 33 | 34 | 35 | def is_palindrome_reverse(s: str) -> bool: 36 | """ 37 | Test if a string is palindrome string by reversing string. 38 | :param s: the string to be checked 39 | :return: True if the string is palindrome, otherwise False. 40 | >>> is_palindrome_reverse("Able was I ere I saw Elba") 41 | True 42 | >>> is_palindrome_reverse("A man, a plan, a canal – Panama") 43 | True 44 | >>> is_palindrome_reverse("Madam, I'm Adam") 45 | True 46 | >>> is_palindrome_reverse("Never odd or even") 47 | True 48 | >>> is_palindrome_reverse("") 49 | True 50 | >>> is_palindrome_reverse(" ") 51 | True 52 | """ 53 | s = "".join(char for char in s.lower() if s.isalnum()) 54 | return s == s[::-1] 55 | 56 | 57 | def is_palindrome_reversion(s: str) -> bool: 58 | """ 59 | Test if a string is palindrome string by reversion. 60 | :param s: the string to be checked 61 | :return: True if the string is palindrome, otherwise False. 62 | >>> is_palindrome_reversion("Able was I ere I saw Elba") 63 | True 64 | >>> is_palindrome_reversion("A man, a plan, a canal – Panama") 65 | True 66 | >>> is_palindrome_reversion("Madam, I'm Adam") 67 | True 68 | >>> is_palindrome_reversion("Never odd or even") 69 | True 70 | >>> is_palindrome_reversion("12345") 71 | False 72 | >>> is_palindrome_reverse("") 73 | True 74 | >>> is_palindrome_reverse(" ") 75 | True 76 | """ 77 | s = "".join(char for char in s.lower() if s.isalnum()) 78 | if len(s) <= 1: 79 | return True 80 | elif s[0] != s[len(s) - 1]: 81 | return False 82 | else: 83 | return is_palindrome_reversion(s[1 : len(s) - 1]) 84 | 85 | 86 | if __name__ == "__main__": 87 | from doctest import testmod 88 | 89 | testmod() 90 | -------------------------------------------------------------------------------- /strings/remove_whitespace.py: -------------------------------------------------------------------------------- 1 | def remove_whitespace(original: str) -> str: 2 | """ 3 | >>> remove_whitespace("I Love Python") 4 | 'ILovePython' 5 | >>> remove_whitespace("I Love Python") 6 | 'ILovePython' 7 | >>> remove_whitespace(' I Love Python') 8 | 'ILovePython' 9 | >>> remove_whitespace("") 10 | '' 11 | """ 12 | return "".join(original.split()) 13 | 14 | 15 | def remove_whitespace2(original: str) -> str: 16 | """ 17 | >>> remove_whitespace2("I Love Python") 18 | 'ILovePython' 19 | >>> remove_whitespace2("I Love Python") 20 | 'ILovePython' 21 | >>> remove_whitespace2(' I Love Python') 22 | 'ILovePython' 23 | >>> remove_whitespace2("") 24 | '' 25 | """ 26 | return original.replace(" ", "") 27 | 28 | 29 | if __name__ == "__main__": 30 | from doctest import testmod 31 | 32 | testmod() 33 | -------------------------------------------------------------------------------- /strings/reverse.py: -------------------------------------------------------------------------------- 1 | def reverse(original: str) -> str: 2 | """ 3 | >>> reverse("abc") 4 | 'cba' 5 | >>> reverse('1234') 6 | '4321' 7 | >>> reverse("cba321") 8 | '123abc' 9 | >>> reverse("") 10 | '' 11 | """ 12 | return original[::-1] 13 | 14 | 15 | def reverse2(original: str) -> str: 16 | """ 17 | >>> reverse2("abc") 18 | 'cba' 19 | >>> reverse2('1234') 20 | '4321' 21 | >>> reverse2("cba321") 22 | '123abc' 23 | >>> reverse2("") 24 | '' 25 | """ 26 | original = list(original) 27 | i, j = 0, len(original) - 1 28 | while i < j: 29 | original[i], original[j] = ( 30 | original[j], 31 | original[i], 32 | ) 33 | i += 1 34 | j -= 1 35 | return "".join(original) 36 | 37 | 38 | if __name__ == "__main__": 39 | from doctest import testmod 40 | 41 | testmod() 42 | --------------------------------------------------------------------------------