列表迭代完整循环检测:cycle_sublist函数循环终止判断算法
如何正确检测
cycle_sublist函数的循环完成条件? 任务描述
实现函数cycle_sublist(lst, start, step),要求如下:
lst为列表start满足0 <= start < len(lst)step为每次迭代的索引增量
禁止使用:切片、导入模块、列表推导式、map/filter等内置函数。
函数逻辑:从start位置开始迭代列表,当回到或越过start位置时停止。示例如下:
cycle_sublist([1], 0, 2) -> [1] cycle_sublist([6, 5, 4, 3], 0, 2) -> [6, 4] cycle_sublist([7, 6, 5, 4, 3], 3, 1) -> [4, 3, 7, 6, 5] cycle_sublist([4, 3, 2, 5, 1, 6, 9], 2, 2) -> [2, 1, 9, 3] cycle_sublist([4, 3, 2, 5, 1, 6, 9], 5, 3) -> [6, 3, 1]
问题详情
我无法正确检测循环是否完成,尝试过两种方法均失败:
- 对比前一步和当前索引与
start的关系,但部分场景失效; - 统计步数并判断是否越过
start,同样无效。
以下是我的代码(缺失循环检测逻辑):
def cycle_sublist(lst,start,step): index = start length = len(last) cycle_complete = False res = [] while True: index = index % length if index >= length else index if ...: cycle_complete = True if cycle_complete and index >= start: break res.append(lst[index]) index += step return res
希望仅获取循环检测的算法,自行完成代码编写。
循环检测算法方案
核心思路是跟踪是否回到起始索引start,同时确保首次访问start时不终止循环,以下是可靠的实现逻辑:
- 初始化当前索引为
start,结果列表为空,标记has_started为False - 进入循环:
- 如果
has_started为True且当前索引等于start,直接终止循环 - 将当前索引对应的元素加入结果列表
- 把
has_started设为True(第一次执行后就会标记为已开始) - 计算下一个索引:
index = (index + step) % len(lst)(统一处理正负step和越界情况)
- 如果
另一种基于区间判断的思路(适合理解循环趋势):
- 当
step > 0时,每次计算下一个索引后,检查:若下一个索引经过取模后,落在[start, 当前索引]的反向区间(即绕回后超过或等于start),则标记循环完成 - 当
step < 0时,检查下一个索引(处理负数后)是否小于或等于start,且已完成至少一轮迭代
最简洁且覆盖所有场景的是第一种基于起始点重复检测的方案,能准确匹配所有示例的终止条件。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

