diff --git a/.editorconfig b/.editorconfig index dec6b5b..4c3931a 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,7 +8,8 @@ root = true [*] -indent_style = tab +indent_style = space +indent_size = 4 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true diff --git a/.github/code-of-conduct.md b/.github/code-of-conduct.md new file mode 100644 index 0000000..f809c8b --- /dev/null +++ b/.github/code-of-conduct.md @@ -0,0 +1,40 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/contributing.md b/.github/contributing.md new file mode 100644 index 0000000..d8d5c29 --- /dev/null +++ b/.github/contributing.md @@ -0,0 +1,103 @@ +## Contributing + +> Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. + +## See + +- [General Rules](#general-rules) +- [All ▲lgorithms Structure](#all-lgorithms-python-library-structure) +- [Adding new algorithms](#adding-new-algorithms) +- [Style](#style) +- [Adding Documentation](#adding-documentation) + +### General Rules + +- As much as possible, try to follow the existing format of markdown and code. + +### All ▲lgorithms Python Library Structure + +- Directories and files are all in lower case letter. +- Files are separated by an underscore (`_`) following the `snake_case` style. +- Directories in documentation are separated by a minus or hyphen (`-`) following `kebeab-case` style. + +> We follow this structure + +``` +├── allalgorithms +│ │── sorting +| | │── bubble_sort.py +| | └── merge_sort.py +│ └── searches +| │── binary_search.py +| └── linear_search.py +├── docs +│ │── sorting +| | │── bubble-sort.md +| | └── merge-sort.md +│ └── searches +| │── binary-search.md +| └── linear-search.md +└── tests + │── test_searches.py + └── test_sorting.py +``` + +### Adding new algorithms + +- Make your pull requests to be **specific** and **focused**. Instead of contributing "several algorithms" all at once contribute them all one by one separately (i.e. one pull request for "Binary Search", another one +for "Bubble Sort" and so on). +- Describe what you do in code using **comments**. + +### Style + +

Please DO NOT EDIT CHANGELOG on your pull requests, this is must be edited by one of the write access maintainers when they going to drop a new release.

