MASOUD
MASOUD

Reputation: 41

Combining elements in a list in Python where sequence matters

I have a 2d list

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

Figures are the node names in a TSP ([6,7] means go from 6 to 7). Each row in a corresponds to a tour in specific day. I need to make another 2d list which sequences are considered: Below is what I need:

FinalTours = [[6,7,4], 
              [4,7,8,15],
              [15,3,19,12]]

Any suggestions? I tried the code below but it only works for the first day (first row of a)

FinalTours = [[] for i in range(T)]           
for t in range(T):
    for i in AllTour[t]:
        if t == 0:
            Wakeup = 6
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

        else:
            Wakeup = Tour[-1] 
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

Upvotes: 2

Views: 65

Answers (1)

user2390182
user2390182

Reputation: 73470

Naive approach brute-forcing a path from a list, using itertools.permutations

from itertools import permutations

def is_path(lst):
    # check if [[a, b], [b, c], [c, d], ...] holds
    return all(x[1] == y[0] for x, y in zip(lst, lst[1:]))

def make_path(lst):
    # find lst permutation that is a path
    for p in permutations(lst, len(lst)):
        if is_path(p):
            return p
    raise ValueError('No Path possible')

def flatten_path(lst):
    # turn [[a, b], [b, c]] into [a, b, c]
    return lst[0][:1] + [x[1] for x in lst]

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

paths = [flatten_path(make_path(x)) for x in a]
# [[6, 7, 4], [4, 7, 8, 15], [15, 3, 19, 12]]

Upvotes: 2

Related Questions