How to calculate a mod b in Python?

Python

Python Problem Overview


Is there a modulo function in the Python math library?

Isn't 15 % 4, 3? But 15 mod 4 is 1, right?

Python Solutions


Solution 1 - Python

There's the % sign. It's not just for the remainder, it is the modulo operation.

Solution 2 - Python

you can also try divmod(x, y) which returns a tuple (x // y, x % y)

Solution 3 - Python

>>> 15 % 4
3
>>>

The modulo gives the remainder after integer division.

Solution 4 - Python

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.

Solution 5 - Python

Why don't you use % ?


print 4 % 2 # 0

Solution 6 - Python

I don't think you're fully grasping modulo. a % b and a mod b are just two different ways to express modulo. In this case, python uses %. No, 15 mod 4 is not 1, 15 % 4 == 15 mod 4 == 3.

Solution 7 - Python

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHickView Question on Stackoverflow
Solution 1 - PythoneduffyView Answer on Stackoverflow
Solution 2 - PythonuolotView Answer on Stackoverflow
Solution 3 - PythonBill the LizardView Answer on Stackoverflow
Solution 4 - PythonMerijnView Answer on Stackoverflow
Solution 5 - PythonGeoView Answer on Stackoverflow
Solution 6 - PythonUnsignedByteView Answer on Stackoverflow
Solution 7 - PythonNehal PawarView Answer on Stackoverflow