Advertisement
hoangreal

Find family members who have no parents or exactly one parent.

Oct 21st, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. """
  2. Given a list of (parent, child) relationships, return a sorted list of family members who have no parents or exactly one parent.
  3. """
  4. from collections import defaultdict
  5.  
  6. def find_family_members(relations: list[tuple[str, str]]) -> list[str]:
  7.     in_degree = defaultdict(int)
  8.     all_members = set()
  9.    
  10.     # Populate in-degree and collect all members
  11.     for parent, child in relations:
  12.         in_degree[child] += 1
  13.         all_members.add(parent)
  14.         all_members.add(child)
  15.    
  16.     # Members that appear only as parents have in-degree 0
  17.     # Members that never appear as children also have in-degree 0
  18.     # So ensure to set in-degree for all members not present in in_degree
  19.     for member in all_members:
  20.         if member not in in_degree:
  21.             in_degree[member] = 0
  22.    
  23.     # Collect members with in-degree 0 or 1
  24.     result = [member for member, degree in in_degree.items() if degree <= 1]
  25.    
  26.     # Return sorted list for consistency
  27.     return sorted(result)
  28.  
  29. # Example Usage:
  30. if __name__ == "__main__":
  31.     # Example input: list of (parent, child) relationships
  32.     relationships = [
  33.         ("John", "Mary"),
  34.         ("John", "Alice"),
  35.         ("Mary", "Bob"),
  36.         ("Alice", "Bob"),
  37.         ("Eve", "John"),
  38.         ("Eve", "Mary"),
  39.         # Introducing a cycle
  40.         ("Bob", "Eve")
  41.     ]
  42.    
  43.     members = find_family_members(relationships)
  44.     print("Family members with 0 or 1 parent:")
  45.     for member in members:
  46.         print(member)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement