Add doctests for sorting algorithms (#1263)

* doctests and intro docstring added

* doctests, docstrings and check for empty collection added

* Intro docstring added

* python versions reversed
This commit is contained in:
Parth Paradkar 2019-10-03 13:49:11 +05:30 committed by Christian Clauss
parent b8490ed097
commit 390feb0b23
2 changed files with 46 additions and 8 deletions

View File

@ -1,9 +1,25 @@
"""Pancake Sort Algorithm."""
# Only can reverse array from 0 to i
"""
This is a pure python implementation of the pancake sort algorithm
For doctests run following command:
python3 -m doctest -v pancake_sort.py
or
python -m doctest -v pancake_sort.py
For manual testing run:
python pancake_sort.py
"""
def pancake_sort(arr):
"""Sort Array with Pancake Sort."""
"""Sort Array with Pancake Sort.
:param arr: Collection containing comparable items
:return: Collection ordered in ascending order of items
Examples:
>>> pancake_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([-2, -5, -45])
[-45, -5, -2]
"""
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
@ -17,4 +33,6 @@ def pancake_sort(arr):
if __name__ == '__main__':
print(pancake_sort([0, 10, 15, 3, 2, 9, 14, 13]))
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(pancake_sort(unsorted))

View File

@ -1,7 +1,29 @@
'''
This is an implementation of Pigeon Hole Sort.
For doctests run following command:
python3 -m doctest -v pigeon_sort.py
or
python -m doctest -v pigeon_sort.py
For manual testing run:
python pigeon_sort.py
'''
def pigeon_sort(array):
"""
Implementation of pigeon hole sort algorithm
:param array: Collection of comparable items
:return: Collection sorted in ascending order
>>> pigeon_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pigeon_sort([])
[]
>>> pigeon_sort([-2, -5, -45])
[-45, -5, -2]
"""
if(len(array) == 0):
return array
# Manually finds the minimum and maximum of the array.
min = array[0]
max = array[0]
@ -37,6 +59,4 @@ def pigeon_sort(array):
if __name__ == '__main__':
user_input = input('Enter numbers separated by comma:\n')
unsorted = [int(x) for x in user_input.split(',')]
sorted = pigeon_sort(unsorted)
print(sorted)
print(pigeon_sort(unsorted))