I wanted to know if it will be possible to solve the Josepheus problem using list in python.
In simple terms Josephus problem is all about finding a position in a circular arrangement which would be safe if executions were handled out using a skip parameter which is known beforehand.
For eg : given a circular arrangement such as [1,2,3,4,5,6,7]
and a skip parameter of 3, the people will be executed in the order as 3,6,2,7,5,1
and position 4
would be the safe.
I have been trying to solve this using list for some time now, but the index positions becomes tricky for me to handle.
a=[x for x in range(1,11)] skip=2 step=2 while (len(a)!=1): value=a[step-1] a.remove(value) n=len(a) step=step+skip large=max(a) if step>=n: diff=abs(large-value) step=diff%skip print a
Updated the question with code snippet, but i don’t think my logic is correct.
Advertisement
Answer
Quite simply, you can use list.pop(i)
to delete each victim (and get his ID) in a loop. Then, we just have to worry about wrapping the indices, which you can do just by taking the skipped index mod the number of remaining prisoners.
So then, the question solution becomes
def josephus(ls, skip): skip -= 1 # pop automatically skips the dead guy idx = skip while len(ls) > 1: print(ls.pop(idx)) # kill prisoner at idx idx = (idx + skip) % len(ls) print('survivor: ', ls[0])
Test output:
>>> josephus([1,2,3,4,5,6,7], 3) 3 6 2 7 5 1 survivor: 4