[英]Most efficient way to look for the last digit of a number?
I recently had a question in a Python exam where we were asked to check for numbers to be ending in 8 and I came across two ways and I was wondering which one was the most efficient or if there was an even better way to do so. 我最近在Python考试中遇到了一个问题,我们被要求检查数字是否以8结尾,我遇到了两种方式,我想知道哪一个最有效,或者是否有更好的方法。
(If n is the desired number) So, method 1: (如果n是所需的数字)那么,方法1:
if n % 10 == 8:
//do stuff here
Method 2: 方法2:
if str(n)[-1] == 8:
//do stuff here
You could easily test this yourself with Python's built-in timeit.timeit
function: 您可以使用Python的内置
timeit.timeit
函数轻松地timeit.timeit
:
>>> from timeit import timeit
>>> n = 12345678
>>> timeit("n % 10 == 8", "from __main__ import n")
0.45508130223254284
>>> timeit("str(n)[-1] == '8'", "from __main__ import n")
1.689859186013905
>>>
As you can see from the results above, the first solution is very efficient and outperforms the second by almost four times. 从上面的结果可以看出,第一种解决方案非常有效,并且比第二种解决方案的性能提高了近四倍。
For more fun and excitement in addition to iCodez answer, you can use the dis
module to see what the difference in instructions is: 除了iCodez答案之外,为了获得更多乐趣和兴奋,您可以使用
dis
模块查看说明中的不同之处:
wayne@wango ~ ⚘ python3.4 14:24:49
Python 3.4.0 (default, Mar 25 2014, 15:24:33)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> dis.dis('n % 10 == 8')
1 0 LOAD_NAME 0 (n)
3 LOAD_CONST 0 (10)
6 BINARY_MODULO
7 LOAD_CONST 1 (8)
10 COMPARE_OP 2 (==)
13 RETURN_VALUE
>>> dis.dis('str(n)[-1] == 8')
1 0 LOAD_NAME 0 (str)
3 LOAD_NAME 1 (n)
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 LOAD_CONST 2 (-1)
12 BINARY_SUBSCR
13 LOAD_CONST 1 (8)
16 COMPARE_OP 2 (==)
19 RETURN_VALUE
If I were to make a guess, I'd say the major time difference has to do with the string conversion. 如果我猜一下,我会说主要的时差与字符串转换有关。 And a quick test:
并快速测试:
>>> from timeit import timeit
>>> n = 12345678
>>> m = "12345678"
>>> timeit("n % 10 == 8", "from __main__ import n")
0.09333206800511107
>>> timeit("m[-1] == '8'", "from __main__ import m")
0.05890634500246961
>>>
Shows this to be the case. 显示这种情况。
Additionally in your code, the second example would always equate to False
, since a string will never ==
a number. 此外,在您的代码中,第二个示例总是等于
False
,因为字符串永远不会==
一个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.