From 390feb0b23b4845a7ddfec7afd703aa053d1b224 Mon Sep 17 00:00:00 2001 From: Parth Paradkar Date: Thu, 3 Oct 2019 13:49:11 +0530 Subject: [PATCH] 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 --- sorts/pancake_sort.py | 28 +++++++++++++++++++++++----- sorts/pigeon_sort.py | 26 +++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/sorts/pancake_sort.py b/sorts/pancake_sort.py index 3b48bc6e4..873c14a0a 100644 --- a/sorts/pancake_sort.py +++ b/sorts/pancake_sort.py @@ -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)) diff --git a/sorts/pigeon_sort.py b/sorts/pigeon_sort.py index 5e5afa137..5417234d3 100644 --- a/sorts/pigeon_sort.py +++ b/sorts/pigeon_sort.py @@ -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))