0

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']

wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

0

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']
azro
  • 53,056
  • 7
  • 34
  • 70
  • Ah, I see. Thank you so much, I tried incrementing it by 1 by forgot that I should subtract n+1 from the length. – La Lala Nov 17 '22 at 20:42
0

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")))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • 1
    It's close. `pairwise()` returns 2-tuples, not slices. This works: `list(map(''.join, pairwise(x)))` – wjandrea Nov 17 '22 at 20:49
  • Beside the point, but you know you can install 3.10 on any OS, right? You can also try it out [on Python.org](https://www.python.org/shell/). – wjandrea Nov 17 '22 at 20:51