# Program to arrange cards so that they can be revealed in ascending order in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a list of cards, and we want to order the cards in a way so that they are revealed in ascending order. As we know, the cards are revealed in this manner: 1. The top most card is removed and revealed and then next card is gone to the back. 2. Step 1 is repeated until there's no more cards. We have to find an ordering of the cards such that they are revealed in ascending order.

So, if the input is like cards = [1, 2, 3, 4, 5, 6, 7, 8], then the output will be [1, 5, 2, 7, 3, 6, 4, 8], as 1 is removed and 5 is moved to the back, current situation [2, 7, 3, 6, 4, 8, 5]. 2 is removed and 7 is moved to the back, current situation [3, 6, 4, 8, 5, 7] 3 is removed and 6 is moved to the back, current situation [4, 8, 5, 7, 6] 4 is removed and 8 is moved to the back, current situation [5, 7, 6, 8] 5 is removed and 7 is moved to the back, current situation [6, 8, 7]. 6 is removed and 8 is moved to the back, current situation [7, 8]. 7 is removed and there is only one card . Then remove 

To solve this, we will follow these steps −

• sort the list cards
• idx:= a list with elements 0 to length of cards
• order:= a new list
• q:= a queue and insert elements of idx
• while q is non-zero, do
• delete element from left of q and insert into order
• if q is non-zero, then
• ans:= make a list of size cards, and fill with 0
• for each element i from order and card from cards, do
• ans[i]:= card
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import deque
class Solution:
def solve(self, cards):
cards.sort()
idx=[i for i in range(len(cards))]
order=[]
q=deque(idx)
while q:
order.append(q.popleft())
if q: q.append(q.popleft())
ans=[0 for _ in cards]
for i,card in zip(order,cards):
ans[i]=card
return ans
ob = Solution()
print(ob.solve([1, 2, 3, 4, 5, 6, 7, 8]))

## Input

[1, 2, 3, 4, 5, 6, 7, 8]

## Output

[1, 5, 2, 7, 3, 6, 4, 8]