3

I am looking for the Josephus_problem ,but the result is not my Expected. Why?

def J(n,x):
    li=range(1,n+1)
    k=0
    res=[]
    while len(li)>1:
        k= (x+k-1) % len(li)
        li.pop(k)
        res.append(li)
        #print li
    return res

print J(5,3)

Expected Output:

[1, 2, 4, 5]

[2, 4, 5]

[2, 4]

[4]

Actual Output:

[[4], [4], [4], [4]]

1 Answer 1

5

You need to append copy of list here:

res.append(li[:]) # <-- not res.append(li) !!!

The actual reason of what's going on it that list is mutable data structure in Python. Look at this snippet

>>> l = [1,2,3]
>>> p = [l,l,l]    
>>> p
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> l.pop()
3
>>> p
[[1, 2], [1, 2], [1, 2]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.