As trincot said : set intersection is the best way to do that.
If you want to use a graph, you could represents each person with a node and the friendship as edges connecting between the person and their friends.
To catch the mutual friends between X and Y , you could consider the outdegree of X and Y nodes, afterwards the intersection.
The full code will be:
class FriendshipGraph:
def __init__(self):
self.graph = defaultdict(set)
def add_friendship(self, person1, person2):
self.graph[person1].add(person2)
self.graph[person2].add(person1)
def get_mutual_friends(self, *people):
if not people:
return set()
mutual_friends = self.graph[people[0]].copy()
for person in people[1:]:
if person not in self.graph:
return set()
mutual_friends &= self.graph[person]
mutual_friends -= set(people)
return mutual_friends
graph = FriendshipGraph()
Test the code with those examples:
graph = FriendshipGraph()
graph.add_friendship("Ahmed", "Mohammed")
graph.add_friendship("Ahmed", "Khaled")
graph.add_friendship("Ahmed", "Sara")
graph.add_friendship("Mohammed", "Khaled")
graph.add_friendship("Mohammed", "Fatima")
graph.add_friendship("Sara", "Fatima")
graph.add_friendship("Khaled", "Sara")
graph.add_friendship("Khaled", "Nour")
graph.add_friendship("Sara", "Nour")
print("Mutual friends between Ahmed and Mohammed:", graph.get_mutual_friends("Ahmed", "Mohammed"))
print("Mutual friends between Ahmed and Fatima:", graph.get_mutual_friends("Ahmed", "Fatima"))
print("Mutual friends between 3 people:", graph.get_mutual_friends("Ahmed", "Mohammed", "Sara"))
print("Mutual friends between 4 people:", graph.get_mutual_friends("Ahmed", "Mohammed", "Sara", "Fatima"))
print("Mutual friends between 5 people:", graph.get_mutual_friends("Ahmed", "Mohammed", "Sara", "Khaled", "Nour"))