Magician licensing problem -- python implementation

Posted by nsstudio on Fri, 20 Dec 2019 21:46:33 +0100

Problem description

The magician has A, 2, 3 J. Q, K thirteen spades. Before performing magic, the magician has stacked them in A certain order (with the colored side facing down). The magic performance process is as follows: first, the magician counts 1, then turns the top card, which is spade A; then puts it on the table; second, the magician counts 1, 2; puts the first card at the bottom of these cards, turns the second card, which is spade 2; third The magician counts 1, 2 and 3, puts the first and second cards at the bottom of these cards in turn, and turns the third card over, which is exactly spade 3 Until all the cards are turned out. Ask the order of the original cards

Correct result: [1, 8, 2, 5, 10, 3, 12, 11, 9, 4, 7, 6, 13]

Solution

1. list
def solution_list():
    pokers = [0 for _ in range(13)]         # Initialization
    count = len(pokers)                     # Total number of cards
    index = -1

    for num in range(1, 14):
        i = 0                               # count
        while i < num:
            index = (index + 1) % count     # Index one step forward (recyclable)
            if pokers[index] == 0:          # Count only when the current element is 0, skip if it is not 0
                i += 1
        pokers[index] = num

    print('#' * 50)
    print(f'\n Card group: {pokers}\n')
    print('#' * 50)
2. Single cycle list
class Node:
    """node"""

    def __init__(self, value):
        self.data = value
        self.next = None

    def __repr__(self):
        return f'Node: {self.data}'


class CircularLinkedList:
    """circular linked list """
    def __init__(self):
        self.rear = None    # Tail node

    def is_empty(self):
        return self.rear is None

    def append(self, elem):
        """Tail insertion method"""
        temp = Node(elem)
        if self.rear is None:
            temp.next = temp
            self.rear = temp
        else:
            temp.next = self.rear.next
            self.rear.next = temp
            self.rear = temp
            
    def print_all(self):
        """
        //Print all nodes in order
        """
        if self.is_empty():
            return
        p = self.rear.next      # Get head node
        print('Head', end='')
        while True:
            print('-->', p.data, end='')
            if p is self.rear:      # Reach tail stop
                break
            p = p.next
        print('-->Finish')


def solution_circular_linked_list():
    pokers = CircularLinkedList()
    for _ in range(13):
        pokers.append(0)

    temp = pokers.rear
    for num in range(1, 14):
        i = 0
        while i < num:
            temp = temp.next
            if temp.data == 0:
                i += 1
        temp.data = num

    print('#' * 50)
    print('\n Card group: ')
    pokers.print_all()
    print('\n' + '#' * 50)

Topics: Python