I learn python just about one month. This is a recursive function I worte for my Pygame to find the correct way in a polygon without retreat. It's just a Pentagon here, (0,1,2,3,4) are vertices' number.
However, this code works with two global variables:
last_poses = {}
route_all = []
This means I have to initialize those two variables every time I call it. And I also try to return the all the available route lines, but it didn't work properly.
This result comes from the global variable, it's correct:
[{0: 0, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0}, {0: 0, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0}]
This result comes from return value:
[{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 0}]
My question is to return the correct value without global variables. Anyone who can help me resolve this, I really appreciate that.
legal_action = ((4,1),(0,2),(1,3),(2,4),(0,3))
def route_cal(start_pos, steps):
global last_poses,route_all
last_poses[steps] = start_pos
steps -= 1
dest_all = list(legal_action[start_pos])
if len(last_poses) >= 2:
for i in dest_all:
if i == last_poses[steps+2]:
dest_all.remove(i)
if steps > 0:
for pos in dest_all:
# route_cal(pos,steps)
return route_cal(pos,steps)
elif steps == 0:
last_poses[steps] = dest_all[0]
route_all.append(last_poses)
return route_all
# return route_all
last_poses = {}
route_all = []
# route_cal(0, 5)
# print route_all
routelines = route_cal(0,5)
print routelines