Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More pythonic way of achieving decimal zip [duplicate]

Given two numbers a and b, definition of decimal zip is as explained below:

• the first (i.e. the most significant) digit of C is the first digit of a;

• the second digit of C is the first digit of b;

• the third digit of C is the second digit of a;

• the fourth digit of C is the second digit of b;

• etc.

If one of the integers a and b runs out of digits, the remaining digits of the other integer are appended to the result.

Example:

Input: a = 12, b = 59 Output should be: c = 1529

Input: a = 1094, b = 12 Output: c = 110294

I have this code:

a = 1234534543
b = 3525523342

a = str(a)
b = str(b)
aLen = len(a)
bLen = len(b)

c = "".join([x+y for (x,y) in zip(a,b)]) + a[min(aLen,bLen):] + b[min(aLen,bLen):]
print(int(c))

It works, but is there a more pythonic way to achieve the same?

Problem with the above code is:

  • I am trying to append the remaining digits of a and b although one or them or neither of them will be unnecessary in certain cases.
  • It takes some time when the input is too big.
like image 896
Harish Talanki Avatar asked Feb 05 '23 05:02

Harish Talanki


1 Answers

You could use itertools.zip_longest:

from itertools import zip_longest
c = "".join([x+y for (x,y) in zip_longest(str(a), str(b), fillvalue='')])

In case you don't like the x+y there is also itertools.chain which flattens the iterable:

from itertools import chain
c = "".join(chain.from_iterable(zip_longest(a,b, fillvalue='')))

You can also wrap this inside inside an int, to do everything in one line:

c = int("".join(chain.from_iterable(zip_longest(a,b, fillvalue=''))))
like image 87
MSeifert Avatar answered Feb 06 '23 17:02

MSeifert