gpt4 book ai didi

python - 将数字分解为其他数字

转载 作者:行者123 更新时间:2023-12-02 04:45:23 25 4
gpt4 key购买 nike

我正在尝试编写代码,该代码将返回大量 3(最多 3 位数字)的可能分解。
该数字由num=str([0-999])+str([0-999])+str([0-999])组成。所有组件都是独立且随机的。
例如,'1111' 的预期输出为:[[1,11,1],[11,1,1],[1,1,11]].

到目前为止我编写的代码:

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)

我的代码在不同情况下的(不正确)输出:

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

有人可以告诉我我做错了什么吗?

最佳答案

如果我正确理解了这个问题,这可以通过调整发现的方法来实现 here返回分割输入字符串的所有可能方法:

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)

然后过滤生成器的结果:

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

关于python - 将数字分解为其他数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59985484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com