Skip to content

Commit f0739fc

Browse files
committed
gnome_sort : type hints, docstring, doctests
1 parent 1f99120 commit f0739fc

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed

sorts/gnome_sort.py

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,55 @@
1-
"""Gnome Sort Algorithm."""
1+
"""
2+
Gnome Sort Algorithm (A.K.A. Stupid Sort)
23
4+
This algorithm iterates over a list comparing an element with the previous one.
5+
If order is not respected, it swaps element backward until
6+
order is respected with previous element.
7+
It resumes the initial iteration from element new position.
38
4-
def gnome_sort(unsorted):
5-
"""Pure implementation of the gnome sort algorithm in Python."""
6-
if len(unsorted) <= 1:
7-
return unsorted
9+
For doctests run following command:
10+
python3 -m doctest -v gnome_sort.py
11+
12+
For manual testing run:
13+
python3 gnome_sort.py
14+
"""
15+
16+
17+
def gnome_sort(lst: list) -> list:
18+
"""
19+
Pure implementation of the gnome sort algorithm in Python
20+
21+
Take some mutable ordered collection with heterogeneous
22+
comparable items inside as argument,
23+
return the same collection ordered by ascending.
24+
25+
Examples:
26+
>>> gnome_sort([0, 5, 3, 2, 2])
27+
[0, 2, 2, 3, 5]
28+
29+
>>> gnome_sort([])
30+
[]
31+
32+
>>> gnome_sort([-2, -5, -45])
33+
[-45, -5, -2]
34+
"""
35+
if len(lst) <= 1:
36+
return lst
837

938
i = 1
1039

11-
while i < len(unsorted):
12-
if unsorted[i - 1] <= unsorted[i]:
40+
while i < len(lst):
41+
if lst[i - 1] <= lst[i]:
1342
i += 1
1443
else:
15-
unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
44+
lst[i - 1], lst[i] = lst[i], lst[i - 1]
1645
i -= 1
1746
if i == 0:
1847
i = 1
1948

49+
return lst
50+
2051

2152
if __name__ == "__main__":
2253
user_input = input("Enter numbers separated by a comma:\n").strip()
2354
unsorted = [int(item) for item in user_input.split(",")]
24-
gnome_sort(unsorted)
25-
print(unsorted)
55+
print(gnome_sort(unsorted))

0 commit comments

Comments
 (0)