首页 > 解决方案 > 在没有列表的python中合并两个数字

问题描述

我需要合并两个数字并创建所有可能的结果。

假设我们有a = 45and b = 766,我们正在寻找这样的数字**45**766,**4**7**5**66等等**4**76**5**6,以使原始数字保持相同顺序的方式(我们不能这样做**54**766)。

我只能用数学来解决这个问题。你能说出实现这一目标的任何方法或思路吗?

标签: pythonnumbers

解决方案


您可以编写一个递归生成器函数来执行此操作。有两种递归情况,一种是从 中取一位数,a另一种是从 中取一位数b

def merge(a, b):
    if a == 0:                 # base cases
        yield b
        return
    if b == 0:
        yield a
        return
    
    digit = a % 10             # recursive case where we take last digit from `a`
    for x in merge(a//10, b):  # the recursive call omits that last digit
        yield x*10 + digit     # put the digit to the right of the recursive results

    digit = b % 10             # do all the same things for a digit from `b`
    for x in merge(a, b//10):
        yield x*10 + digit

你可以这样称呼它:

>>> print(list(merge(45, 766)))
[76645, 76465, 74665, 47665, 76456, 74656, 47656, 74566, 47566, 45766]

推荐阅读