permutations might not be exactly the right word.
say x = "123456"
.
I want my code to output ['12','23','34','45','56']
.
Right now, I know how to split it into ['12','34','56']
permutations might not be exactly the right word.
say x = "123456"
.
I want my code to output ['12','23','34','45','56']
.
Right now, I know how to split it into ['12','34','56']
You just need a range that increments by 1
def split_into(values, n):
return [values[i:i + n] for i in range(len(values) - n + 1)]
x = "123456789"
print(split_into(x, 2)) # ['12', '23', '34', '45', '56', '67', '78', '89']
print(split_into(x, 3)) # ['123', '234', '345', '456', '567', '678', '789']
print(split_into(x, 4)) # ['1234', '2345', '3456', '4567', '5678', '6789']
print(split_into(x, 5)) # ['12345', '23456', '34567', '45678', '56789']
In Python 3.10, it looks like itertools.pairwise()
will do what you want:
>>> from itertools import pairwise
>>> print(*map(''.join, pairwise("123456")))
The above is just a simulation as I don't have 3.10 yet ;-) Until then, the documenation for pairwise()
provides an alternative:
from itertools import tee
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
print(*map(''.join, pairwise("123456")))