I'm trying to divide number into groups in plain python without importing or the use of if-statements, and get the division into groups + remainder forming one extra group so that 200 / 99 would be 3, And 7 / 3 would be 3, but that 8 / 4 would still be just 2, and 4 / 2 would be 2 etc.. I cannot import anything so it needs to be in plain python.

I tried storing the numbers from inputs from user into variables and dividing them, and then adding one. I also tried // and adding 1 but I cannot get it to work.

3

There are 3 best solutions below

1
Grismar On

How about this:

a, b = 200, 99
result, remainder = a // b + int(bool(a % b)), a % b

This computes the result by performing an integer divide a // b and computing the remainder a % b. Converting an integer value to a boolean is False for 0 and True for any other value, and converting that back to an integer gives you the value you want to add to the result. The remainder is computed again to assign it, if you need it.

As user @markransom commented, the conversion to int() isn't even necessary, as bool already 'is' an integer type:

>>> isinstance(True, int)
True

So, this works (although it may be considered a bit less readable):

a, b = 200, 99
result, remainder = a // b + bool(a % b), a % b

If you're using a modern version of Python and really want it to be short, this also works:

result = a // b + bool(remainder := a % b)

This uses the walrus operator to assign the remainder when it is first computed, avoiding having to compute it twice as well.

4
tdelaney On

Python boolean operations short-circuit and return the last value evaluated and you can use that to convert a non-zero remainder to 1 for addition to a quotient

def group_me(dividend, divisor):
    quotient, remainder = divmod(dividend, divisor)
    return quotient + (remainder and 1 or 0)

print(group_me(200, 99))
print(group_me(7, 3))
print(group_me(8, 4))

Output

3
3
2

If remainder is non-zero, remainder and 1 short-circuits and returns 1. Otherwise, the or now becomes 0 or 0, which retains its last value 0.

0
Z Li On

You could do an if statement mathematically without using if itself:

n, d = 200, 99
x, y = n/d, n//d + 1
result = int((x%1 == 0) * x + (x%1 != 0) * y)

Essentially it is condition * answer 1 + (1 - condition) * answer 2. Then it switch to whichever answer depending on condition being 1 or 0.