You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

折叠次数计算Python函数异常:为何结果远超预期?

问题分析与修复

你的代码出现无限循环、返回极大值的核心原因是使用了浮点数除法/,导致边长永远无法真正变为0——正数不断除以2只会无限趋近于0,但始终大于0,while width > 0 and height > 0的条件会永远成立,计数器counter会无限累加。

具体错误点

  1. 浮点数除法的问题:folding函数里的x / 2返回浮点数(比如1/2得到0.5,0.5/2得到0.25,以此类推),永远不会等于0,循环无法终止。
  2. 冗余的max判断:两次调用max(width, height)完全没必要,直接比较width和height的大小即可。

修复后的代码

def count_folds(width: int, height: int) -> int:
    counter = 0
    while width > 0 and height > 0:
        if width >= height:
            width = width // 2  # 使用整数除法,直接得到整数结果
        else:
            height = height // 2
        counter += 1
    return counter

# 测试示例
print("count_folds: ", count_folds(2, 1))  # 输出:2
print("count_folds: ", count_folds(15, 7)) # 输出:4

修复说明

  • 用整数除法//替代浮点数除法/,这样每次对折后边长会直接取整,当边长为1时,1//2会得到0,触发循环终止条件。
  • 简化了判断逻辑,直接比较width和height的大小,避免重复计算max值,提升代码效率。

内容的提问来源于stack exchange,提问作者Mimo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:55:25