2021年3月27日星期六

Recursive function returning None in Python for josephus algorithm

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)>2:          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.

https://stackoverflow.com/questions/66837559/recursive-function-returning-none-in-python-for-josephus-algorithm March 28, 2021 at 09:02AM

没有评论:

发表评论