mercredi 29 août 2018

variable scope under while+for loop and if statement

The purpose of this code is trying to output the route where the second element of one tuple is the same as the first element of another tuple.

When the i += 1 has the same indentation as for loop, "JFK" is the origin, path = segments. I got ['JFK', 'DEN', 'SFO', 'LAS', 'LAX', 'ORD', 'ATL'] which is the correct answer.

When i += 1 has the same indentation as if statement, I only got ['JFK', 'DEN', 'SFO', 'LAS']. Does anyone know why???

segments = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"),   
("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]

def get_route(path, origin):

    my_list = []

    i = 0

    list_len = len(path)

    path_copy = path.copy()

    while i <= list_len:

        for k in path_copy:

            if origin == k[0] and origin not in my_list:

                my_list.append(k[0])

                origin = k[1]

                path_copy.remove(k)

         i += 1

    return my_list

Aucun commentaire:

Enregistrer un commentaire