0

Let us use tuples and lists to represent a family tree. Each person is represented as a tuple. The first element of the tuple is this person’s name. The second element of the tuple is a list that contains this person’s children. Each child is represented as a tuple itself. If a person has no child, the list of his/her children is empty. For example, if Mary has no child, she is represented as ('Mary', []). If Jane has two children named Nick and Wendy, and neither Nick nor Wendy has any child, then Jane is represented as ('Jane', [('Nick', []), ('Wendy', [])]). If Mary and Jane are Frank’s children, and Frank doesn’t have any other child, then Frank is represented as ('Frank', [('Mary', []), ('Jane', [('Nick', []), ('Wendy', [])])]). The following picture shows their relationship:

relationship

Define a function called get_family_members() that takes in the representation of a person called head, who represents the head of a family tree. The head may have several children, grandchildren, great-grandchildren, etc. The function returns all the members of this person’s family (including himself/herself) in a list. The members should be ordered by generation. In other words, a person of the n-th generation should always appear after a person of the (n-1)-th generation. Also, people of the same generation should be ordered based on their sequence in the original list. For example, if Nick and Wendy are of the same generation, and Nick appears before Wendy in the original list, then Nick should appear before Wendy in the returned list.

Here's what I have done:

def get_family_members(head):
    # modify the code below
    new_dict = {}
    return_list = []
    new_list = head
    #append first ele in
    return_list.append(new_list[0])
    new_dict[new_list[0]] = new_list[1]
    # new_list = new_list[1]
    key = new_list[0]
    print(new_dict[key])
    end = False
    j = 0
    if new_dict[key] != []:
        while end == False:
            i = 0
            for tuple1 in new_dict[key]:
                if tuple1[i] not in return_list:
                    return_list.append(tuple1[i])
                    new_dict[tuple1[i]] = tuple1[i+1]
                    print("element",tuple1[i])
                    print("new list",new_dict[tuple1[i]])
                    print("return list",return_list)
                    if tuple1[i+1] != []:
                        key = tuple1[i]


                else:
                    end = True
                    return return_list
                print("key",key)

    return [key]

But it seems to be wrong when i am using this test case:

print("Test Case #1:")
print()

family_head = ('Mary', [])
result_list = get_family_members(family_head)
print("Expected: ['Mary']")
print("Actual  : " + str(result_list))
print()
print("Expected type of returned value: <class 'list'>")
print("Actual type of returned value  : " + str(type(result_list)))
print()
print("====================")
print()

# Test Case 2:
print("Test Case #2:")
print()

family_head = ('Jane', [('Nick', []), ('Wendy', [])])
result_list = get_family_members(family_head)
print("Expected: ['Jane', 'Nick', 'Wendy']")
print("Actual  : " + str(result_list))
print()
print("====================")
print()

# Test Case 3:
print("Test Case #3:")
print()

family_head = ('Frank', [('Mary', []), ('Jane', [('Nick', [])])])
result_list = get_family_members(family_head)
print("Expected: ['Frank', 'Mary', 'Jane', 'Nick']")
print("Actual  : " + str(result_list))
print()
print("====================")
print()

# Test Case 4:
print("Test Case #4:")
print()

family_head = ('Alan', [('Bob', [('Chris', [])]), ('Eric', [])])
result_list = get_family_members(family_head)
print("Expected: ['Alan', 'Bob', 'Eric', 'Chris']")
print("Actual  : " + str(result_list))
print()
print("====================")
print()

# Test Case 5:
print("Test Case #5:")
print()

family_head = ('Alan', [('Bob', [('Chris', []), ('Debbie', [('Cindy', [])])]), ('Eric', [('Dan', []), ('Fanny', [('George', [])])]), ('Hannah', [])])
result_list = get_family_members(family_head)
print("Expected: ['Alan', 'Bob', 'Eric', 'Hannah', 'Chris', 'Debbie', 'Dan', 'Fanny', 'Cindy', 'George']")
print("Actual  : " + str(result_list))
print()
print("====================")
print()

RMPR
  • 3,368
  • 4
  • 19
  • 31
qiqi lim
  • 9
  • 1

1 Answers1

0

Consider the following tree

                    Root
    1           2           3           4
11  12  13   21   22                41      42

which could written down as

                    (Root,[
    (1,[(11,[]),12,13]),  (2,[21,22]), (3,[]), (4,[41,42])
])

Output should be

[Root, 1 ,2, 3, 4, 11, 12, 13, 21, 22]

(notice that for all leaves (but 11) I have not written a (12,[]) tuple but directly the primitive type 12

Now this kind of traversal is call bfs.

Since we have a tree which does not have cycles, bfs can be furtherly simplified.

  • Still keep the idea of delaying the exploration of current "children" to the back of the stack
  • Regarding the tuple "11" stuff, stack += children is not modified if children==[] so this is still ok
def get_family_members(family):
    (root, children) = family
    L = [root]
    stack = children

    while len(stack):
        node = stack.pop(0)
        #if we pushed a leaf
        if type(node) is not tuple:
            L += [node]
        else:
            #add children to the __back__ of the stack
            (child, children) = node
            L += [child]
            stack += children
    return L
fam = (0,[
    (1,[(11,[]),12,13]),  (2,[21,22]), (3,[]), (4,[])
])
print(get_family_members(fam))
#[0, 1, 2, 3, 4, 11, 12, 13, 21, 22]
grodzi
  • 5,633
  • 1
  • 15
  • 15