+ +This repository follow the [PEP8 Style Gide for Python](https://www.python.org/dev/peps/pep-0008/), so make sure you lint your code before adding a new pull request. + +Each `.py` file should have the following header. (no for testing files) + +```py +# -*- coding: UTF-8 -*- +# +# Binary search works for a sorted array. +# The All ▲lgorithms library for python +# +# Contributed by: Carlos Abraham Hernandez +# Github: @abranhe +# +``` + +If the algorithm is modified, this should be included there also. + +```py +# Contributed by: Carlos Abraham Hernandez +# Github: @abranhe +# +# Modified by: Your Name +# Github: @yourgithubusername +``` + +If the algorithm have been modified by multiple contributors, that should be included as follow. + +```py +# Contributed by: Carlos Abraham Hernandez +# Github: @abranhe +# +# Modifiers: +# Your Name, @yourgithubusername +# Your friend's name, @yourfriendongithub +``` + +### Adding Documentation + +Please make sure if you add an algorithm, you also add the required +documentation for it the `/docs` directory. + +Follow some of the examples already added. + +If you are modifying an algorithm make sure you add a benchmark using [Repl.it](https://repl.it/) for the maintainers to have it easy to review it. + + +#### Lastly and not less important: + +Make sure you start ⭐️ the project and follow [@abranhe](https://git.io/abranhe) diff --git a/.github/issue_template.md b/.github/issue_template.md new file mode 100644 index 0000000..9bfede2 --- /dev/null +++ b/.github/issue_template.md @@ -0,0 +1,21 @@ + + +This issue is: + + + +- [ ] A new Algorithm +- [ ] An update to an existing algorithm. +- [ ] An error found +- [ ] A proposal +- [ ] A question +- [ ] Other (Describe below*) + +**Description:** + + diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b85077b --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,23 @@ + + +This pull request is: + + + +- [ ] A new Algorithm +- [ ] An update to an existing algorithm. +- [ ] An error fix +- [ ] Other (Describe below*) + +This pull request fixes: + + + +**Changes:** + + diff --git a/allalgorithms/.editorconfig b/allalgorithms/.editorconfig index 4d5a7f0..3e4ba08 100644 --- a/allalgorithms/.editorconfig +++ b/allalgorithms/.editorconfig @@ -7,7 +7,8 @@ root = true [*] -indent_style = tab +indent_style = space +indent_size = 4 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true diff --git a/allalgorithms/numeric/__init__.py b/allalgorithms/numeric/__init__.py new file mode 100644 index 0000000..cd1f5cc --- /dev/null +++ b/allalgorithms/numeric/__init__.py @@ -0,0 +1 @@ +from .max_numbers import find_max \ No newline at end of file diff --git a/allalgorithms/numeric/max_numbers.py b/allalgorithms/numeric/max_numbers.py new file mode 100644 index 0000000..122734a --- /dev/null +++ b/allalgorithms/numeric/max_numbers.py @@ -0,0 +1,16 @@ +# -*- coding: UTF-8 -*- +# +# Numeric Algorithms +# The All ▲lgorithms library for python +# +# Contributed by: Becky +# Github: @beckyw5 +# + + +def find_max (L): + max = 0 + for x in L: + if x > max: + max = x + return max diff --git a/allalgorithms/searches/__init__.py b/allalgorithms/searches/__init__.py index dad7119..1f1caa6 100644 --- a/allalgorithms/searches/__init__.py +++ b/allalgorithms/searches/__init__.py @@ -1 +1,3 @@ from .binary_search import * +from .fibonacci_search import * +from .jump_search import * diff --git a/allalgorithms/searches/fibonacci_search.py b/allalgorithms/searches/fibonacci_search.py new file mode 100644 index 0000000..0d9aa01 --- /dev/null +++ b/allalgorithms/searches/fibonacci_search.py @@ -0,0 +1,35 @@ +# -*- coding: UTF-8 -*- +# +# Fibonacci search works for a sorted array. +# The All ▲lgorithms library for python +# +# Contributed by: dieterpl +# Github: @dieterpl +# + + +def fibonacci_search(arr, query): + fib2, fib1 = 0, 1 + fib = fib2 + fib1 + hi = len(arr) - 1 + while fib <= hi: + fib2 = fib1 + fib1 = fib + fib = fib2 + fib1 + offset = -1 + while fib > 1: + i = min(offset + fib2, hi) + if arr[i] < query: + fib = fib1 + fib1 = fib2 + fib2 = fib - fib1 + offset = i + elif arr[i] > query: + fib = fib2 + fib1 = fib1 - fib2 + fib2 = fib - fib1 + else: + return i + if fib1 and arr[offset + 1] == query: + return offset + 1 + return None diff --git a/allalgorithms/searches/jump_search.py b/allalgorithms/searches/jump_search.py new file mode 100644 index 0000000..39a0cc0 --- /dev/null +++ b/allalgorithms/searches/jump_search.py @@ -0,0 +1,25 @@ +# -*- coding: UTF-8 -*- +# +# Jump search works for a sorted array. +# The All ▲lgorithms library for python +# +# Contributed by: pieromoto +# Github: @pieromoto +# +import math + +def jump_search( arr, query): + arr_len = len(arr) + prev = 0 + step = int(math.sqrt(arr_len)) + + for i in range(step-1, arr_len, step): + if(arr[i] >= query): + break + prev = i + + for j in range(prev, arr_len): + if(arr[j] == query): + return j + + return None \ No newline at end of file diff --git a/allalgorithms/sorting/__init__.py b/allalgorithms/sorting/__init__.py index d84d4f4..9d4d453 100644 --- a/allalgorithms/sorting/__init__.py +++ b/allalgorithms/sorting/__init__.py @@ -2,3 +2,8 @@ from .insertion_sort import insertion_sort from .selection_sort import selection_sort from .bubble_sort import bubble_sort +from .pigeonhole_sort import pigeonhole_sort +from .stooge_sort import stooge_sort +from .cocktail_shaker_sort import cocktail_shaker_sort +from .tree_sort import tree_sort +from .heap_sort import heap_sort diff --git a/allalgorithms/sorting/cocktail_shaker_sort.py b/allalgorithms/sorting/cocktail_shaker_sort.py new file mode 100644 index 0000000..1a0252f --- /dev/null +++ b/allalgorithms/sorting/cocktail_shaker_sort.py @@ -0,0 +1,30 @@ +# -*- coding: UTF-8 -*- +# +# Cocktail Shaker Sort Algorithm +# The All ▲lgorithms library for python +# +# Contributed by: Martmists +# Github: @martmists +# + + +def cocktail_shaker_sort(data): + upper = len(data) - 1 + lower = 0 + + no_swap = False + while upper - lower > 1 and not no_swap: + no_swap = True + for j in range(lower, upper): + if data[j + 1] < data[j]: + data[j + 1], data[j] = data[j], data[j + 1] + no_swap = False + upper = upper - 1 + + for j in range(upper, lower, -1): + if data[j - 1] > data[j]: + data[j - 1], data[j] = data[j], data[j - 1] + no_swap = False + lower = lower + 1 + + return data diff --git a/allalgorithms/sorting/heap_sort.py b/allalgorithms/sorting/heap_sort.py new file mode 100644 index 0000000..a5b9e34 --- /dev/null +++ b/allalgorithms/sorting/heap_sort.py @@ -0,0 +1,48 @@ +# -*- coding: UTF-8 -*- +# +# Heap Sort Algorithm +# The All ▲lgorithms library for python +# +# Contributed by: DatHydroGuy +# Github: @DatHydroGuy +# + + +def build_heap(array_to_sort, array_length, index): + """ + Build a heap, where each node has two child nodes, and a root node is greater than both child nodes. + """ + largest = index # Flag the largest element as the last (root) element + left = 2 * index + 1 # Calculate index of left child node + right = 2 * index + 2 # Calculate index of right child node + + # See if left child of root exists and is greater than root + if left < array_length and array_to_sort[index] < array_to_sort[left]: + largest = left + + # See if right child of root exists and is greater than root + if right < array_length and array_to_sort[largest] < array_to_sort[right]: + largest = right + + # If a larger element than root was found, swap with root so that root holds the new largest value + if largest != index: + array_to_sort[index], array_to_sort[largest] = array_to_sort[largest], array_to_sort[index] # swap + + # Re-build the heap under the new largest root node + build_heap(array_to_sort, array_length, largest) + + +def heap_sort(array_to_sort): + """ + Builds a max-heap, then continuously removes the largest element and re-builds the heap until sorted + """ + array_length = len(array_to_sort) + + # Build a max-heap to sort the elements into order + for index in range(array_length // 2 - 1, -1, -1): + build_heap(array_to_sort, array_length, index) + + # One by one extract elements + for index in range(array_length - 1, 0, -1): + array_to_sort[index], array_to_sort[0] = array_to_sort[0], array_to_sort[index] # swap + build_heap(array_to_sort, index, 0) diff --git a/allalgorithms/sorting/pigeonhole_sort.py b/allalgorithms/sorting/pigeonhole_sort.py new file mode 100644 index 0000000..c7ce64f --- /dev/null +++ b/allalgorithms/sorting/pigeonhole_sort.py @@ -0,0 +1,22 @@ +# -*- coding: UTF-8 -*- +# +# Pigeonhole Sort Algorithm +# The All ▲lgorithms library for python +# +# Contributed by: Martmists +# Github: @martmists +# + +def pigeonhole_sort(data): + minimum = min(data) + size = max(data) - minimum + 1 + holes = [0] * size + for item in data: + holes[item - minimum] += 1 + i = 0 + for count in range(size): + while holes[count] > 0: + holes[count] -= 1 + data[i] = count + minimum + i += 1 + return data diff --git a/allalgorithms/sorting/quicksort.py b/allalgorithms/sorting/quicksort.py new file mode 100644 index 0000000..6990462 --- /dev/null +++ b/allalgorithms/sorting/quicksort.py @@ -0,0 +1,29 @@ +# -*- coding: UTF-8 -*- +# +# Quick Sort Algorithm +# The All ▲lgorithms library for python +# +# Contributed by: Brian D. Hopper +# Github: @bubbabeans +# +def partition(xs, start, end): + follower = leader = start + while leader < end: + if xs[leader] <= xs[end]: + xs[follower], xs[leader] = xs[leader], xs[follower] + follower += 1 + leader += 1 + xs[follower], xs[end] = xs[end], xs[follower] + return follower + +def _quicksort(xs, start, end): + if start >= end: + return + p = partition(xs, start, end) + _quicksort(xs, start, p-1) + _quicksort(xs, p+1, end) + +def quicksort(xs): + _quicksort(xs, 0, len(xs)-1) + +# To use: create a list and send it to quicksort: quicksort(list placed here) diff --git a/allalgorithms/sorting/shell_sort.py b/allalgorithms/sorting/shell_sort.py new file mode 100644 index 0000000..b415af8 --- /dev/null +++ b/allalgorithms/sorting/shell_sort.py @@ -0,0 +1,30 @@ +# -*- coding: UTF-8 -*- +# +# Shell Sort Algorithm +# The All ▲lgorithms library for python +# +# Contributed by: Elias +# Github: @eliasbayona +# + +def shell_sort(arr): + n = len(arr) + h = int(n/2) + + + while h > 0: + for i in range(h,n): + + temp = arr[i] + j = i + + while j >= h and arr[j-h] >temp: + arr[j] = arr[j-h] + j -= h + + arr[j] = temp + + h = int(h/2) + + return arr + diff --git a/allalgorithms/sorting/stooge_sort.py b/allalgorithms/sorting/stooge_sort.py new file mode 100644 index 0000000..499f8e6 --- /dev/null +++ b/allalgorithms/sorting/stooge_sort.py @@ -0,0 +1,21 @@ +# -*- coding: UTF-8 -*- +# +# Stooge Sort Algorithm +# The All ▲lgorithms library for python +# +# Contributed by: Martmists +# Github: @martmists +# + + +def stooge_sort(seq, start=0, end=None): + if end is None: + end = len(seq) - 1 + if seq[start] > seq[end]: + seq[start], seq[end] = seq[end], seq[start] + if (end - start + 1) > 2: + third = (end - start + 1) // 3 + stooge_sort(seq, start, end-third) + stooge_sort(seq, start+third, end) + stooge_sort(seq, start, end-third) + return seq diff --git a/allalgorithms/sorting/tree_sort.py b/allalgorithms/sorting/tree_sort.py new file mode 100644 index 0000000..341c305 --- /dev/null +++ b/allalgorithms/sorting/tree_sort.py @@ -0,0 +1,48 @@ +class BinaryTreeNode(object): + #initial values for value,left and right + def __init__(self, value): + self.value = value + self.left = None + self.right = None + + +# inserting a new node in the binary tree +def insert(tree, item): + # if no initial element in the tree + if tree == None: + tree = BinaryTreeNode(item) + else: + if (item < tree.value): + # if left branch of the tree is empty + if (tree.left == None): + tree.left = BinaryTreeNode(item) + else: + insert(tree.left, item) + else: + # if right branch of the tree is empty + if (tree.right == None): + tree.right = BinaryTreeNode(item) + else: + insert(tree.right, item) + return tree + +# funtion for the inorder traversal of the binary tree +def in_order_traversal(tree,a): + if (tree.left != None): + in_order_traversal(tree.left,a) + a.append(tree.value) + if (tree.right != None): + in_order_traversal(tree.right,a) + + +def tree_sort(x): + # root node + t = insert(None, x[0]); + # inserting all elements in the binary tree + for i in x[1:]: + insert(t,i) + # the results of the inorder traversal of a binary tree is a sorted + a = [] + in_order_traversal(t,a) + return a + diff --git a/allalgorithms/string/__init__.py b/allalgorithms/string/__init__.py new file mode 100644 index 0000000..dd8aa8f --- /dev/null +++ b/allalgorithms/string/__init__.py @@ -0,0 +1,3 @@ +from .palindrome_check import * +from .is_unique import * +from .hamming_dist import * diff --git a/allalgorithms/string/hamming_dist.py b/allalgorithms/string/hamming_dist.py new file mode 100644 index 0000000..c2811e1 --- /dev/null +++ b/allalgorithms/string/hamming_dist.py @@ -0,0 +1,14 @@ +# -*- coding: UTF-8 -*- +# +# Binary search works for a sorted array. +# The All ▲lgorithms library for python +# +# Contributed by: ninexball +# Github: @ninexball +# + +def hamming_dist(seq1: str, seq2: str) -> int: + """Compare hamming distance of two strings""" + if len(seq1) != len(seq2): + raise ValueError("length of strings are not the same") + return sum(c1 != c2 for c1, c2 in zip(seq1, seq2)) diff --git a/allalgorithms/string/is_unique.py b/allalgorithms/string/is_unique.py new file mode 100644 index 0000000..986a30c --- /dev/null +++ b/allalgorithms/string/is_unique.py @@ -0,0 +1,16 @@ +# -*- coding: UTF-8 -*- +# +# Check if a string has all unique characters. +# The All ▲lgorithms library for python +# +# Contributed by: José E. Andrade Jr. +# Github: @andradejunior +# + +def is_unique(string_to_check): + character_set = set() + for character in string_to_check: + if character in character_set: + return False + character_set.add(character) + return True diff --git a/allalgorithms/string/palindrome_check.py b/allalgorithms/string/palindrome_check.py new file mode 100644 index 0000000..a9a5991 --- /dev/null +++ b/allalgorithms/string/palindrome_check.py @@ -0,0 +1,17 @@ +# -*- coding: UTF-8 -*- +# +# Checks if string is a palindrome +# The All ▲lgorithms library for python +# +# Contributed by: dieterpl +# Github: @dieterpl +# +import re + +def palindrome_check(s): + s = re.sub(r'[^\w]', '', s) + if len(s) < 2: + return True + if s[0].lower() != s[-1].lower(): + return False + return palindrome_check(s[1:-1]) diff --git a/changelog.md b/changelog.md index 558ec82..a46e7e3 100644 --- a/changelog.md +++ b/changelog.md @@ -1,14 +1,41 @@
-Algorithms +

Algorithms + +Changelog +

-# Version `0.0.0` +# `0.0.1` -Date: October 9, 2018 +Date: **TODO** + +> Algorithms: + +Added: -### Algorithms: +- **Searches** + - Fibonacci Search + - Jump Search -- Sorting +- **Sorting** - Bubble Sort -- Searches + - Cocktail Shaker Sort + - Insertion Sort + - Pigeonhole Sort + - Selection Sort + - Stooge Sort + +- **String** + - Palindrome Checker + +# `0.0.0` + +Date: October 9, 2018 + +> Algorithms: + +- **Searches** - Merge Sort + +- **Sorting** + - Bubble Sort diff --git a/docs/readme.md b/docs/readme.md index 2995cc4..9929e55 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -11,11 +11,11 @@

- - + + - Coverage Status + Coverage Status

@@ -29,9 +29,11 @@ - Why not 😂 - Clean and focused - Actively maintained -- Because All Algorithms should easy to use in Python +- Because All Algorithms should be easy to use in Python -Read the detailed documentation at [python.allalgorithms.com](https://python.allalgorithms.com) or see [Tree](#tree). +Read the detailed documentation at [python.allalgorithms.com](https://python.allalgorithms.com) or see the [`docs`](https://github.com/abranhe/allalgorithms-python/blob/master/docs) directory on Github. See [Tree](#tree). + +**Want to contribute?** [GET STARTED HERE](https://github.com/abranhe/allalgorithms-python/tree/master/.github/contributing.md) ## Install @@ -55,15 +57,25 @@ print(binary_search(arr, 3)) # Tree -- Searches - - [Binary Search](searches/binary-search) -- Sorting - - [Merge Sort](sorting/merge-sort) - +- ### Searches + - [Binary Search](https://python.allalgorithms.com/searches/binary-search) + - [Fibonacci Search](https://python.allalgorithms.com/searches/fibonacci-search) + - [Jump Search](https://python.allalgorithms.com/searches/jump-search) + +- ### Sorting + - [Bubble Sort](https://python.allalgorithms.com/sorting/bubble-sort) + - [Cocktail Shaker Sort](https://python.allalgorithms.com/sorting/cocktail-shaker-sort) + - [Insertion Sort](https://python.allalgorithms.com/sorting/insertion-sort) + - [Merge Sort](https://python.allalgorithms.com/sorting/merge-sort) + - [Pigeonhole Sort](https://python.allalgorithms.com/sorting/pigeonhole-sort) + - [Selection Sort](https://python.allalgorithms.com/sorting/selection-sort) + - [Stooge Sort](https://python.allalgorithms.com/sorting/stooge-sort) +- ### String + - [Palindrome Check](https://python.allalgorithms.com/string/palindrom-check) # Related -- [javascript-lib](https://github.com/abranhe/javascript-lib): All ▲lgorithms Javascript library +- [allalgorithms-javascript](https://github.com/abranhe/allalgorithms-javascript): All ▲lgorithms Javascript library # Maintainers @@ -78,10 +90,10 @@ print(binary_search(arr, 3)) [1]: https://cdn.abranhe.com/projects/algorithms/badge.svg -[2]: https://github.com/abranhe/python-lib +[2]: https://github.com/abranhe/allalgorithms-python [3]: https://avatars3.githubusercontent.com/u/21347264?s=50 [4]: https://github.com/abranhe -[5]: https://github.com/abranhe/python-lib/blob/master/LICENSE +[5]: https://github.com/abranhe/allalgorithms-python/blob/master/license

diff --git a/docs/searches/fibonacci-search.md b/docs/searches/fibonacci-search.md new file mode 100644 index 0000000..fc09267 --- /dev/null +++ b/docs/searches/fibonacci-search.md @@ -0,0 +1,33 @@ +# Fibonacci Search + +In computer science, the Fibonacci search technique is a method of searching a sorted array using a divide and conquer algorithm that narrows down possible locations with the aid of Fibonacci numbers. (Wikipedia) +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.searches import fibonacci_search + +arr = [-2, 1, 2, 7, 10, 77] + +print(fibonacci_search(arr, 7)) +# -> 3 + +print(fibonacci_search(arr, 3)) +# -> None +``` + +## API + +### fibonacci_search(array, query) + +> Return array index if its found, otherwise returns `None` + +##### Params: + +- `array`: Sorted Array +- `query`: Element to search for in the array diff --git a/docs/searches/jump-search.md b/docs/searches/jump-search.md new file mode 100644 index 0000000..d439278 --- /dev/null +++ b/docs/searches/jump-search.md @@ -0,0 +1,36 @@ +# Jump Search + +In computer science, jump search is a search algorithm for sorted array which find the element by jumping ahead by fixed steps or skipping some elements in place of searching all elements. + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.searches import jump_search + +arr = [-2, 1, 2, 7, 10, 77] + +print(jump_search(arr, 7)) +# -> 3 + +print(jump_search(arr, 3)) +# -> None +``` + +## API + +### jump_search(array, query) + +> Return array index if its found, otherwise returns `None` + +##### Params: + +- `arr`: Sorted Array +- `query`: Element to search for in the array + + diff --git a/docs/sorting/cocktail-shaker-sort.md b/docs/sorting/cocktail-shaker-sort.md new file mode 100644 index 0000000..8d8841c --- /dev/null +++ b/docs/sorting/cocktail-shaker-sort.md @@ -0,0 +1,30 @@ +# Cocktail Shaker Sort + +Cocktail shaker sort, also known as bidirectional bubble sort, cocktail sort, shaker sort (which can also refer to a variant of selection sort), ripple sort, shuffle sort, or shuttle sort, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more difficult to implement than a bubble sort, and solves the problem of turtles in bubble sorts. It provides only marginal performance improvements, and does not improve asymptotic performance; like the bubble sort, it is not of practical interest (insertion sort is preferred for simple sorts), though it finds some use in education. + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import cocktail_shaker_sort + +arr = [77, 2, 10, -2, 1, 7] + +print(cocktail_shaker_sort(arr)) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +### cocktail_shaker_sort(array) + +> Returns a sorted array + +##### Params: + +- `array`: Unsorted Array diff --git a/docs/sorting/heap-sort.md b/docs/sorting/heap-sort.md new file mode 100644 index 0000000..09edef6 --- /dev/null +++ b/docs/sorting/heap-sort.md @@ -0,0 +1,33 @@ +# Heap Sort + +Heap sort is a comparison-based sorting algorithm which operates on a Binary Heap data structure. It can be regarded as a version of Selection sort which is improved by use of the heap data structure rather than a linear-time search. + +Heap sort is typically slower than Quicksort, but it does have a better worst-case scenario of O(n log n). It is an in-place algorithm, but does not produce a stable sort. + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import heap_sort + +arr = [77, 2, 10, -2, 1, 7] +heap_sort(arr) + +print(arr) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +### heap_sort(array) + +> Performs an in-place sort of the passed-in array + +##### Params: + +- `array`: Unsorted Array diff --git a/docs/sorting/pigeonhole-sort.md b/docs/sorting/pigeonhole-sort.md new file mode 100644 index 0000000..d74631b --- /dev/null +++ b/docs/sorting/pigeonhole-sort.md @@ -0,0 +1,30 @@ +# Pigeonhole Sort + +Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the length of the range of possible key values (N) are approximately the same. It requires O(n + N) time. It is similar to counting sort, but differs in that it "moves items twice: once to the bucket array and again to the final destination [whereas] counting sort builds an auxiliary array then uses the array to compute each item's final destination and move the item there." + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import pigeonhole_sort + +arr = [77, 2, 10, -2, 1, 7] + +print(pigeonhole_sort(arr)) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +### pigeonhole_sort(array) + +> Returns a sorted array + +##### Params: + +- `array`: Unsorted Array diff --git a/docs/sorting/quicksort.md b/docs/sorting/quicksort.md new file mode 100644 index 0000000..e09bc38 --- /dev/null +++ b/docs/sorting/quicksort.md @@ -0,0 +1,39 @@ +# Quicksort + +A quicksort is a quicker method of sorting, and there are four different ways of implementing it. The example given uses a pivot point. + +A pivot point is created in the middle of an array, and all larger items go after the pivot point, and smaller items are placed in front +of the pivot point. + +The pivot point is then moved to the middle of either the smaller or larger items, and the sort is run again on that half. + +This continues over and over again until everything is in the proper place. + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import quicksort + +arr = [77, 2, 10, -2, 1, 7] + +print(quicksort(arr)) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +``` +quicksort(array) +``` + +> Returns a sorted array + +##### Params: + +- `array`: Sorted Array diff --git a/docs/sorting/shell-sort.md b/docs/sorting/shell-sort.md new file mode 100644 index 0000000..f984897 --- /dev/null +++ b/docs/sorting/shell-sort.md @@ -0,0 +1,29 @@ +# Selection Sort + +In computer science, shell sort improves upon insertion sort by moving out of order elements more than one position at a time. It has a best case O(n log n) time complexity, and for other cases, it depends on the gap sequence. According to Poonen Theorem, worst case complexity for shell sort is Θ(NlogN)^2/(log logN)^2) or Θ(NlogN)^2/log logN) or Θ(N(logN)^2) or something in between. +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import shell_sort + +arr = [77, 2, 10, -2, 1, 7] + +print(shell_sort(arr)) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +### selection_sort(array) + +> Returns a sorted array + +##### Params: + +- `array`: Unsorted Array diff --git a/docs/sorting/stooge-sort.md b/docs/sorting/stooge-sort.md new file mode 100644 index 0000000..816fdea --- /dev/null +++ b/docs/sorting/stooge-sort.md @@ -0,0 +1,30 @@ +# Stooge Sort + +Stooge sort is a recursive sorting algorithm. It is notable for its exceptional bad time complexity of O(n^(log 3 / log 1.5)) = O(n^2.7095...). The running time of the algorithm is thus slower compared to reasonable sorting algorithms, and is slower than Bubble sort, a canonical example of a fairly inefficient sort. It is however more efficient than Slowsort. + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import stooge_sort + +arr = [77, 2, 10, -2, 1, 7] + +print(stooge_sort(arr)) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +### stooge_sort(array) + +> Returns a sorted array + +##### Params: + +- `array`: Unsorted Array diff --git a/docs/sorting/tree-sort.md b/docs/sorting/tree-sort.md new file mode 100644 index 0000000..bd87af6 --- /dev/null +++ b/docs/sorting/tree-sort.md @@ -0,0 +1,38 @@ +# Tree Sort + +A tree sort is a sort algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order. It has two phases: +1. Frist is creating a binary search tree using the given array elements. +2. Second phase is traversing the given binary search tree in inorder, thus resulting in a sorted array. + +**Performance** + +The average number of comparisions for this method is O(nlogn). But in worst case, number of comparisions is reduced by O(n^2), a case which arrives when the tree is skewed. + + + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.sorting import tree_sort + +arr = [77, 2, 10, -2, 1, 7] + +print(tree_sort(arr)) +# -> [-2, 1, 2, 7, 10, 77] +``` + +## API + +### tree_sort(array) + +> Returns a sorted array + +##### Params: + +- `array`: Unsorted Array \ No newline at end of file diff --git a/docs/string/hamming-dist.md b/docs/string/hamming-dist.md new file mode 100644 index 0000000..124a824 --- /dev/null +++ b/docs/string/hamming-dist.md @@ -0,0 +1,32 @@ +# Hamming Distance + +In informatics, Hamming distance is the number of positions where the characters differ between two strings of equal length + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +``` +>>> from allalgorithms.sorting import hamming_dist + +>>> hamming_dist("hello world", "hello wario") +3 +``` + +## API + +### hamming_dist(seq1, seq2) + +> Returns an integer + +> Raises a ValueError if strings are of unequal length + +##### Params: + +- `seq1`: first string to compare +- `seq2`: second string to compare + diff --git a/docs/string/is-unique.md b/docs/string/is-unique.md new file mode 100644 index 0000000..7dc439f --- /dev/null +++ b/docs/string/is-unique.md @@ -0,0 +1,36 @@ +# Is Unique + +This algorithms checks if a string has all unique characters in O(n) time. + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.string import is_unique + +str = "abcdefg" + +print(is_unique(str) +# -> True + +str = "test" + +print(is_unique(str) +# -> False +``` + +## API + +### is_unique(string) + +> Return True if string has all unique characters, False otherwise + +##### Params: + +- `string`: Input String + diff --git a/docs/string/palindrome-check.md b/docs/string/palindrome-check.md new file mode 100644 index 0000000..6e6cc7f --- /dev/null +++ b/docs/string/palindrome-check.md @@ -0,0 +1,36 @@ +# Palindrome Check + +A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar or the number 10201. (Wikipedia) + +## Install + +``` +pip install allalgorithms +``` + +## Usage + +```py +from allalgorithms.string import palindrome_check + +str = "10201" + +print(palindrome_check(str) +# -> True + +str = "test" + +print(palindrome_check(str) +# -> False +``` + +## API + +### palindrome_check(string) + +> Return True if string is a palindrome, False otherwise + +##### Params: + +- `string`: Input String + diff --git a/readme.md b/readme.md index 2a480f2..36c01ba 100644 --- a/readme.md +++ b/readme.md @@ -11,11 +11,11 @@

- - + + - Coverage Status + Coverage Status

@@ -31,7 +31,9 @@ - Actively maintained - Because All Algorithms should be easy to use in Python -Read the detailed documentation at [python.allalgorithms.com](https://python.allalgorithms.com) or see the [`docs`](https://github.com/abranhe/python-lib/blob/master/docs) directory on Github. See [Tree](#tree). +Read the detailed documentation at [python.allalgorithms.com](https://python.allalgorithms.com) or see the [`docs`](https://github.com/abranhe/allalgorithms-python/blob/master/docs) directory on Github. See [Tree](#tree). + +**Want to contribute?** [GET STARTED HERE](https://github.com/abranhe/allalgorithms-python/tree/master/.github/contributing.md) ## Install @@ -55,15 +57,25 @@ print(binary_search(arr, 3)) # Tree -- Searches +- ### Searches - [Binary Search](https://python.allalgorithms.com/searches/binary-search) -- Sorting - - [Merge Sort](https://python.allalgorithms.com/sorting/merge-sort) - + - [Fibonacci Search](https://python.allalgorithms.com/searches/fibonacci-search) + - [Jump Search](https://python.allalgorithms.com/searches/jump-search) + +- ### Sorting + - [Bubble Sort](https://python.allalgorithms.com/sorting/bubble-sort) + - [Cocktail Shaker Sort](https://python.allalgorithms.com/sorting/cocktail-shaker-sort) + - [Insertion Sort](https://python.allalgorithms.com/sorting/insertion-sort) + - [Merge Sort](https://python.allalgorithms.com/sorting/merge-sort) + - [Pigeonhole Sort](https://python.allalgorithms.com/sorting/pigeonhole-sort) + - [Selection Sort](https://python.allalgorithms.com/sorting/selection-sort) + - [Stooge Sort](https://python.allalgorithms.com/sorting/stooge-sort) +- ### String + - [Palindrome Check](https://python.allalgorithms.com/string/palindrom-check) # Related -- [javascript-lib](https://github.com/abranhe/javascript-lib): All ▲lgorithms Javascript library +- [allalgorithms-js](https://github.com/abranhe/allalgorithms-js): All ▲lgorithms Javascript library # Maintainers @@ -78,10 +90,10 @@ print(binary_search(arr, 3)) [1]: https://cdn.abranhe.com/projects/algorithms/badge.svg -[2]: https://github.com/abranhe/python-lib +[2]: https://github.com/abranhe/allalgorithms-python [3]: https://avatars3.githubusercontent.com/u/21347264?s=50 [4]: https://github.com/abranhe -[5]: https://github.com/abranhe/python-lib/blob/master/LICENSE +[5]: https://github.com/abranhe/allalgorithms-python/blob/master/license

diff --git a/setup.py b/setup.py index c8eca1f..5a95e27 100644 --- a/setup.py +++ b/setup.py @@ -27,6 +27,6 @@ 'Programming Language :: Python :: 3.6', ), project_urls={ - 'Source': 'https://github.com/abranhe/python-lib', + 'Source': 'https://github.com/abranhe/allalgorithms-python', }, ) diff --git a/tests/test_numeric.py b/tests/test_numeric.py new file mode 100644 index 0000000..2be532d --- /dev/null +++ b/tests/test_numeric.py @@ -0,0 +1,13 @@ +import unittest + +from allalgorithms.numeric import find_max + + +class TestMax(unittest.TestCase): + + def test_find_max_value(self): + test_list = [3, 1, 8, 7, 4] + self.assertEqual(8, find_max(test_list)) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_searches.py b/tests/test_searches.py index 622beeb..41120f7 100644 --- a/tests/test_searches.py +++ b/tests/test_searches.py @@ -1,7 +1,10 @@ import unittest -from allalgorithms.searches import binary_search - +from allalgorithms.searches import ( + binary_search, + fibonacci_search, + jump_search +) class TestSearches(unittest.TestCase): @@ -12,6 +15,19 @@ def test_binary_search(self): self.assertEqual(None, binary_search(arr, 8)) self.assertEqual(None, binary_search(arr, -1)) + def test_fibonacci_search(self): + arr = [1, 2, 3, 7, 10, 19, 27, 77] + self.assertEqual(3, fibonacci_search(arr, 7)) + self.assertEqual(7, fibonacci_search(arr, 77)) + self.assertEqual(None, fibonacci_search(arr, 8)) + self.assertEqual(None, fibonacci_search(arr, -1)) + + def test_jump_search(self): + arr = [1, 2, 3, 7, 10, 19, 27, 77] + self.assertEqual(3, binary_search(arr, 7)) + self.assertEqual(7, binary_search(arr, 77)) + self.assertEqual(None, binary_search(arr, 8)) + self.assertEqual(None, binary_search(arr, -1)) if __name__ == '__main__': unittest.main() diff --git a/tests/test_sorting.py b/tests/test_sorting.py index e11902b..680a943 100644 --- a/tests/test_sorting.py +++ b/tests/test_sorting.py @@ -1,12 +1,19 @@ import unittest from allalgorithms.sorting import ( - bubble_sort, - insertion_sort, - merge_sort, - selection_sort + bubble_sort, + insertion_sort, + merge_sort, + selection_sort, + pigeonhole_sort, + stooge_sort, + cocktail_shaker_sort, + tree_sort, + heap_sort, + shell_sort, ) + class TestSorting(unittest.TestCase): def test_merge_sort(self): self.assertEqual([-44, 1, 2, 3, 7, 19], merge_sort([7, 3, 2, 19, -44, 1])) @@ -20,6 +27,25 @@ def test_insertion_sort(self): def test_selection_sort(self): self.assertEqual([-44, 1, 2, 3, 7, 19], selection_sort([7, 3, 2, 19, -44, 1])) + def test_pigeonhole_sort(self): + self.assertEqual([-44, 1, 2, 3, 7, 19], pigeonhole_sort([7, 3, 2, 19, -44, 1])) + + def test_stooge_sort(self): + self.assertEqual([-44, 1, 2, 3, 7, 19], stooge_sort([7, 3, 2, 19, -44, 1])) + + def test_cocktail_shaker_sort(self): + self.assertEqual([-44, 1, 2, 3, 7, 19], cocktail_shaker_sort([7, 3, 2, 19, -44, 1])) + + def test_tree_sort(self): + self.assertEqual([-44, 1, 2, 3, 7, 19], tree_sort([7, 3, 2, 19, -44, 1])) + + def test_heap_sort(self): + array = [7, 3, 2, 19, -44, 1] + heap_sort(array) + self.assertEqual([-44, 1, 2, 3, 7, 19], array) + + def test_shell_sort(self): + self.assertEqual([-44, 1, 2, 3, 7, 19], shell_sort([7, 3, 2, 19, -44, 1])) if __name__ == "__main__": unittest.main() diff --git a/tests/test_string.py b/tests/test_string.py new file mode 100644 index 0000000..3cca91c --- /dev/null +++ b/tests/test_string.py @@ -0,0 +1,26 @@ +import unittest + +from allalgorithms.string import palindrome_check, is_unique + + +class TestSorting(unittest.TestCase): + + def test_palindrome_check(self): + self.assertEqual(True, palindrome_check("a")) + self.assertEqual(True, palindrome_check("10201")) + self.assertEqual(False, palindrome_check("test")) + self.assertEqual(True, palindrome_check("Mr. Owl ate my metal worm")) + self.assertEqual(True, palindrome_check("Was it a car or a cat I saw?")) + self.assertEqual(False, palindrome_check("How are you?")) + + def test_is_unique(self): + self.assertEqual(True, is_unique("abcdefg")) + self.assertEqual(True, is_unique("1234567")) + self.assertEqual(True, is_unique("algorithms")) + self.assertEqual(False, is_unique("abcdefa")) + self.assertEqual(False, is_unique("abddefg")) + self.assertEqual(False, is_unique("12345567")) + + +if __name__ == "__main__": + unittest.main()