将数字拆分为所有可能的数字组,保持原始顺序

2024-05-13 04:05:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数字,我想拆分如下。我想保持数字出现的顺序,但由此产生的列表必须保持数字的原始顺序

我的号码是3147,可以按如下所示进行拆分。3147可以分为31、47或3、1、47等,但不能丢失原始编号musn的顺序

那么我如何实现这一点呢

最好是用Python来回答,但用任何其他语言也可以

Input
3147

Output

[3,1,4,7]
[3,147]
[3,1,47]
[31,4,7]
[31,47]
etc

Tags: 语言列表inputoutput顺序etc数字编号
3条回答

较短的递归方法:

def split(d):
   yield tuple(d)
   if len(d) > 1:
     yield from [b for i in range(len(d)-1) for b in split(d[:i]+[d[i]+d[i+1]]+d[i+2:])]

val = 3147
print(set(split(list(map(str, str(val))))))

输出:

{('3', '1', '4', '7'), 
('3', '1', '47'), 
('3', '147'), 
('31', '4', '7'), 
('3147',), 
('314', '7'), 
('3', '14', '7'), 
('31', '47')}

无递归的惰性解决方案:

import itertools

def splitter(L):
    for a in itertools.product([0,1], repeat=len(L) - 1):
        a = (0,) + a
        yield [''.join(map(lambda x: x[0], g)) 
               for _, g in itertools.groupby(zip(L, a), key=lambda x: x[1])]

L = ['3','1','4','7']
for l in splitter(L):
    print(l)

输出:

['3147']
['314', '7']
['31', '4', '7']
['31', '47']
['3', '1', '47']
['3', '1', '4', '7']
['3', '14', '7']
['3', '147']

您可以使用我的答案here的改编:

代码:

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

用法:

for x in splitter(3147):
    print(x)

输出:

[3, 147]
[3, 1, 47]
[3, 1, 4, 7]
[3, 14, 7]
[31, 47]
[31, 4, 7]
[314, 7]

相关问题 更多 >