在python递归函数中,我需要编写一个代码来打印字母''作为一个沉睡的人的追踪步骤。我用两个函数编写了代码.....
import random
def rs():
""" rs chooses a random step and returns it
note that a call to rs() requires parentheses
inputs: none at all!
"""
return random.choice([-1,1])
def rwsteps( start, low, hi ) :
'''
inputs :start --> Starting position of sleepwalker
low --> nonnegative smallest value allowed
hi --> highest value allowed'''
if start <= low or start >= hi :
return
else :
print '|' + ' ' * (start - low) + 'S' + ' ' * (hi - start) + '|'
return rwsteps( start + rs() , low, hi )
工作正常,现在我需要添加另一个功能来打印自己打印步骤后的步数。我不想在功能本身内计算。请提前告诉你。
EDIT 谢谢你们 我有一个想法,它的工作,所以这里是我的新代码
import random
def rs():
""" rs chooses a random step and returns it
note that a call to rs() requires parentheses
inputs: none at all!
"""
return random.choice([-1,1])
c = 0
def counter():
global c
c += 1
return c
def rwsteps( start, low, hi ) :
'''
inputs :start --> Starting position of sleepwalker
low --> nonnegative smallest value allowed
hi --> highest value allowed'''
if start <= low or start >= hi :
print c - 1
return
else :
print '|' + ' ' * (start - low) + 'S' + ' ' * (hi - start) + '|'
counter()
return rwsteps( start + rs() , low, hi )
rwsteps( 10, 5, 15 )
&#13;
答案 0 :(得分:1)
您可以使用装饰器函数来包装rwsteps
函数并计算调用次数:
用于计算包装函数调用的装饰器函数将:
from random import getrandbits
import sys
sys.setrecursionlimit(10**6)
def counted(fn):
def wrapper(*args, **kwargs):
wrapper.count += 1
return fn(*args, **kwargs)
wrapper.count = 0
return wrapper
def rs():
return -1 if getrandbits(1) else 1
@counted
def rwsteps(pos, low, hi) :
if pos > low and pos < hi:
print "{0: <{l}}S{0: >{r}}".format('|', l=pos-low, r=hi-pos)
return rwsteps(pos+rs(), low, hi)
rwsteps(5, 0, 10)
rwsteps.count
| S |
| S |
| S |
| S |
|S |
| S |
| S |
| S |
|S |
| S |
|S |
| S |
| S |
| S |
|S |
| S |
|S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
|S |
28
使用@
装饰符符号与:
rwsteps = counted(rwsteps)
rwsteps(5, 0, 10)
rwsteps.count
哪个也有效:
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
| S |
|S |
14