简体   繁体   中英

Program with "5 10 20 40" pattern in Python without infinite "if" statements

I want to make a python program where the user inserts a number

If number < 5, it prints 0

If 5 < number < 10, it prints 1

If 10 < number < 20, it prints 2

If 20 < number < 40, it prints 3

If 40 < number < 80, it prints 4

If 80 < number < 160, it prints 5

If 160 < number.... and so on forever

The pattern is 5 10 20 40 80 160 320 640 1280...

I am pretty new to coding and I'm not sure how to do that, any help is appreciated.

Using the concept of Geometric progression your function can be written as:

import math

def bucket(value):
    return math.ceil(math.log(value/5)/math.log(2))

where 5 is first term of the sequence and the common ratio be 2.

Output:

bucket(321)
7

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