Home > Back-end >  What the most Pythonic way for implementing a Numeric-Range-Based Switch Case condition?
What the most Pythonic way for implementing a Numeric-Range-Based Switch Case condition?

Time:10-06

I want to understand the most pythonic way of implementing a Numeric-Range-Base switch case.

Consider the below function as an example to provide suggestions.

def bucket(input_number):
    if input_number <= 29:
        bucket = 1
    elif 29 < input_number <= 59:
        bucket = 2
    elif 59 < input_number <= 89:
        bucket = 3
    elif 89 < input_number <= 119:
        bucket = 4
    elif 119 < input_number <= 149:
        bucket = 5
    elif 149 < input_number <= 179:
        bucket = 6
    elif 179 < input_number <= 209:
        bucket = 7
    elif 209 < input_number <= 239:
        bucket = 8
    elif 239 < input_number <= 269:
        bucket = 9
    elif 269 < input_number <= 299:
        bucket = 10
    elif 299 < input_number <= 329:
        bucket = 11
    elif 329 < input_number <= 359:
        bucket = 12
    elif input_number > 359:
        bucket = 13
    else:
        bucket = 0
    return bucket

Please note:

  • Do not assume an equation or logic can be built for the ranges.

CodePudding user response:

You can divide by 30 like below:

def bucket(input_number):
    if input_number > 359:
        return 13
    elif input_number < 0:
        return 0
    return input_number // 30   1

CodePudding user response:

I don't know about being "pythonic" or runtime-effectivness, but this looks like a nicer way:

bucket_dict = {29: 2, 59: 3, 89: 4, 119: 5, ...}
def bucket(input_number):
    answer = 1 # number to return if input_number is smaller than the lowest value
    for k in sorted(bucket_dict.keys()):
        if input_number <= k:
            return answer
        answer = bucket_dict[k]
    return 13 # number to return if input_number is larger than the highest value
  • Related