pyTony
pyMod
6,300 posts since Apr 2010
Reputation Points: 879
Solved Threads: 986
Skill Endorsements: 26
I suggest a non recursive function
from collections import deque
def getDegrees(target, base):
"Return the distance from actor base to actor target (-1 on failure)"
if target == base:
return 0
else:
enqueued = set([base])
fifo = deque(((base, 0),))
while fifo:
actor, depth = fifo.popleft()
for other in actedWith.get(actor, ()):
if other == target:
return depth + 1
elif other not in enqueued:
enqueued.add(other)
fifo.append((other, depth + 1))
return -1 # no degree
Technically, it's a breadth-first traversal, see http://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_Traversal
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11