python经典百题之围圈报数

题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

程序分析

  1. 思路1:模拟游戏过程

    • 使用一个循环队列模拟游戏过程,每次循环移除报数为3的人,直到剩下最后一个人为止。
  2. 思路2:数学规律

    • 利用数学规律推导出最后留下的人的编号,而不需要实际模拟游戏过程。
  3. 思路3:递归计算

    • 使用递归的方式来求解,递归函数表示从n个人中找出最后留下的人的编号。

现在让我们用这三种思路实现Python代码。

方法1:模拟游戏过程

解题思路

  • 使用一个循环队列模拟游戏过程,每次循环移除报数为3的人,直到剩下最后一个人为止。

代码实现

def last_person_using_simulation(n):
    # Create a list of n people
    people = list(range(1, n + 1))
    
    # Index to keep track of current person
    current_index = 0
    
    while len(people) > 1:
        # Find the person to be removed
        remove_index = (current_index + 2) % len(people)
        
        # Remove the person
        people.pop(remove_index)
        
        # Update the current index for the next iteration
        current_index = remove_index % len(people)
    
    return people[0]

# Example usage
n = 10  # Number of people
result = last_person_using_simulation(n)
print(f"The last person remaining is originally numbered {result}.")

优缺点

  • 优点:
    • 直观易懂,容易实现。
  • 缺点:
    • 需要维护一个列表,空间复杂度较高。

方法2:数学规律

解题思路

  • 利用数学规律推导出最后留下的人的编号,而不需要实际模拟游戏过程。

代码实现

def last_person_using_math(n):
    if n == 1:
        return 1
    else:
        return (last_person_using_math(n - 1) + 3 - 1) % n + 1

# Example usage
n = 10  # Number of people
result = last_person_using_math(n)
print(f"The last person remaining is originally numbered {result}.")

优缺点

  • 优点:
    • 时间复杂度为O(n),空间复杂度为O(1)。
  • 缺点:
    • 可能在大规模n下会导致递归栈溢出。

方法3:递归计算

解题思路

  • 使用递归的方式来求解,递归函数表示从n个人中找出最后留下的人的编号。

代码实现

def last_person_using_recursion(n):
    if n == 1:
        return 1
    else:
        return (last_person_using_recursion(n - 1) + 3 - 1) % n + 1

# Example usage
n = 10  # Number of people
result = last_person_using_recursion(n)
print(f"The last person remaining is originally numbered {result}.")

优缺点

  • 优点:
    • 直观易懂,容易实现。
    • 时间复杂度为O(n),空间复杂度为O(n)。
  • 缺点:
    • 可能在大规模n下会导致递归栈溢出。

总结和推荐

  • 推荐方法2(数学规律)
    • 具有较好的时间复杂度和空间复杂度。
    • 避免了递归可能产生的栈溢出问题。
    • 相比方法1(模拟游戏过程)和方法3(递归计算),数学规律更高效。

综上所述,推荐使用数学规律的方法来解决该问题。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忧伤的玩不起

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值