A. Miranda A. Miranda - 2 months ago 10
Python Question

Removing every nth element from a list until two elements remain in python3

modeling a game of Russian roulette where the contestants stand in a circle.
-every 7th contestant loses until 2 are left alive.

contestants = list(range(1, 51))
dead_men = []
dead_man = 6

while len(contestants) > 2:
if dead_man > len(contestants):
dead_man = dead_man - len(contestants)
loser = contestants.pop(dead_man)
dead_men.append(loser)
dead_man += 6


This gives me an index error with an index of 9 when my list length is 8

Answer

I assume you meant contestants instead of soldiers everywhere?

If so, then I think you just need:

while dead_man >= len(contestants):

(while rather than if in case you need to subtract multiple times, and >= rather than just > since indexes always need to be less than the length of the list)

You might also use dead_man %= len(contestants). This uses module arithmetic.

My favorite way to do this sort of thing with the modulo trick:

contestants = list(range(1, 51))
dead_men = []
dead_man = 6 % len(contestants)

while len(contestants) > 2:
    loser = contestants.pop(dead_man)
    dead_men.append(loser)
    dead_man = (dead_man + 6) % len(contestants)