Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

askthedev.com Logo askthedev.com Logo
Sign InSign Up

askthedev.com

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Ubuntu
  • Python
  • JavaScript
  • Linux
  • Git
  • Windows
  • HTML
  • SQL
  • AWS
  • Docker
  • Kubernetes
Home/ Questions/Q 13221
Next
In Process

askthedev.com Latest Questions

Asked: September 26, 20242024-09-26T21:37:44+05:30 2024-09-26T21:37:44+05:30In: Python

How to Determine a Person’s Level in a Family Tree Using Python?

anonymous user

I’ve been diving into some interesting programming challenges recently, and one that got me thinking involves calculating a pedigree. So here’s the scenario: Imagine you’ve got a family tree represented as a list of tuples, where each tuple consists of a person and their parents. The goal is to determine the level of a person in the tree, which is determined by how many generations they are from the oldest known ancestor.

For example, let’s say we have the following data structure:

“`python
family = [
(‘grandparent’, None, None),
(‘parent’, ‘grandparent’, None),
(‘child’, ‘parent’, None),
(‘grandchild’, ‘child’, None)
]
“`

In this structure, ‘grandparent’ is at the top, and ‘grandchild’ is at the bottom. What I need help with is figuring out how to write a function that takes a person’s name and returns their level in the pedigree (starting from 0 for the oldest ancestor). So for ‘grandparent’, the function would return 0, for ‘parent’, it would return 1, for ‘child’, it would return 2, and for the ‘grandchild’, it would return 3.

I started sketching out some ideas, but it quickly became more complicated than I anticipated. I want to make sure that the function can handle cases where the person doesn’t exist, and maybe it should return -1 in such cases.

I’ve thought about using a dictionary to map each person to their parents, but I’m not sure how to traverse the tree recursively and count the levels accurately.

Does anyone have a straightforward solution or even a useful approach to tackle this problem? I’m all ears for any tips or code snippets you can share to help me nail this down!

  • 0
  • 0
  • 2 2 Answers
  • 0 Followers
  • 0
Share
  • Facebook

    Leave an answer
    Cancel reply

    You must login to add an answer.

    Continue with Google
    or use

    Forgot Password?

    Need An Account, Sign Up Here
    Continue with Google

    2 Answers

    • Voted
    • Oldest
    • Recent
    1. anonymous user
      2024-09-26T21:37:46+05:30Added an answer on September 26, 2024 at 9:37 pm

      To solve the problem of determining a person’s level in a family tree represented as a list of tuples, we can define a function that constructs a dictionary mapping each person to their parent. This representation allows easy traversal of the family tree to count the levels from the individual to their oldest known ancestor. Below is a code snippet that demonstrates this approach:

      def get_level(family, person):
          # Create a dictionary mapping each person to their parents
          tree = {p[0]: p[1] for p in family}
          
          # Initialize level
          level = 0
          
          # Traverse the tree upwards to count the levels
          while person in tree:
              parent = tree[person]
              if parent is None:  # Found the oldest ancestor
                  return level
              person = parent
              level += 1
          
          return -1  # Person not found in the tree
      
      # Example usage
      family = [
          ('grandparent', None),
          ('parent', 'grandparent'),
          ('child', 'parent'),
          ('grandchild', 'child')
      ]
      print(get_level(family, 'grandchild'))  # Output: 3
      print(get_level(family, 'parent'))      # Output: 1
      print(get_level(family, 'unknown'))     # Output: -1
      

        • 0
      • Reply
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp
    2. anonymous user
      2024-09-26T21:37:45+05:30Added an answer on September 26, 2024 at 9:37 pm

      def get_level(family, person):
          # Create a dictionary to map each person to their parents
          family_dict = {child: parent for child, parent, _ in family}
      
          # Start from the person and count levels
          level = 0
          current = person
          
          while current is not None:
              if current not in family_dict:
                  return -1  # Person doesn't exist
              current = family_dict[current]
              level += 1
          
          return level - 1  # Subtract one to account for the loop incrementing after the last ancestor
      
      # Example usage
      family = [
          ('grandparent', None, None),
          ('parent', 'grandparent', None),
          ('child', 'parent', None),
          ('grandchild', 'child', None)
      ]
      
      print(get_level(family, 'grandparent'))  # Output: 0
      print(get_level(family, 'parent'))       # Output: 1
      print(get_level(family, 'child'))        # Output: 2
      print(get_level(family, 'grandchild'))   # Output: 3
      print(get_level(family, 'nonexistent'))  # Output: -1
      

        • 0
      • Reply
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp

    Related Questions

    • What is a Full Stack Python Programming Course?
    • How to Create a Function for Symbolic Differentiation of Polynomial Expressions in Python?
    • How can I build a concise integer operation calculator in Python without using eval()?
    • How to Convert a Number to Binary ASCII Representation in Python?
    • How to Print the Greek Alphabet with Custom Separators in Python?

    Sidebar

    Related Questions

    • What is a Full Stack Python Programming Course?

    • How to Create a Function for Symbolic Differentiation of Polynomial Expressions in Python?

    • How can I build a concise integer operation calculator in Python without using eval()?

    • How to Convert a Number to Binary ASCII Representation in Python?

    • How to Print the Greek Alphabet with Custom Separators in Python?

    • How to Create an Interactive 3D Gaussian Distribution Plot with Adjustable Parameters in Python?

    • How can we efficiently convert Unicode escape sequences to characters in Python while handling edge cases?

    • How can I efficiently index unique dance moves from the Cha Cha Slide lyrics in Python?

    • How can you analyze chemical formulas in Python to count individual atom quantities?

    • How can I efficiently reverse a sub-list and sum the modified list in Python?

    Recent Answers

    1. anonymous user on How do games using Havok manage rollback netcode without corrupting internal state during save/load operations?
    2. anonymous user on How do games using Havok manage rollback netcode without corrupting internal state during save/load operations?
    3. anonymous user on How can I efficiently determine line of sight between points in various 3D grid geometries without surface intersection?
    4. anonymous user on How can I efficiently determine line of sight between points in various 3D grid geometries without surface intersection?
    5. anonymous user on How can I update the server about my hotbar changes in a FabricMC mod?
    • Home
    • Learn Something
    • Ask a Question
    • Answer Unanswered Questions
    • Privacy Policy
    • Terms & Conditions

    © askthedev ❤️ All Rights Reserved

    Explore

    • Ubuntu
    • Python
    • JavaScript
    • Linux
    • Git
    • Windows
    • HTML
    • SQL
    • AWS
    • Docker
    • Kubernetes

    Insert/edit link

    Enter the destination URL

    Or link to existing content

      No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.