0

I need to model a four generational family tree starting with a couple. After that if I input a name of a person and a relation like 'brother' or 'sister' or 'parent' my code should output the person's brothers or sisters or parents. I have a fair bit of knowledge of python and self taught in DSA. I think I should model the data as a dictionary and code for a tree DS with two root nodes(i.e, the first couple). But I am not sure how to start. I just need to know how to start modelling the family tree and the direction of how to proceed to code. Thank you in advance!

Lax_Sam
  • 1,099
  • 2
  • 14
  • 32

1 Answers1

5

There's plenty of ways to skin a cat, but I'd suggest to create:

  1. A Person class which holds relevant data about the individual (gender) and direct relationship data (parents, spouse, children).
  2. A dictionary mapping names to Person elements.

That should allow you to answer all of the necessary questions, and it's flexible enough to handle all kinds of family trees (including non-tree-shaped ones).

Henning Koehler
  • 2,456
  • 1
  • 16
  • 20
  • After creating the class how can I store the data in a dictionary? I mean how to map the names to class elements? – Lax_Sam Nov 15 '18 at 03:28
  • Not sure I understand the question - `familyTree['Hans'] = Person(...)` will add the mapping of the name `'Hans'` to `Person(...)` to the dictionary `familyTree`. https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries – Henning Koehler Nov 16 '18 at 02:14
  • It is related to your answer but not exactly the same. I wanted to know whether I can create a nested dictionary and how to print the contents. For eg: {'Hans': {'name': 'Lucy', 'relation': 'wife''}}. So Person class takes in two arguments name and relation and I need to print it out. – Lax_Sam Nov 16 '18 at 09:45
  • 1
    Create methods `__init__` (constructor) and `__repr__` (string representation) for this, see https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr. – Henning Koehler Nov 17 '18 at 03:20