简体   繁体   中英

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.

(If n is the desired number) So, method 1:

if n % 10 == 8:
    //do stuff here

Method 2:

if str(n)[-1] == 8:
    //do stuff here

You could easily test this yourself with Python's built-in timeit.timeit function:

>>> 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:

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.

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