I need to submit a project to prove my programming skills and it is about finding the path and the bacon number. I have coded everything and it runs (but extremely slow). Any names with a Bacon number of 2 will run within 5 minutes, but anything greater than a score of 2 takes forever.
I used BFS to perform the search:
def find_degrees_of_separation(actor_movies, movies_actors, actor1, actor2):
'''
Parameters
movie_actors: Dictionary (Keys are the movie name, and values are all the actors acting in that movie)
actor_movies: Dictionary (Keys are the actor name, and values are all the movies the actor acted in )
actor1: str (Name of actor 1)
actor2: str (Name of actor 2)
Output
actor_collaborations: Dictionary (Keys are the names of an actor, values are all other actors who have acted together in the same movie)
'''
visited_person = set() # queue
q = [(actor1, [actor1])]
while q:
cur_actor, cur_path = q.pop(0)
visited_person.add(cur_actor)
if cur_actor == actor2:
print(cur_path)
return (len(cur_path)-1)
for movie in actor_movies[cur_actor]:
for actor in movies_actors[movie]:
if actor not in visited_person:
new_path = cur_path.copy()
new_path.append(actor)
q.append((actor, new_path))
return -1
Since it ran too slow, I also did floyd-warshall, where I transformed everything into a pair, but I didn't code it because I think floyd-warshall is O(n^3). I also created another dictionary called actor_actors, where Keys are the actor name, and values are all the actors that have acted in that movie with him/her. Nonetheless, it still runs slow.
Are there any suggestions on how I can make it faster? I am not allowed to use any libraries (except copy) and this made it hard for me since I have been doing more data science stuff and not data structure stuff for the past few years. Thank you in advance.