2

I have a number, which I want to split as shown below. I want to keep the order in which the number is present but the list which is made from this must maintain the original order of the number.

The number which I have is 3147 which can be split as shown below. 3147 can be split into 31, 47 or 3,1,47 etc. But the order of the original number musn't be lost.

So how can I implement this?

It would be best if I get an answer in Python but in any other language is also fine.

Input
3147

Output

[3,1,4,7]
[3,147]
[3,1,47]
[31,4,7]
[31,47]
etc
CDJB
  • 14,043
  • 5
  • 29
  • 55
febavi
  • 31
  • 3

3 Answers3

5

You can use an adaption of my answer here:

Code:

def splitter(n):
    s = str(n)
    for i in range(1, len(s)):
        start = s[0:i]
        end = s[i:]
        yield [int(start), int(end)]
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield list(int(x) for x in result)

Usage:

for x in splitter(3147):
    print(x)

Output:

[3, 147]
[3, 1, 47]
[3, 1, 4, 7]
[3, 14, 7]
[31, 47]
[31, 4, 7]
[314, 7]
CDJB
  • 14,043
  • 5
  • 29
  • 55
1

Lazy solution with no recursion:

import itertools

def splitter(L):
    for a in itertools.product([0,1], repeat=len(L) - 1):
        a = (0,) + a
        yield [''.join(map(lambda x: x[0], g)) 
               for _, g in itertools.groupby(zip(L, a), key=lambda x: x[1])]

L = ['3','1','4','7']
for l in splitter(L):
    print(l)

Output:

['3147']
['314', '7']
['31', '4', '7']
['31', '47']
['3', '1', '47']
['3', '1', '4', '7']
['3', '14', '7']
['3', '147']
Grigory Feldman
  • 405
  • 3
  • 7
1

Shorter recursive approach:

def split(d):
   yield tuple(d)
   if len(d) > 1:
     yield from [b for i in range(len(d)-1) for b in split(d[:i]+[d[i]+d[i+1]]+d[i+2:])]

val = 3147
print(set(split(list(map(str, str(val))))))

Output:

{('3', '1', '4', '7'), 
('3', '1', '47'), 
('3', '147'), 
('31', '4', '7'), 
('3147',), 
('314', '7'), 
('3', '14', '7'), 
('31', '47')}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102