What is going on inside my loop?

I tried to program the Josephus problem , and for some reason it only works in some situations, I don't know why. TL, DR, how it works is:

You have a group of people in a circle. Each Nth person will be killed until only one last person remains. So say, for example, you have 10 people [AKA: X], and you decide to kill every third person [AKA: Nth], it will look like this:

1st round: 1, 2, (3 matrices), 4, 5, (6 stamps), 7, 8, (9 stamps), 10

2nd round: 1, (2 dies because it's a continuous circle), 3, 5, (7 dies), 8, 10

Third round: (1), 4, 5, (8), 10

4th round: 4, (5), 10

Fifth round: 4, (10)

And we finally stayed with person 4 as a lone survivor.

My program does a great job. However, when I enter X like 55and N like 17, I get the wrong answer from a person 27when he should be a person 40. Can someone tell me where my loop is getting confused?

Source:

def solveJosephus(specifics):
    people = [int(x) for x in range(1,int(specifics[0])+1)]
    killPosition = int(specifics[1])
    positionCounter = 0
    sorted = False

    while not sorted:
        if len(people) == 1:
            print(people[0]) # Pyschologically scarred Winner!
            sorted = True
        for person in people:
            positionCounter += 1
            if positionCounter == killPosition:
                print(person)
                people.remove(person)
                positionCounter = 1

solveJosephus(raw_input().split())
+4
source share
3 answers

In addition to all the other answers (telling you to make a copy of the list with the iteration), another problem with your code is that you reset positionCounterto 1 in this line: positionCounter = 1. It should be reset to 0. Here is the full working code (still working):

def solveJosephus(specifics):
    people = [int(x) for x in range(1,int(specifics[0])+1)]
    killPosition = int(specifics[1])
    positionCounter = 0
    sorted = False

    while not sorted:
        if len(people) == 1:
            print(people[0]) # Pyschologically scarred Winner!
            sorted = True
        for person in people[:]: #Make copy of iterating list
            positionCounter += 1
            if positionCounter == killPosition:
                print(person)
                people.remove(person)
                positionCounter = 0 #Important! 0 != 1

solveJosephus(raw_input().split())
+1
source

, , .

:

, X = 5 N = 2. [1,2,3,4,5]. index = 1 2 . [1,3,4,5]. , - 1, 3. ( = 3), , 4, 5.

+5

, , , , ,

for person in people:
    ...
    people.remove(person)

. , people.copy() , , .

+1

All Articles