试图写一个递归的“随机漫步”功能

时间:2013-06-07 05:58:20

标签: python recursion

def rwSteps(start, low, hi):
    n=0
    while low <= start <= hi:
        print (start-low-1)*" " + "#" + (hi-start)*" ", n
        start+=random.choice((-1,1))
        n+=1
    return "%d steps" % (n-1)


print rwSteps(10, 5, 15)

上面的函数是我需要以递归方式重写的函数。该函数采用起始点整数,低点和高点。从起始点开始,函数应从起始点随机执行+1或-1,直到达到上限或下限。这是我到目前为止所拥有的。

def RandomWalkSteps(start, low, hi):

    count = 0
    count = count + 1 

    if(low <= start <= hi):
        count = count + 1 
        start+=random.choice((-1,1))
        newStart = start
        RandomWalkSteps(newStart, low, hi)
        return count 

我觉得我非常接近,但是我遇到了把“count”语句放在哪里以使它在每个递归实例中正确递增的麻烦。如果我遗漏任何重要的信息,任何帮助都会受到赞赏并随时向我大喊。

3 个答案:

答案 0 :(得分:2)

def RandomWalkSteps(start, low, hi):
    if low < start < hi:
        return 1 + RandomWalkSteps(random.choice((-1,1)), low, hi)
    return 0

答案 1 :(得分:1)

def RandomWalkSteps(start, low, hi, count=0):
    if low < start < hi:
        return RandomWalkSteps(start+random.choice((-1,1)), low, hi, count+1)
    return count

print RandomWalkSteps(10, 5, 15)

答案 2 :(得分:0)

我相信这就是你要找的东西

def RandomWalkSteps(count, start, low, hi):
    if low <= start <= hi:
        start+=random.choice((-1,1))
        newStart = start
        return RandomWalkSteps(count+1, newStart, low, hi)
    else:
        return count

致电RandomWalkSteps(0, x, y, z)而非RandomWalkStep(x, y, z)

相关问题