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:
a
and b
although one or them or neither of them will be unnecessary in certain cases.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=''))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With