docs: Add type hints and improve documentation for pancake_sort (#13960)

* docs: Add type hints and improve documentation for pancake_sort

Updated docstring for pancake_sort function to include detailed explanations of parameters, return values, time complexity, and space complexity. Improved formatting and added examples for clarity.

* Apply batched suggestions from code review

Co-authored-by: Christian Clauss <cclauss@me.com>

---------

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Charan Nadipudi
2026-09-19 23:59:14 +02:00
committed by GitHub
co-authored by Christian Clauss
parent b5aa7be2fd
commit ec98ef96e2
+24 -12
View File
@@ -1,12 +1,23 @@
"""
This is a pure Python implementation of the pancake sort algorithm
"""Pancake Sort Algorithm Implementation.
A pure Python implementation of the Pancake Sort algorithm.
Pancake sort is a sorting algorithm that sorts an array by repeatedly flipping
subsections of the array, similar to how you might sort a stack of pancakes
by inserting a spatula and flipping the top portion.
The algorithm works by finding the maximum element, flipping it to the top,
then flipping it down to its correct position. This process is repeated for
the remaining unsorted portion.
Time Complexity: O(n^2) - We perform n iterations, each with up to 2 flips
Space Complexity: O(1) - In-place sorting, only uses a constant amount of extra space
For doctests run following command:
python3 -m doctest -v pancake_sort.py
python3 -m doctest -v pancake_sort.py
or
python -m doctest -v pancake_sort.py
python -m doctest -v pancake_sort.py
For manual testing run:
python pancake_sort.py
python pancake_sort.py
"""
from collections.abc import Sequence
@@ -51,12 +62,13 @@ def pancake_sort[T: Comparable](arr: Sequence[T]) -> list[T]:
arr = list(arr)
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
# Find the index of maximum element in arr[0:cur]
max_index = arr.index(max(arr[:cur]))
# Move maximum element to end of current unsorted portion:
# 1. Flip to bring max to the beginning
arr[: max_index + 1] = reversed(arr[: max_index + 1])
# 2. Flip to send max to position cur-1
arr[:cur] = reversed(arr[:cur])
cur -= 1
return arr
@@ -67,4 +79,4 @@ if __name__ == "__main__":
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{pancake_sort(unsorted) = }")
print(f"{unsorted = }, {pancake_sort(unsorted) = }")