0

I'm programming the josephus algorithm.

The Josephus Problem is a mathematical problem in which a circle is made, its circumference formed of n people. Starting from the person in the 0th position, each person eliminates the person to their left (the next person in the circle). The next living person then does the same, and the process is repeated until there is only one person left alive.

I used a recursive function like this :

def loopInList(L):
    if len(L)>1:
        i=0
        while i < len(L) - 1 :
            L.remove(L[i+1])
            i += 1 
        loopInList(L[i:] + L[:i])
    else:
        return L[0]
        
def josephus(n):
    L = [x for x in range(n)]
    return loopInList(L)
print(josephus(9))

The problem is that it's returning me None, yet when I print L[0] instead of returning it, I have this list [2,0] which is the good result, so my algorithm works. But it only return the value of the first function loopInList called (the one that get the fresh list as argument), and with this fresh list I don't go in the else statement so it's returning None. I want my first function called to return the value returned in the last function called in the recursive loop.

2
  • Should L>2 be L>1? Commented Mar 28, 2021 at 1:06
  • Yeah you're right, my bad. anyway still got my None problem :/ (it's edited btw) Commented Mar 28, 2021 at 1:11

1 Answer 1

0

Did you intend this (just added the return statement in the recursing block):

def loopInList(L):
    if len(L)>1:

        i=0
        while i < len(L) - 1 :
            L.remove(L[i+1])
            i += 1 
        return loopInList(L[i:] + L[:i])
    else:
        return L[0]
        
def josephus(n):
    L = [x for x in range(n)]
    return loopInList(L)
print(josephus(9))
Sign up to request clarification or add additional context in comments.

2 Comments

That's it, a simple instruction missed :( I'm discovering recursion sorry^^
We all have done it. Since this has been closed, you may not be able to mark this as the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.