1

I have a string of integers e.g. s = "1234" I want to split it to the individual sequential combinations of integers split = [ 1234, 1, 2, 3, 4, 12, 123, 23, 234, 34 ] How can I code this in Python?

What i tried:

for i in range(0,len(number)-1):
x =["" + number[j] for j in range(i, len(number))]
print(x)

Output:

['1', '2', '3', '4', '5']
['2', '3', '4', '5']
['3', '4', '5']
['4', '5']
Lau
  • 3,260
  • 5
  • 16
  • 25
  • Are *duplicates* allowed? What is the amswer for, say, `1212`? Is it [1212, 121, 212, 12, 21, 12, 1, 2, 1, 2]` or `[1212, 121, 212, 12, 21, 1, 2]` only? – Dmitry Bychenko Jan 11 '17 at 11:25
  • 1
    Possible duplicate of [How to get all possible combinations of a list’s elements?](http://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – fredtantini Jan 11 '17 at 11:33
  • I'm sorry for not making my question clear enough but I need the combinations to be sequential in string `1234` combinations for `2` should only be `23, 234` ignoring `21 and 24` – Lau Jan 11 '17 at 11:42

3 Answers3

2

You need all the combinations, so you can use itertools.combinations and a generator expression in order to generate all of them:

In [25]: from itertools import combinations
In [26]: list(''.join(sub) for i in range(1, len(s) + 1) for sub in combinations(s, i))
Out[26]: 
['1',
 '2',
 '3',
 '4',
 '12',
 '13',
 '14',
 '23',
 '24',
 '34',
 '123',
 '124',
 '134',
 '234',
 '1234']
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Thanks for the answer but what I really needed was a sequential combination lists so elements `13, 14, 134 ` etc. should be ignored in my case – Lau Jan 11 '17 at 11:47
2

You can use combinations from itertools library combined with list comprehension:

>>> from itertools import combinations
>>> s = "1234"
>>> [int(''.join(x)) for i in range(len(s)) for x in combinations(s, i + 1)]
[1, 2, 3, 4, 12, 13, 14, 23, 24, 34, 123, 124, 134, 234, 1234]

update As you need only sequential combinations, you can use all substrings from the string (using How To Get All The Contiguous Substrings Of A String In Python?):

>>> l = len(s)
>>> [int(s[i:j+1]) for i in range(l) for j in range(i,l)]
[1, 12, 123, 1234, 2, 23, 234, 3, 34, 4]
Community
  • 1
  • 1
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
0

Are you looking for somethng like this:

stringA = "1234";
lenA = len(stringA);

# Loop through the number of times stringA is long.
for n in range(lenA):
    print("---");
    # Loop through string, print part of the string.
    for x in range(lenA-n):
        print(stringA[n:n + (x+1)])

I suggest having a look at substrings, that is what I also do in my example above.
Link

Tenzin
  • 2,415
  • 2
  • 23
  • 36