python - 在没有列表的python中合并两个数字
问题描述
我需要合并两个数字并创建所有可能的结果。
假设我们有a = 45
and 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]
推荐阅读
- android - android studio - 如何根据文本调整按钮的大小?
- node.js - 如何构建动态 MongoDB 查询
- ios - Cordova - 使用多个目标配置文件更新 exportOptions plist 以创建 ipa
- javascript - 迭代 Swagger YAML 文件以动态生成属性列表
- docusignapi - 一小时后Docusign API失败
- microsoft-graph-api - Microsoft Graph API 为同一邮件返回了不同的 threadID
- android - 从 DB 文件创建 Android Room 实体类
- javascript - 如何在不调用/创建侦听器函数的情况下增加 let 变量
- android - 我的应用 UI 中的广告展示位置是否遵循 admob 政策或违反?
- c# - 处理预制件时出现错误“对象引用未设置为对象的实例”