mardi 5 octobre 2021

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

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.

Aucun commentaire:

Enregistrer un commentaire