58. Last one standing
People numbered 1 to n stand in a circle. Starting from person 1, count around the circle; the person counted k-th leaves, and the count starts again at 1 with the next person still in the circle. This goes on until one person is left.
With n = 5 and k = 2: count 1, 2, so person 2 leaves. Count 3, 4: person 4 leaves. Count 5, 1: person 1 leaves. Count 3, 5: person 5 leaves. Person 3 is the last one standing.
Write a function last_standing(n, k) that takes the number of people n and the count k, and returns the number
of the last person left. k can be bigger than the number of people still in the circle: the count simply goes
round more than once. With k = 1 people leave in order, so person n is last.
Example 1
n = 5, k = 23Example 2
n = 7, k = 34Example 3
n = 1, k = 51Constraints
nandkare whole numbers from 1 to 100.
Submit also runs 8 more tests you can't see.
Practises Modules and Imports (lesson 22).
collections.dequeis a list made for adding and removing at both ends.deque(range(1, n + 1))holds the circle, person 1 at the front.circle.rotate(-1)moves the front person to the back: that is counting past them. Rotate by-(k - 1)to count past k - 1 people at once.- After that rotation the k-th person is at the front:
circle.popleft()takes them out, and the next count starts with the new front. Stop whenlen(circle) == 1.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def last_standing(n, k):
"""Find the last person left in the counting circle.
n: int, how many people, numbered 1 to n
k: int, every k-th person counted leaves
Returns: int, the number of the last person left
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.