Using six methods of Python: given a positive integer of no more than 5 bits, judge how many bits there are

Keywords: Python less

Method 1: comparison

a=int(input(">>>>"))
if a<10:            
    print(1)
elif a<100:   #The first condition has been filtered to be greater than 9, so the range here is 11 to 100
    print(2)
elif a<1000:
    print(3)
elif a<10000:
    print(4)
else:
    print(5)

Method 2: use integer division. If it is a 0 or not a 0 after division, calculation is introduced in this method, and the efficiency will be reduced. Therefore, if you can add, do not subtract, if you can multiply, do not divide, if you can not calculate, do not calculate

i = int(intput('>>>')
if i // 10000:
    print(5):
elif i // 1000:
    print(4)
elif i // 100:
    print(3)
elif i // 10:
    print(2)
else:
    print(1)

Analysis: assume that in the case of 5 digits, other conditions are not considered

In [1]: 6666 // 10000
Out[1]: 0                Divide by 10000 to zero to prove less than 5 digits
 
In [2]: 6666 // 1000
Out[2]: 6                But if it's divisible by 1000, it's a four digit number
 
In [3]: 6666 // 100
Out[3]: 66
 
In [4]: 6666 // 10
Out[4]: 666
 
In [5]: 6666 // 1
Out[5]: 6666

PS: no one answers the questions? Need Python learning materials? You can click the link below to get it by yourself
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

Method three:

a=int(input(">>>"))
if a<0:
    print("Format is wrong")
elif a<100000:    ##Limit 5 bits
    if a<10:
        print(1)
    elif a<100:
        print(2)
    elif a<1000:
        print(3)
    elif a<10000:
        print(4)
    else:  
        print(5)
else:
    print("Please enter a number of no more than 5 digits")

Method 4: string processing implementation

#!/usr/bin/python3
nnumber=input(">>>>")
length=len(nnumber)
if length>4:
    print(5)
elif length>3:
    print(4)
elif length>2:
    print(3)
elif length>1:
    print(2)
else:
    print(1)

Method 5: half realization

#!/usr/bin/python3
number = int(input("number >> "))
if number >= 100:       ##Fold directly from 100
    if number >= 10000:
        print("5")
    elif number >= 1000:
        print("4")
    else:
        print("3")
else:
    if number >= 10:
        print("2")
    else:
        print("1")

Method 6: math implementation. This method is slower than division, and it will be obvious if the cycle is 1 million times

number=int(input("Enter a positive integer of no more than 5 digits: ")
if a<=0 or a>=100000:
    print('Please enter a positive integer with no more than 5 digits')
else:
    import math
    b=int(math.log10(a)+1)
    print(b)

Posted by c4onastick on Mon, 16 Dec 2019 06:05:54 -0800