"""
Lecture examples on recursive functions that deal with a family tree

Author: Daisy Fan (kdf4)
Date: Apr 5, 2021
"""

from person import Person

def num_ancestors(p):
    """ Returns the number of known ancestors of p

    Precondition: p is a Person (not None)
    """
    # 1. Handle base case
    if p.parent1==None and p.parent2==None:
        return 0

    # 2. Break into two parts
    parent1s= 0
    if p.parent1 != None:
        parent1s= 1 + num_ancestors(p.parent1)
    parent2s= 0
    if p.parent2 != None:
        parent2s= 1 + num_ancestors(p.parent2)

    # 3. Combine the result
    return parent1s + parent2s


def all_ancestors(p):
    """ Returns a list of all known ancestors of p

    Each element of the returned list is a Person instance or the list is empty.

    Precondition: p is a Person (not None)
    """
    # 1. Handle base case
    if p.parent1==None and p.parent2==None:
        return []

    # 2. Break into two parts
    parent1s= []
    if p.parent1 != None:
        parent1s= [p.parent1] + all_ancestors(p.parent1)
    parent2s= []
    if p.parent2 != None:
        parent2s= [p.parent2] + all_ancestors(p.parent2)

    # 3. Combine the result
    return parent1s + parent2s


# Build the family tree shown on lecture slides
# Students: Do not worry about this block of code that builds a family tree.
#           Just look at lecture slides for the members of this family.
p01= Person('John Sr.', None, None)
p02= Person('Pamela', None, None)
p04= Person('Eva', None, None)
p05= Person('Shane', None, None)
p06= Person('Carmen', None, None)
p11= Person('John Jr.', p01, p02)
p12= Person('Jane', None, p04)
p13= Person('Portia', None, None)
p14= Person('Ellen', p05, p06)
p21= Person('John III', p11, p12)
p22= Person('Alice', p13, p14)
p31= Person('John IV', p21, p22)

# How many known ancestors does John IV have?
print('John IV has ' + str(num_ancestors(p31)) + ' known ancestors')
# How many known ancestors does Ellen have?
print('Ellen has ' + str(num_ancestors(p14)) + ' known ancestors')
# How many known ancestors does Jane have?
print('Jane has ' + str(num_ancestors(p12)) + ' known ancestors')
# How many known ancestors does Eva have?
print('Eva has ' + str(num_ancestors(p04)) + ' known ancestors')

# Who are the known ancestors of Alice?
print("\nAlice's known ancestors: ")
alice_ancestors= all_ancestors(p22)
for a in alice_ancestors:
    print(a.name)

# Who are the known ancestors of Jane?
print("\nJane's known ancestors: ")
jane_ancestors= all_ancestors(p12)
for a in jane_ancestors:
    print(a.name)

# Shane has no known all_ancestors
shane_ancestors= all_ancestors(p05)
if len(shane_ancestors)==0:
    print('\nShane has no known ancestors')
else:
    print('\nCheck your code!')
