将数字分解为其他数字 [英] Decompose number into other numbers
问题描述
我正在尝试编写代码,以返回可能分解为3个数字(最多3个数字)的数字.
该数字由num=str([0-999])+str([0-999])+str([0-999])
组成.所有组件都是独立且随机的.
例如,'1111'
的预期输出将是:[[1,11,1],[11,1,1],[1,1,11]]
.
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?
推荐答案
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)]
用法:
>>> 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')]
这篇关于将数字分解为其他数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!