将计数保持在递归函数中

时间:2014-04-22 00:50:47

标签: python function recursion count random-walk

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

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

1 个答案:

答案 0 :(得分: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