0
\$\begingroup\$

I am trying to write a program where if I call

get_bin_pos(19.4) ==> output as 20
get_bin_pos(13.4) ==> output as 20
get_bin_pos(31.4) ==> output as 40

I wrote something like below, it looks bad, any suggestion in optimizing it ?

Switch statement for this would be more readable, but we don't have a switch in python. So any other way?

def get_bin_pos(self, value):
        if value <= 10:
            return 10
        if value <= 20:
            return 20
        if value <= 30:
            return 30
        if value <= 40:
            return 40
        if value <= 50:
            return 50
        if value <= 60:
            return 60
        if value <= 70:
            return 70
\$\endgroup\$
3
  • 2
    \$\begingroup\$ return (int(value / 10) + 1) * 10 perhaps? \$\endgroup\$ Commented Nov 20, 2017 at 3:14
  • 1
    \$\begingroup\$ return int((value + 10) / 10) * 10 (similar to @vnp's suggestion, but more intuitive in my view) \$\endgroup\$ Commented Nov 20, 2017 at 7:29
  • \$\begingroup\$ @vnp (int(10 / 10) + 1) * 10 == 20... Maybe not the correct method. \$\endgroup\$ Commented Nov 20, 2017 at 16:05

1 Answer 1

4
\$\begingroup\$
  • If you want to ceil, then you want to use math.ceil. This is as easy as:

    \$10 \lceil \frac{value}{10} \rceil\$

  • You may want to make a generic function to ceil within a bound.

  • You can set your somewhat weird limits to the function.
import math


def ceil(number, bound=1):
    return bound * math.ceil(number / bound)


def get_bin_pos(value):
    if value > 70:
        return None
    return ceil(max(value, 1), 10)
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.