对于一些简单的递归代码,在Python 2.7中键入错误

时间:2015-01-07 07:24:58

标签: python-2.7 recursion types

我在Python 2.7中遇到了一些带有递归代码的类型错误。下面的代码基本上是一个riemann积分,您可以在曲线下方添加矩形区域。当'step'为0.25或更大时,它可以正常工作,但当它小于0.25时会发生类型错误。为什么会发生这种情况,我该如何解决?

最后一行代码出现以下错误:

  File "/home/i/PycharmProjects/6.00.1x/prob3/radiationExposure.py", line 25, in radiationExposure
return f(stop - step) * step + radiationExposure(start, (stop - step), step)    

TypeError:+的不支持的操作数类型:'float'和'NoneType'

我的代码如下:

def f(x):
    import math
    return 10*math.e**(math.log(0.5)/5.27 * x)

def radiationExposure(start, stop, step):

'''
    Computes and returns the amount of radiation exposed
    to between the start and stop times. Calls the
    function f to obtain the value of the function at any point.

    start: integer, the time at which exposure begins
    stop: integer, the time at which exposure ends
    step: float, the width of each rectangle. You can assume that
      the step size will always partition the space evenly.

    returns: float, the amount of radiation exposed to
      between start and stop times.
    '''

    if stop - step == start:
        return f(stop - step) * step
    elif stop - step > start:
        return f(stop - step) * step + radiationExposure(start, (stop - step), step)

注意那些有道德的人:这是为了满足我自己的好奇心。 edx.org上的归档麻省理工学院课程没有成绩,此问题不需要递归代码。

1 个答案:

答案 0 :(得分:1)

问题中提供的radiationExposure函数会在None时返回stop-step < start,因为if条件均未得到满足。

if stop - step == start:
    return f(stop - step) * step
elif stop - step > start:
    return f(stop - step) * step + radiationExposure(start, (stop - step), step)
# If the execution reaches this point and the function ends, it will return None

如果您希望算术能够准确地给出stop-step==start,那么请不要使用浮点变量,因为它们是近似值。

如果您改为:

if stop - step <= start:
    return f(stop - step) * step
else:
    return f(stop - step) * step + radiationExposure(start, stop - step, step)

至少可以确保函数返回一个数而不是None