Start free

Advanced · Stacks and queues · 204 of 264

Counting out

n people stand in a circle, numbered 1 to n. Counting starts at person 1; every k-th person leaves the circle. Print the order in which they leave. Tip: collections.deque and rotate().

Input: n and k on one line. Output: the leaving order on one line.

Examples

Input
7 3
Output
3 6 2 7 5 1 4
Input
1 1
Output
1
Input
5 2
Output
2 4 1 5 3

One more test checks other inputs when you press Check.

Stuck? The idea behind stacks and queues

A stack is last in, first out: a list's append() and pop(). A queue is first in, first out: collections.deque with append() and popleft().

Stacks match brackets and undo actions; queues serve things in the order they came.

stack = []
for ch in "(()":
    if ch == "(":
        stack.append(ch)
    elif stack:
        stack.pop()
print("left open:", len(stack))

Watch for: pop() on an empty list stops the program: check the stack isn't empty first.

All the stacks and queues exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More stacks and queues exercises