Lau
Lau

Reputation: 3680

Split string of integers to all possible list of numbers

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

Upvotes: 1

Views: 1955

Answers (3)

Tenzin
Tenzin

Reputation: 2505

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

Upvotes: 0

roman
roman

Reputation: 117636

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]

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107357

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

Upvotes: 2

Related Questions