2

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?

3
  • Convert a and b to string. Concatenate the string. Apply some logic to generate those permutations. Then convert the string result back to int. Commented Oct 30, 2021 at 9:21
  • I cannot do that, only mathematics, no strings no lists. Commented Oct 30, 2021 at 9:28
  • Then combine a and b using multiplication, division and modulo operators. 45 * 1000 + 766 = 45766. 45 modulo 10 = 5, 45 / 10 = 4, 4 * 10000 + 766 * 10 + 5 = 47665. Something like that. Commented Oct 30, 2021 at 9:31

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.