user15033416
user15033416

Reputation:

Merge two number with the integers at corresponding position together (without using str)

Let's say I have two integers:

a = 123
b = 4567

I want to merge these numbers keeping the corresponding position of integer at each position together. My desire final number is:

1425367

But I don't want to use str to achieve this.


Here's the code I have written so far. But it simply disregards the last number.

Edit: I know I used str, but I don't know any other way to achieve this

def f(a,b):
    sa, sb = list(str(a)), list(str(b))
    i, j = 0, 0
    s = ""
    while i < len(sa) and j < len(sb):
        s += sa[i]
        s += sb[j]
        i += 1
        j += 1
    return s

print(f(23,56))```

Upvotes: 1

Views: 902

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

Here's my approach to achieve this without using string (or f-string):

  1. Create a function to split your numbers into list of integers
  2. Merge list of both the integers containing corresponding numbers together
  3. Join the numbers in the list using multiplication by 10 to get desired final number

Step 1: Split number to list of integers

Created custom function using math.log10() which returns the list of integers from given string

from math import log10

def get_num_left_to_right(num):
    n = int(log10(num))
    for i in range(n, -1, -1):
        fac = 10**i
        x = num//fac
        yield x
        num -= x * fac

Sample run:

a, b = 123, 4567

x = list(get_num_left_to_right(a))
# where `x` holds:
# [1, 2, 3]

y = list(get_num_left_to_right(b))
# where `y` holds:
# [4, 5, 6, 7]

Step 2: Merge both the lists with corresponding number together

I am using itertools.chain and itertools.izip_longest along with list comprehension to achieve this. For example:

from itertools import izip_longest, chain

num_list = [x for x in chain(*izip_longest(x, y)) if x is not None]
# where `num_list` will hold:
# [1, 4, 2, 5, 3, 6, 7]

Step 3: Multiply the number in list by the power of 10

Finally, I am multiply the numbers in the list by the 10**(length-i-1) to get the desired position of integer in the final number

num, length = 0, len(num_list)

for i, n in enumerate(num_list):
    num += n*10**(length-i-1)

# where `num` will be holding:
# 14253670

Upvotes: 0

Akshay Sehgal
Akshay Sehgal

Reputation: 19307

Try this approach without any form of string or fstrings. A pure numeric approach -

from itertools import zip_longest

def get_pos_nums(num):
    pos_nums = []
    while num != 0:
        pos_nums.append((num % 10))
        num = num // 10
    return list(reversed(pos_nums))

zipped = zip_longest(get_pos_nums(a), get_pos_nums(b))
digits = [i for j in zipped for i in j if i!=None]
number = sum(d * 10**i for i, d in enumerate(digits[::-1]))
1425367
  1. The first function breaks a number into its digits by dividing by 10
  2. Next zip_longest zips the 2 lists in the order provided, giving None if one of the strings runs out of digits.
  3. Flatten this list of digits and remove the Nones
  4. Combine them with a sum after multiplying each with power of 10s

Upvotes: 1

Samwise
Samwise

Reputation: 71512

Use f-strings instead of str, and use zip_longest to combine the two strings:

>>> from itertools import zip_longest
>>> int(''.join((x or "") + (y or "") for x, y in zip_longest(f"{a}", f"{b}")))
1425367

If you have some "no imports" rule, it's not too much harder to do this with the builtin zip, but you need to special-case the trailing digits:

>>> int(''.join((x or "") + (y or "") for x, y in zip(f"{a}", f"{b}")) + f"{a}")[len(f"{b}"):] + f"{b}"[len(f"{a}"):]
1425367

Upvotes: 4

Related Questions