Python 试图写一个递归的;“随机游走”;功能 def RW步骤(启动、低、高): n=0 虽然低
我相信这就是你想要的Python 试图写一个递归的;“随机游走”;功能 def RW步骤(启动、低、高): n=0 虽然低,python,recursion,Python,Recursion,我相信这就是你想要的 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, h
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
def随机步数(计数、开始、低、高):
如果低def步数(开始、低、高、计数=0):
如果低<启动<高:
返回RandomWalkSteps(开始+随机。选择(-1,1)),低,高,计数+1)
返回计数
打印步骤(10、5、15)
def随机行走步骤(开始、低、高):
如果低<启动<高:
返回1+RandomWalkSteps(随机选择(-1,1)),低,高)
返回0
python是否进行尾部调用消除?如果是这样,这比falsetru的更有效solution@ikegamiPython不优化尾部调用。
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
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
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(start, low, hi):
if low < start < hi:
return 1 + RandomWalkSteps(random.choice((-1,1)), low, hi)
return 0