Given the list a = ['a', 'b', 'c', 'd', 'e']
, I would use itertools.combinations
to get all unique combos like ['ab', 'ac', ...]
, as per the classic SO answer
How can I limit the unique combinations to items that are not farther away than n
spots?
Example
If I want list items no more than n=2
spots away, I would accept 'ab'
and 'ac'
as combinations but not 'ae'
, because the distance between 'a'
and 'e'
is greater than n=2
Edit - code
Below the plain python code solution, which I'd avoid due to the double-for loop, that is not ideal for large lists
a = ['a', 'b', 'c', 'd', 'e']
n_items = len(a)
n_max_look_forward = 2
unique_combos = []
for i, item in enumerate(a):
for j in range(i+1, min(i+n_max_look_forward+1, n_items)):
unique_combos.append( item+a[j] )
print(unique_combos)