Family Tree

From the site:

You have a list of family relationships between father and son. Every element on this list has two elements. The first is the father’s name, the second is a son’s name. All names in the family are unique. Check if the family tree is correct. There are no strangers in the family tree. All connections in the family are natural.

Input: list of lists. Every element has two strings. List has at least one element

Output: bool. Is family tree correct

I’ve had some difficulty with this…and I realized I am probably severely overcomplicating this…

def is_family(tree):
    fam = {}
    for i in range(len(tree)):
        if tree[i][0] not in fam.keys():
            fam.update({tree[i][0]: []})
        if tree[i][0] in fam.keys():
            children = fam.get(tree[i][0])
            fam[tree[i][0]] = children

    source =tree[0][0]

    fathers = [name for name in fam.keys()]
    for name in fathers:
        # father for self?
        if name in fam[name]:
            return False
        if len(fathers) > 1:
            for i in range(len(fathers)):
                # parse the children
                for c in range(len(fam[fathers[i]])):
                    # stranger
                    if fam[fathers[i]][c] not in fam[source]:
                        return False
                    if fam[fathers[i]][c] in fam.keys():
                        # father to brother
                        if fam[fam[fathers[i]][c]][0] in fam[fathers[i]]:
                            return False
                        # Father for Father
                        if fathers[i] in fam[fam[fathers[i]][c]]:
                            return False

    return True

So my first thought was to make a dictionary to hold  {father: children}, but accessing that got really confusing and honestly even after a run trying it…i cant get it right. It fails on this assert:

    assert is_family([
        ['Logan', 'Mike'],
        ['Logan', 'Jack'],
        ['Mike', 'Alexander']
    ]) == True, 'Grandfather'

I;ve got a fairly easy work day tomorrow so I think I will walk through it from scratch…maybe even ditch the dictionary concept all together….anyway…working on learning new stuff and growing. Just wanted to document it.

Write a Comment