in Uncategorized

Family Tree solved…

I sat down this morning and took another look at the What is wrong with this family quest…and it really racked my brain. But…I got it finally. Here is the code:

def is_family(tree):
    source = tree[0][0]
    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
    # build a list of all children and fathers
    children = []
    fathers = [n for n in fam.keys()]
    for father in fathers:
        for i in range(len(fam.get(father))):
        # find the source
        if father not in children:
                source = father
        if father in fam[father]:
            return False  # cannot be your own father!
        for i in range(len(fam[father])):
            if fam[father][i] in fathers:
                if fam[fam[father][i]][0] == father:
                    return False  # you cannot be your fathers father.

        if father != source:
            if father in fam[source]:
                for i in range(len(fam[father])):
                    if fam[father][i] in fam[source]:
                        return False  # cannot be a father to your brother
        if father not in children and father != source:
            return False  # No strangers in the family...
    return True

Write a Comment