mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 21:45:27 +08:00
* Add type hints to pancake_sort function * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Use modern list[int] type hint instead of deprecated typing.List * Update pancake_sort to use Sequence and TypeVar Refactor pancake_sort function to accept any sequence type. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Make pancake_sort generic with type parameter T --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: changsheng <changsheng0804-blip@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
"""
|
|
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
|
|
"""
|
|
|
|
from collections.abc import Sequence
|
|
from typing import TypeVar
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
def pancake_sort[T](arr: Sequence[T]) -> list[T]:
|
|
"""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
|
|
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)]
|
|
cur -= 1
|
|
return arr
|
|
|
|
|
|
if __name__ == "__main__":
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
|
print(pancake_sort(unsorted))
|