【问题标题】:Error in python: unsupported operand type(s) for *: 'int' and 'NoneType'python中的错误:*:'int'和'NoneType'不支持的操作数类型
【发布时间】:2015-04-19 01:21:10
【问题描述】:

我正在提供我的输入文件:

2 1  

我已经编写了一个代码来查找概率(特定于我的工作):

def fact(x):
    f=1
    if x > 0:
        for i in range(1,x + 1):
            f = f*i
        return f


def allele(s):
    n,k=[int(i) for i in s.split()]
    summ=0
    for i in range(n,((2**k)+1)):
            if i < (2**k +1):
                probability = (fact(2**k)/(fact(i)*fact((2**k)-i)))*(0.25**i)*(0.75**((2**k)-i))
                summ=summ+probability
    print summ

allele(open('D:\python\input.txt', 'r').read())  

我在计算概率的那一行出现错误:

unsupported operand type(s) for *: 'int' and 'NoneType' 

我不知道怎么解决。

【问题讨论】:

  • 至少,正确缩进你的代码。我们也不想坐在那里数线。此外,您的行号可能与我们的不同。发布实际行比发布行号更好。
  • 您是否使用一系列输入测试了功能等位基因?如果 allele() 通常失败,请不要向我们展示其余代码和输入数据。如果您的问题在于读取输入文件,请缩小范围。 (提示:当您新定义一个变量并且不确定该变量是否具有正确的值时,请输入大量 print() 语句。)

标签: python


【解决方案1】:

你的 fact 函数返回 None 为 0 而不是 1 因为你缩进了 return f 多一级。

def fact(x):
    f = 1
    if x > 0:
        for i in range(1, x + 1):
            f *= i
    return f

真的,您应该只使用math.factorial

from math import factorial as fact

【讨论】:

    猜你喜欢
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多