在没有列表的情况下合并 python 中的两个数字
Merging two numbers in python without list
我需要合并两个数字并创建所有可能的结果。
假设我们有 a = 45
和 b = 766
,我们正在寻找这样的数字 **45**766
、**4**7**5**66
、**4**76**5**6
等等,在原始数字保持相同顺序的方式(我们不能这样做 **54**766
)。
我只能用数学来解决这个问题。
您能说出实现这一目标的任何方法或思路吗?
您可以编写执行此操作的递归生成器函数。有两种递归情况,一种是从 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]
我需要合并两个数字并创建所有可能的结果。
假设我们有 a = 45
和 b = 766
,我们正在寻找这样的数字 **45**766
、**4**7**5**66
、**4**76**5**6
等等,在原始数字保持相同顺序的方式(我们不能这样做 **54**766
)。
我只能用数学来解决这个问题。 您能说出实现这一目标的任何方法或思路吗?
您可以编写执行此操作的递归生成器函数。有两种递归情况,一种是从 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]