How can I get the first two digits of a number?

前端 未结 4 1497
-上瘾入骨i
-上瘾入骨i 2020-12-30 19:31

I want to check the first two digits of a number in Python. Something like this:

for i in range(1000):

    if(first two digits of i == 15):
        print(\"         


        
4条回答
  •  时光说笑
    2020-12-30 20:31

    Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).

    The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits

    # the "maths" version
    import math
    
    def first_n_digits1(num, n):
        return num // 10 ** (int(math.log(num, 10)) - n + 1)
    
    %timeit first_n_digits1(34523452452, 2)
    1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit first_n_digits1(34523452452, 8)
    1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    # 22 digits
    %timeit first_n_digits1(3423234239472523452452, 2)
    1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit first_n_digits1(3423234239472523452452, 15)
    1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    # 196 digits
    %timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
    1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    # The "string" verions
    def first_n_digits2(num, n):
        return int(str(num)[:n])
    
    %timeit first_n_digits2(34523452452, 2)
    744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit first_n_digits2(34523452452, 8)
    768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    # 22 digits
    %timeit first_n_digits2(3423234239472523452452, 2)
    767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit first_n_digits2(3423234239472523452452, 15)
    830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    # 196 digits
    %timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
    1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

提交回复
热议问题