w3resource

Python: Sort a list of elements using Pancake sort


18. Pancake Sort

Write a Python program to sort a list of elements using Pancake sort.
Pancake sorting is the colloquial term for the mathematical problem of sorting a disordered stack of pancakes in order of size when a spatula can be inserted at any point in the stack and used to flip all pancakes above it. A pancake number is the minimum number of flips required for a given number of pancakes. The problem was first discussed by American geometer Jacob E. Goodman. It is a variation of the sorting problem in which the only allowed operation is to reverse the elements of some prefix of the sequence.

Sample Solution:

Python Code:

def pancake_sort(nums):
    arr_len = len(nums)
    while arr_len > 1:
        mi = nums.index(max(nums[0:arr_len]))
        nums = nums[mi::-1] + nums[mi+1:len(nums)]
        nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]
        arr_len -= 1
    return nums

user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
print(pancake_sort(nums))

Sample Output:

Input numbers separated by a comma:
 15, 79, 25, 38, 69
[15, 25, 38, 69, 79]

Flowchart:

Flowchart: Python Data Structures and Algorithms: Sort a list of elements using Pancake sort

For more Practice: Solve these Related Problems:

  • Write a Python program to implement pancake sort and print the flip sequence required to sort the list.
  • Write a Python script to perform pancake sort on an array and display intermediate pancake flips at each step.
  • Write a Python program to sort a list using pancake sort and then count the total number of flips performed.
  • Write a Python function to implement pancake sort on a list of numbers and then verify the sorted output by reversing the flips.

Go to:


Previous: Write a Python program to sort a list of elements using Heap sort.
Next: Write a Python program to sort a list of elements using Radix sort.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.