Hi I came across a question in the Algorithms 4th Edition by Robert Sedgewick.
Dequeue sort. Explain how you would sort a deck of cards, with the res
I have a strategy which seems very straightforward to myself:
Consier this the same as the bubble sort: 1) compare(possibly swap) and then move; 2) dont' compare and move(don't change the order). And two kinds of actions take 52 steps(the length of the decks) in one round.
Condition 1:
def exchange_move(cards):
if cards[0] > cards[1]:
cards[0], cards[1] = cards[1], cards[0]
cards.append(cards.popleftL())
else:
cards.append(cards.popleft())
Condition 2:
def move(cards):
cards.append(cards.popleft())
And take these two kinds of actions in each round:
for i in range(card_len-skip):
exchange_move(cards)
for i in range(skip)
move(cards)
And this is the complete code in Python:
from collections import deque
import random
from enum import Enum
class Suit(Enum):
__order__ = "spade heart club diamond"
spade = 1
heart = 2
club = 3
diamond = 4
class Card(object):
def __init__(self, suit, value):
assert type(suit) == Suit
assert value > 0 and value < 14
self._suit = suit
self._value = value
self.value = self._get_value()
def _get_value(self):
return self._suit.value * 13 + self._value
def __lt__(self, other):
return self.value < other.value
def __str__(self):
return str((self._suit.name, self._value))
cards = deque(maxlen=52)
for s in Suit:
for i in range(13):
cards.append(Card(s, i+1))
random.shuffle(cards)
def is_sorted(cards):
for i in range(len(cards)-2):
if cards[i] > cards[i+1]:
return False
return True
def exchange_move(cards):
if cards[0] > cards[1]:
cards[0], cards[1] = cards[1], cards[0]
cards.append(cards.popleft())
def move(cards):
cards.append(cards.popleft())
skip = 0
while(not is_sorted(cards)):
if skip == len(cards):
print('something strange happened')
for i in range(len(cards)-skip):
exchange_move(cards)
for i in range(skip):
move(cards)
skip += 1
for c in cards:
print(c)