More pythonic way to achieve decimal zipper

Given two numbers aand b, the definition of decimal zip is explained below:

• the first (that is, the most significant) digit C is the first digit a;

• the second digit C is the first digit b;

• the third digit C is the second digit a;

• the fourth digit C is the second digit b;

• etc.

If one of the integers aand bends with the numbers, the remaining numbers another integer is added 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))

, ?

:

  • a b, .
  • , .
+4
2

itertools.zip_longest:

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

x+y, itertools.chain, :

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

int, :

c = int("".join(chain.from_iterable(zip_longest(a,b, fillvalue=''))))
+4

oneliner:

from itertools import zip_longest

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

: zip_longest, , fillvalue iterables. "" ( ) , zip .

+4

Source: https://habr.com/ru/post/1679834/


All Articles