约瑟夫环问题(Josephus_problem)

递归:

def J(n,x):
   return 0 if n==1 else (J(n-1,x)+x-1) % n

循环:

def J(n,x):
    k=0
    for i in range(2,n+1):
        k=(k+x)%i
    return k+1

 

列表推倒:

def J(n,x):
    return reduce(lambda t, _: (t[(x-1) % len(t):] + t[:(x-1) % len(t)])[1:], range(n-1), range(1, n+1))

 

def J(n,x):
    li=range(1,n+1)
    while li:
        print '\t'.join('1' if i in li else '0' for i in range(1,n+1))
        li=(lambda t: li[t:]+li[:t])( (x-1)%len(li) )[1:]
J(10, 5)
#Out: #1 1 1 1 1 1 1 1 1 1 #1 1 1 1 0 1 1 1 1 1 #1 1 1 1 0 1 1 1 1 0 #1 1 1 1 0 0 1 1 1 0 #1 0 1 1 0 0 1 1 1 0 #1 0 1 1 0 0 1 1 0 0 #1 0 1 1 0 0 1 0 0 0 #0 0 1 1 0 0 1 0 0 0 #0 0 1 0 0 0 1 0 0 0 #0 0 1 0 0 0 0 0 0 0

 

 

In Mathematica :

《约瑟夫环问题(Josephus_problem)》

 

 《约瑟夫环问题(Josephus_problem)》

    原文作者:约瑟夫环问题
    原文地址: https://www.cnblogs.com/c-hy/archive/2012/09/16/2687840.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