In an exercise I need to simulate a sleepwalker (kind of), and one of the variables it needs to return are the amount of steps taken before the function stops. I'm trying to accomplish this by wanting to append the type of movement to a list "steps", and returning the length of that list when done. But it's not appending properly, the list is filled with 'None' and the length stays 0, why is that and how can I fix it? (I am not allowed to use for/while loops)
I'm talking about the code in the function rwsteps, though I've provided everything since it uses recursion
def rs():
"""rs chooses a random step and returns it.
note that a call to rs() requires parentheses
arguments: none at all!
"""
return choice([-1, 1])
def rwpos(start, nsteps):
""" Arguments:
start: Integer that shows the start position of the sleepwalker
nsteps: A non-negative integer of the amount of random steps from the start position
Function returns the random-walker's position
"""
#sys.setrecursionlimit(1000)
random_step = rs()
if nsteps == 0:
return start #position after nsteps
if random_step == 1:
return rwpos(start + 1, nsteps - 1)
elif random_step == -1:
return rwpos(start - 1, nsteps - 1)
def rwsteps(start, low, hi):
""" Arguments:
start: Integer representing the start position of the sleepwalker
low: Non-negative integer representing the lowest value the sleepwalker is allowed to walk
to
hi: Non-negative integer representing the highest value the sleepwalker is allowed to walk
to
So; hi >= start >= low
Function returns every step of the sleepwalker and stops if the sleepwalker goes out of
bounds (higher than hi or lower than low)
rwsteps returns the amount of steps it takes the sleepwalker to go out of bounds
"""
#time.sleep(0.1)
sys.setrecursionlimit(1000)
random_step = rs()
steps = [] #type of steps taken
if start < low or start > hi:
return len(steps) #amount of steps taken
if random_step == 1:
print("|" + "_"*(start-low) + "S" + "_"*(hi-start) + "|")
return rwsteps(start + 1, low, hi), steps.append("forwards")
if random_step == -1:
print("|" + "_"*(start-low) + "S" + "_"*(hi-start) + "|")
return rwsteps(start - 1, low, hi), steps.append("backwards")