0

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Use floor division by 8 (`//`). Check the output of `9//8` for example – G. Anderson May 21 '21 at 16:22
  • 2
    I think the intention is to realize that the boundary occurs at `num = 8y + 1`.. So by that logic you can use the fact that `y = (num-1)/8` – Chad S. May 21 '21 at 16:22

4 Answers4

1

Try enumerate?

num=32
x=[9,17,25,33,41,48,57]
for nums,data in enumerate(x):
    if data>num:
        y=nums+1
        break
    else:
        pass

print(y)

1

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.

Joffan
  • 1,485
  • 1
  • 13
  • 18
0

Only idea I came up with, was to create a dictionary with ranges as keys.

ranges = {range(0,9):1,range(9,17):2,range(17,25):3,range(25,33):4,range(33,41):5,range(41,49):6,range(49,57):7}
number = 10
for k,v in ranges.items():
    if number in k:
        print(v)

in this case the output is 2

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

You could loop through the conditions like this:

num = 32

limits = (57, 49, 41, 33, 25, 17, 9,) 
# ^ traversing in reverse because then
# the chance that we don't have to go
# through the entire loop is greater.

for possible_y,  limit in zip(range(7, 0, -1), limits):
    # zip takes 2 or more iterables and returns
    # tuples of the current iteration for each iterable
    # so e.g (7, 57,) is returned for the first iteration. 

    if num < limit:
        y = possible_y
        break
else:
    # else after a for loop in Python is only executed if 
    # no break statement was encountered in the outer-
    # most loop.
    y = 8
    
jrbergen
  • 660
  • 5
  • 16