pythonif-statementsimplifysimplification

How to simplify long if/elif statement when using comparison


I am trying to simplify this:

if num < 9:
    y = 1
elif num < 17:
    y = 2
elif num < 25:
    y = 3
elif num < 33:
    y = 4
elif num < 41:
    y = 5
elif num < 49:
    y = 6
elif num < 57:
    y = 7
else:
    y = 8

I haven't found a way to do this yet - can someone help me?


Solution

  • Crossing a sorted set of arbitrary boundaries could be done with:

    all_bounds = [9,17,25,33,41,49,57]
    y = len(all_bounds) + 1     # case when all tests fail
    for ix, bound in enumerate(all_bounds):
        if num < bound:
            y = ix + 1
            break
    

    As noted in comments, if there is rule to how the boundaries are derived then better to use that - but only if it is a clear rule, preferably with some understanding of how it came about. Don't force-fit a pattern on arbitrary data.

    For a large set of boundary values I would search for the correct value with a binary chop; for this example it's not worthwhile.