[Codewars] 039: Josephus Survivor

题目

In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.

Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:

josephus_survivor(7,3) => means 7 people in a circle;
one every 3 is eliminated until one remains
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out
[1,2,4,5,7] => 6 is counted out
[1,4,5,7] => 2 is counted out
[1,4,5] => 7 is counted out
[1,4] => 5 is counted out
[4] => 1 counted out, 4 is the last element - the survivor!

The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata.

Notes and tips: using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1.

经典的约瑟夫环问题

我的答案

def josephus_survivor(n,k):
    L = list(range(1, n + 1))
    index = 0
    for _ in range(n - 1):
        index = (index + k) % len(L)
        index -= 1
        del L[index]
        if index == -1:
            index = 0
    return L[0]

其他精彩答案

def josephus_survivor(n, k):
    v = 0
    for i in range(1, n + 1): v = (v + k) % i
    return v + 1
def josephus_survivor(n, k):
    return reduce(lambda x, y: (x+k)%y, xrange(0, n+1)) + 1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • By clicking to agree to this Schedule 2, which is hereby ...
    qaz0622阅读 1,493评论 0 2
  • 这是一首具有勉怀意味的诗歌。诗说棠梨树枝繁叶茂,告诫后人勿将其砍伐毁坏掉,因为召伯曾经在这树下搭建草屋居住过、歇息...
    四夕清禾阅读 1,498评论 0 3
  • 今天又是重度雾霾, 医院里的病人很多。 为什么会有雾霾呢? 这个问题煞是蹊跷。 大师说雾霾是因为人心乱了, 我初时...
    曹润青阅读 1,053评论 20 33
  • 伊川县直中学——牛世俊 大部分人都知道体育锻炼的好处,但是能长期坚持锻炼的却没几个人,为什么?原因概括起来,可能有...
    0f565e2c2de2阅读 133评论 0 2
  • 在互联网及社交媒体将人与人之间的沟通以及信息的获取变得太过容易的今天,我总倾向于扮演观看和汲取的角色。然而我...
    小夜花阅读 632评论 0 1