我需要合併兩個數字並創建所有可能的結果。
假設我們有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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句