![](/img/trans.png)
[英]What is the most efficient way of finding all the factors of a number in Python?
[英]what is the most efficient way of concat two numbers to one number in python?
在python中將兩個數字連接到一個數字的最有效方法是什么?
數字總是介於0到255之間,我已經通過Concat測試了幾種方式作為字符串並轉換回int但是它們對我的代碼來說非常昂貴。
例
a = 152
c = 255
d = concat(a,c)
回答:
d = 152255
如果數字有界,只需乘以並加:
>>> a = 152
>>> c = 255
>>> d = a*1000+c
>>> d
152255
>>>
這很快:
def concat(a, b):
return 10**int(log(b, 10)+1)*a+b
它使用對數來查找第一個數字必須乘以10的次數,以使總和作為連接起作用
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
是的,你去了:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.