当前位置: 首页 > news >正文

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 peoplepeople = list(range(1, n + 1))# Index to keep track of current personcurrent_index = 0while len(people) > 1:# Find the person to be removedremove_index = (current_index + 2) % len(people)# Remove the personpeople.pop(remove_index)# Update the current index for the next iterationcurrent_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 1else: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 1else: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(递归计算),数学规律更高效。

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

http://www.lryc.cn/news/180304.html

相关文章:

  • Google Earth Engine(GEE)案例——如何去除和过滤Landsat和sentinel等系列影像集合中的空影像(三种方法)
  • Leetcode 69.x的平方根
  • Node18.x基础使用总结(二)
  • LCD 的RGB接口(SYNC Mode/ SYNC-DE Mode/ DE Mode)
  • flink生成水位线记录方式--周期性水位线生成器
  • 百度资源搜索平台出现:You do not have the proper credential to access this page.怎么办?
  • 树莓派CM4开启I2C与UART串口登录同时serial0映射到ttyS0 开启多串口
  • 【租车骑绿道】python实现-附ChatGPT解析
  • 【ONE·Linux || 多线程(一)】
  • 华为智能企业上网行为管理安全解决方案(1)
  • Acwing 240. 食物链
  • c++ 容器适配器
  • 正则表达式的应用领域及基本语法解析
  • CIP或者EtherNET/IP中的PATH是什么含义?
  • 使用lombok进行bulider之后调取HashMap的自定义方法进行对象操作报空指针异常(pojo也适用)
  • 矩阵-day14
  • 上古神器:十六位应用程序 Debug 的基本使用
  • [学习笔记]ARXML - Data Format
  • Go_原子操作和锁
  • 初识Java 12-1 流
  • 【软件工程_UML—StartUML作图工具】startUML怎么画interface接口
  • 单片机之瑞萨RL78定时计数器
  • 手机号码格式校验:@Phone(自定义参数校验注解)
  • ORACLE Redo Log Buffer 重做日志缓冲区机制的设计
  • PWN Test_your_nc Write UP
  • Centos7配置firewalld防火墙规则
  • 【新版】系统架构设计师 - 未来信息综合技术
  • CAD二次开发LineSegment2d
  • Linux shell编程学习笔记5:变量命名规则、变量类型、使用变量时要注意的事项
  • 如何把word的页眉页脚改为图片