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

Time:08-01

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.

CodePudding user response:

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
  • Related