A group of students need to line up for the procession of an event. We only have the information about every pair of students who are next to each other. We use a list of tuples to represent this line-up information: Each element of the list is a tuple that contains the name of a student (call him/her A) and the name of the student behind A.
For example, ("Alice", "Bob") means Bob is behind Alice. The list [("Alice", "Bob"), ("Bob", "Chris")] means Bob is behind Alice and Chris behind Bob.
For the student who's at the very end of the line-up, we use an empty string to indicate that there's nobody behind this student. E.g., ("Darren", "") means there's nobody behind Darren, i.e., Darren is at the end of the line-up.
Given a list of tuples that contains the line-up information of every pair of students who are next to each other, implement a function that returns the students in a list based on their order in the line-up.
I could only manage to get the first and the last with the code below, but I can't get the whole group in.
def get_lineup(a_list):
lst_of_names = []
output_lst = []
if len(a_list) == 0:
return []
for i in range(len(a_list)):
for j in range(len(a_list[i])):
lst_of_names.append(a_list[i][j])
for k in range(len(lst_of_names)):
if lst_of_names.count(lst_of_names[k]) == 1 and lst_of_names[k] != "":
output_lst.append(lst_of_names[k])
for i in range(len(a_list)):
if a_list[i][1] == "":
output_lst.append(a_list[i][0])
return output_lst
Example 1:
get_lineup([("Chris", "Darren"), ("Alice", "Bob"), ("Darren", ""), ("Bob", "Chris")]) should return ["Alice", "Bob", "Chris", "Darren"].
Example 2:
Given the following code,
info = [("Mary", "Jason"), ("John", "Alan"), ("Jason", "George"), ("Alan", "Christie"), ("Christie", "Mary"), ("George", "")]
print(get_lineup(info))
we should see the following output:
['John', 'Alan', 'Christie', 'Mary', 'Jason', 'George']