每日一题 约瑟夫问题的多种解法 (第二次考试第二题)

方法一:直接pop,符合条件时(计数器=m)不管,反之加到列表最后

def ysf(n, m):
    # 特殊情况 m=1
    if m == 1:
        return n
    # 其他情况
    list1 = list(range(1, n + 1))
    # print(list1)
    index = 0
    while list1:
        index += 1
        temp = list1.pop(0)
        # print(temp)
        if index == m:
            index = 0
            continue
        list1.append(temp)
        if len(list1) == 1:
            return list1[0]
            break


# print(ysf(3,1))
# print(ysf(5,2))

方法二:老师课上方法,所有操作均在原数列中进行

def ysf4(n, m):
    index, num, counter = 0, 0, 0
    persons = [True] * n
    # print(persons)
    while counter < n - 1:
        if persons[index]:
            num += 1
            if num == m:
                persons[index] = False
                counter += 1
                num = 0
        index += 1
        index %= n
    return persons.index(True) + 1


# print(ysf4(n,m))

方法三 单循环链表,复习数据结构而写

class Node():
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


def createLink(n):
    if n < 0:
        return False
    if n == 1:
        return Node(1)
    else:
        root = Node(1)
        p = root
        for i in range(2, n + 1):
            p.next = Node(i)
            p = p.next
        p.next = root
        return root


def showLink(root):
    p = root
    while 1:
        print(p.value)
        p = p.next
        if p == None or p == root:
            break


def ysf_link(n, m):
    if m == 1:
        print('survive:', n)
        return
    root = createLink(n)
    p = root
    while 1:
        for i in range(m - 2):
            p = p.next
        print('kill:', p.next.value)
        p.next = p.next.next
        p = p.next
        if p.next == p:
            break
    print('survive:', p.value)

方法四:递归方法(稍微难理解一些)

递归方法思路

def ysf2(n, k, count):
    if count == 1:
        return (n + k - 1) % n
    else:
        return (ysf2(n - 1, k, count - 1) + k) % n


# print(ysf2(10,4,10))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值