You need to enable JavaScript to run this app. 修改Collatz猜想Python函数使其接收float时抛出ValueError
优惠活动
大模型
产品
解决方案
定价
更多

修改Collatz猜想Python函数使其接收float时抛出ValueError

Collatz函数参数校验修复方案

核心改动说明

你需要在函数入口新增严格的int类型校验,这里必须使用type(n)做类型判断,不能用isinstance(n, int):后者只会判断值是否符合int的结构,值为整数的float(如10.0)会被误判为合法,而type(n)会严格校验变量的实际类型,刚好匹配你的需求。

修复后完整代码

def Collatz(n):
    # 新增float类型拦截逻辑
    if type(n) is not int:
        raise ValueError("参数必须为正整数")
    
    collatzlist = [n]
    if n > 0:
        while n > 1:
            if n % 2 == 0:
                # 可选优化:用整数除法替换普通除法,保证生成的序列元素都是int类型
                # 不需要的话可以换回 n = n / 2
                n = n // 2
            else:
                n = n * 3 + 1
            collatzlist.append(n)
    else:
        raise ValueError("参数必须为正整数")

    return collatzlist

效果验证

  • 传入int类型的10:正常执行,返回Collatz序列[10, 5, 16, 8, 4, 2, 1](如果保留普通除法的话序列元素会是float类型)
  • 传入float类型的10.0:直接抛出ValueError,符合要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 11:36:03