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

标签 python python-3.x string list split

我正在尝试编写代码,该代码将返回大量 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/

相关文章:

python - 在 pyspark 中写入 CSV 文件时选择编码

Python3 : Wait for Daemon to finish iteration

string - 删除给定字符串第一次出现之后/之前的所有内容

javascript - 如何将 JS 多行字符串转换为带有制表符的单行

python - 需要修改版本的 Python 字典

python - 使用 numpy 将向量添加到矩阵的特定行

python - 在 Python 中命名正则表达式组

python - Flask-Limiter 不适用于基于 Flask-Restful API 的应用程序

python - 在 python 中使用正则表达式操作解析出 URL

java - 如何检查两个字符串实际上相等并且具有相同的字符?即使有空格或小写