python - What is going wrong inside of my loop? -


i've been trying program josephus problem , reason working in situations, i'm unsure why. tl;dr of how works this:

you have x group of people in circle. every nth person going killed until 1 final person remains. example have 10[aka: x] people , decide kill every 3rd [aka: nth] person this:

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

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

3rd round: (1), 4, 5, (8), 10

4th round: 4, (5), 10

5th round: 4, (10)

and left person #4 lone survivor.

my program fine. however, when enter x 55 , n 17 incorrect answer of person 27 when should person 40. can tell me loop messes up?

source code:

def solvejosephus(specifics):     people = [int(x) 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         person in people:             positioncounter += 1             if positioncounter == killposition:                 print(person)                 people.remove(person)                 positioncounter = 1  solvejosephus(raw_input().split()) 

in addition other answers (telling make copy of list when iterating), problem code reset positioncounter 1 in line: positioncounter = 1. should reset 0. here complete working code (works far):

def solvejosephus(specifics):     people = [int(x) 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         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()) 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -