尝试编写递归"random walk"函数


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"语句,以便它在每个递归实例中正确地增加。如果我遗漏了任何重要的信息,请随时向我大喊大叫。

def RandomWalkSteps(start, low, hi):
    if low < start < hi:
        return 1 + RandomWalkSteps(random.choice((-1,1)), low, hi)
    return 0
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)

我相信这就是你要找的

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)

最新更新