So 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
('Jane', [('Nick', []), ('Wendy', [])])
If Mary and Jane are Frank’s children, and Jon is Mary's child, while Nick and Wendy are Jane's children, then Frank is represented as
('Frank', [('Mary', [('Jon', [])]), ('Jane', [('Nick', []), ('Wendy', [])])])
Thus, how do I write a function that will return a list of members in the family in a hierarchal order? For example
get_family_members(('Mary', []))
['Mary']
get_family_members(('Jane', [('Nick', []), ('Wendy', [])]))
['Jane', 'Nick', 'Wendy']
get_family_members(('Frank', [('Mary', [('Jon', [])]), ('Jane', [('Nick', []), ('Wendy', [])])]))
['Frank', 'Mary', 'Jane', 'Jon', 'Nick', 'Wendy',]
My attempt:
def get_family_members(fam_list):
result = []
if type(fam_list) != list:
fam_list = [fam_list]
for i in range(len(fam_list)):
result.append(fam_list[i][0])
for i in range(len(fam_list)):
if fam_list[i][1] != []:
li = get_family_members(fam_list[i][1])
result += li
return result