0

我看到了一些关于计算递归迭代次数的帖子,但我无法遵循或它们不适用。对不起,如果它是多余的!感谢您的帮助!我正在尝试使用递归函数来纠正随机游走情况的函数并保持对步数的计数。它还有一个视觉组件,它告诉我实际功能似乎正在工作,但不是计数部分。

def rwSteps (start, low, hi ):
    """ returns the number of steps the sleepwalker took in order to finally reach the `lower or upper bound
    input: an integer start (starting position of the sleepwalker), an integer low (nonnegative, the smallest value our sleepwalker can wander to), and an integer hi (the highest value the sleepwalker can wander to)
    """
    count=0
    newcount = count +1
    ' '*start + '~'
    print (' '*start + '~')
    if low < start and start < hi:
        newstart = start + rs()
        newcount = count + 1
        return rwSteps(newstart, low, hi)
        return newcount



    elif start == low:
        finalcount = newcount +1
        return finalcount

    elif start == hi:
        finalcount = newcount +1
        return finalcount
4

1 回答 1

1

只需让函数返回它及其后代所采取的步数:

def rwSteps (where, low, hi):
    print("{}~".format(' ' * where))

    if low < where < hi:
        return 1 + rwSteps(where + rs(), low, hi)
    else:
        return 0

然而,这是一个不好的递归使用——它很慢并且很可能耗尽堆栈空间并且可以很容易地被迭代重写:

from random import randint

def rs():
    return randint(-1, 1)

def rw_steps (where, low, hi ):
    """
    Returns the number of steps the sleepwalker took
    before hitting the lower or upper bound

    Input:
        where: int    starting location of the sleepwalker
        low: int      >=0, the lower boundary
        hi: int       >low, the upper boundary
    """
    steps = 0
    while low < where < hi:
        print("{}~".format(' ' * where))
        steps += 1
        where += rs()

    print("Went out of bounds after {} steps".format(steps))
    return steps
于 2014-04-22T01:28:32.233 回答