Merging two numbers in python without list

Viewed 66

I need to merge two numbers and create all possible outcomes.

Lets say we have a = 45 and b = 766, we are looking for such numbers **45**766, **4**7**5**66, **4**76**5**6 and so on, In a way that the original numbers stay in the same order (we can't do **54**766).

I can use only math to solve this. Can you name any method or path of thinking to achieve this goal?

1 Answers

You can write a recursive generator function that does this. There are two recursive cases, one where you take one digit from a and one where you take a digit from 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

You can call it like this:

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