Decompose Number Into Other Numbers
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])
Solution 1:
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 inrange(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:
defgetDecomps(s):
return [x for x in splitter(s) iflen(x) == 3andall(len(y) <= 3for 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')]
Post a Comment for "Decompose Number Into Other Numbers"