4

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.
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Harish Talanki
  • 866
  • 13
  • 27

2 Answers2

4

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=''))))
MSeifert
  • 145,886
  • 38
  • 333
  • 352
4

Yes you can use the following oneliner:

from itertools import zip_longest

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

The code works as follows: we use zip_longest to zip the two strings together, and we make use of fillvalues in case one of the iterables gets exhausted. Then for each two "digits" (or empty strings in case the string is exhausted), we concatenate these together, and then we concatenate all those combinations of the zip together for the result.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555