简体   繁体   中英

what is the most efficient way of concat two numbers to one number in python?

what is the most efficient way of concat two numbers to one number in python?

numbers are always in between 0 to 255, i have tested few ways by Concat as string and cast back to int but they are very costly in time vice for my code.

example

    a = 152 
    c = 255
    d = concat(a,c)

answer:

    d = 152255

If the numbers are bounded, just multiply and add:

>>> a = 152
>>> c = 255
>>> d = a*1000+c
>>> d
152255
>>>

This is pretty fast:

def concat(a, b):
    return 10**int(log(b, 10)+1)*a+b

It uses the logarithm to find how many times the first number must be multiplied by 10 for the sum to work as a concatenation

In [1]: from math import log

In [2]: a = 152

In [3]: b = 255


In [4]: def concat(a, b):
   ...:     return 10**int(log(b, 10)+1)*a+b
   ...:

In [5]: concat(a, b)
Out[5]: 152255

In [6]: %timeit concat(a, b)
1000000 loops, best of 3: 1.18 us per loop

Yeah, there you go:

a = 152
b = 255

def concat(a, b):
    n = next(x for x in range(10) if 10**x>a)  # concatenates numbers up to 10**10
    return a * 10**n + b

print(concat(a, b))  # -> 152255

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM