Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Given a list of (parent, child) relationships, return a sorted list of family members who have no parents or exactly one parent.
- """
- from collections import defaultdict
- def find_family_members(relations: list[tuple[str, str]]) -> list[str]:
- in_degree = defaultdict(int)
- all_members = set()
- # Populate in-degree and collect all members
- for parent, child in relations:
- in_degree[child] += 1
- all_members.add(parent)
- all_members.add(child)
- # Members that appear only as parents have in-degree 0
- # Members that never appear as children also have in-degree 0
- # So ensure to set in-degree for all members not present in in_degree
- for member in all_members:
- if member not in in_degree:
- in_degree[member] = 0
- # Collect members with in-degree 0 or 1
- result = [member for member, degree in in_degree.items() if degree <= 1]
- # Return sorted list for consistency
- return sorted(result)
- # Example Usage:
- if __name__ == "__main__":
- # Example input: list of (parent, child) relationships
- relationships = [
- ("John", "Mary"),
- ("John", "Alice"),
- ("Mary", "Bob"),
- ("Alice", "Bob"),
- ("Eve", "John"),
- ("Eve", "Mary"),
- # Introducing a cycle
- ("Bob", "Eve")
- ]
- members = find_family_members(relationships)
- print("Family members with 0 or 1 parent:")
- for member in members:
- print(member)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement