3

I am trying to write code that will return possible decompositions of a big number of 3, up to 3-digit, numbers.
The number is formed by num=str([0-999])+str([0-999])+str([0-999]). All the components are independent and random.
For example, the expected output for '1111' would be: [[1,11,1],[11,1,1],[1,1,11]].

The code I have written so far:

def isValidDecomp(num,decmp,left):
    if(len(num)-len(decmp)>=left):
        if(int(decmp)<999):
            return True
    return False

def decomp(num,length,pos,left):
    """
    Get string repping the rgb values
    """
    while (pos+length>len(num)):
        length-=1
    if(isValidDecomp(num,num[pos:pos+length],left)):
        return(int(num[pos:pos+length])) 
    return 0 #additive inverse

def getDecomps(num):
    length=len(num)
    decomps=[[],[],[]]
    l=1
    left=2
    for i in range(length): 
        for j in range(3):
            if(l<=3):
                decomps[j].append(decomp(num,l,i,left))
                l+=1
            if(l>3): #check this immediately
                left-=1
                l=1#reset to one
    return decomps

d=getDecomps('11111')

print( d)

My code's (incorrect) outputs with different cases:

input,output
'11111', [[1, 1, 1, 1, 1], [11, 11, 11, 11, 1], [111, 111, 111, 11, 1]]
'111', [[1, 1, 1], [0, 11, 1], [0, 11, 1]]
'123123145', [[1, 2, 3, 1, 2, 3, 1, 4, 5], [12, 23, 31, 12, 23, 31, 14, 45, 5], [123, 231, 0, 123, 231, 0, 145, 45, 5]]

Can someone please tell me what I'm doing wrong?

CDJB
  • 14,043
  • 5
  • 29
  • 55
pasha
  • 406
  • 1
  • 4
  • 17

1 Answers1

4

If I understand the question correctly, this could be achieved by adapting the approach found here to return all possible ways to split the input string:

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

And then filtering the results from the generator:

def getDecomps(s):
    return [x for x in splitter(s) if len(x) == 3 and all(len(y) <= 3 for y in x)]

Usage:

>>> getDecomps('1111')
[('1', '1', '11'), ('1', '11', '1'), ('11', '1', '1')]
>>> getDecomps('111')
[('1', '1', '1')]
>>> getDecomps('123123145')
[('123', '123', '145')]
>>> getDecomps('11111')
[('1', '1', '111'),
 ('1', '11', '11'),
 ('1', '111', '1'),
 ('11', '1', '11'),
 ('11', '11', '1'),
 ('111', '1', '1')]
CDJB
  • 14,043
  • 5
  • 29
  • 55