handloomweaver
handloomweaver

Reputation: 5011

Find all possible combinations of tuple pairs merging each into new sequences

I have a bus route that travels on a route (sequence of places) in this order:-

Ayr - Newton - Troon - Paisley - Glasgow

i.e route = ['Ayr', 'Newton', 'Troon', 'Paisley', 'Glasgow']

I needed to find every possible way you can split the journey up (always starting at Ayr ending at Glasgow so I have code (python) that finds every pair combination and appends each (tuple) pair to a list.

pairs = [('Ayr', 'Newton'),('Ayr', 'Troon'),('Ayr', 'Paisley'),('Ayr', 'Glasgow'),('Newton', 'Troon'),('Newton', 'Paisley'),('Newton', 'Glasgow'),('Troon', 'Paisley'),('Troon', 'Glasgow'),('Paisley', 'Glasgow')]

What I want to end up with is a list of lists or list of tuples (or the fastest most memory efficient sequence) that has every possible combination of pairs (that starts in Ayr and ends in Glasgow).

final_splits = [['Ayr', 'Glasgow'], ['Ayr', 'Newton', 'Glasgow'], ['Ayr', 'Newton', 'Troon', 'Glasgow'], ['Ayr', 'Newton', 'Troon', 'Paisley', 'Glasgow'], ['Ayr', 'Troon', 'Glasgow'], ['Ayr', 'Troon', 'Glasgow'], ['Ayr', 'Troon', 'Paisley', 'Glasgow']..........etc]

Not an easy one! Can anyone help?

Upvotes: 1

Views: 1745

Answers (1)

John La Rooy
John La Rooy

Reputation: 304167

Assuming every combination would appear in pairs, there is no need to compute that intermediate step

>>> from itertools import combinations
>>> route = ['Ayr', 'Newton', 'Troon', 'Paisley', 'Glasgow']
>>> [(route[0],)+x+(route[-1],) for i in range(len(route)-1) for x in combinations(route[1:-1],i)]
[('Ayr', 'Glasgow'), ('Ayr', 'Newton', 'Glasgow'), ('Ayr', 'Troon', 'Glasgow'), ('Ayr', 'Paisley', 'Glasgow'), ('Ayr', 'Newton', 'Troon', 'Glasgow'), ('Ayr', 'Newton', 'Paisley', 'Glasgow'), ('Ayr', 'Troon', 'Paisley', 'Glasgow'), ('Ayr', 'Newton', 'Troon', 'Paisley', 'Glasgow')]

Upvotes: 7

Related Questions