Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python divmod() — A Simple Guide with Video
1
Python divmod() — A Simple Guide with Video

Python’s built-in
Code:
divmod(a, b)
function takes two integer or float numbers
Code:
a
and
Code:
b
as input arguments and returns a tuple
Code:
(a // b, a % b)
. The first tuple value is the result of theinteger division
Code:
a//b
. The second tuple is the result of the remainder, also called modulo operation
Code:
a % b
. In case of float inputs,
Code:
divmod()
still returns the division without remainder by rounding down to the next round number.

[Image: divmod-1024x576.jpg]

Usage

Learn by example! Here are some examples of how to use the
Code:
divmod()
built-in function with integer arguments:

Code:
# divmod() with integers >>> divmod(10, 2) (5, 0) >>> divmod(10, 3) (3, 1) >>> divmod(10, 4) (2, 2) >>> divmod(10, 5) (2, 0) >>> divmod(10, 10) (1, 0)

You can also use float arguments as follows:

Code:
# divmod() with floats >>> divmod(10.0, 2.0) (5.0, 0.0) >>> divmod(10.0, 3.0) (3.0, 1.0) >>> divmod(10.0, 4.0) (2.0, 2.0) >>> divmod(10.0, 5.0) (2.0, 0.0) >>> divmod(10.0, 10.0) (1.0, 0.0)
Video divmod()



Syntax divmod()

Code:
Syntax: divmod(a, b) -> returns a tuple of two numbers. The first is the result of the division without remainder a/b. The second is the remainder (modulo) a%b.

Arguments |
Code:
integer
|
The dividend of the division operation.

|
Code:
integer
|
The divisor of the division operation.

Return Value |
Code:
tuple
|
Returns a tupleof two numbers. The first is the result of the division without remainder. The second is the remainder (modulo).

Interactive Shell Exercise: Understanding divmod()

Consider the following interactive code:

https://trinket.io/embed/python/4b2905866a

Exercise: Guess the output before running the code.

But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

[Image: image-1.png]

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners

Exact Mathematical Definition divmod()

You can generally use the
Code:
divmod(a, b)
function with two integers, one integer and one float, or two floats.

Two integers. Say you call
Code:
divmod(a, b)
with two integers
Code:
a
and
Code:
b
. In this case, the exact mathematical definition of the return value is
Code:
(a // b, a % b)
.

Code:
a = 5 b = 2 print((a // b, a % b)) print(divmod(a, b)) # OUTPUT: # (2, 1) # (2, 1)

One integer and one float. Say you call
Code:
divmod(a, b)
with an integer
Code:
a
and a float
Code:
b
. In this case, the exact mathematical definition of the return value is the return value of converting the integer to a float and calling
Code:
divmod(a, float(b))
.

Code:
a = 5.0 b = 2 print((a // b, a % b)) print(divmod(a, b)) # OUTPUT: # (2.0, 1.0) # (2.0, 1.0)

Two floats. Say you call
Code:
divmod(a, b)
with two floats
Code:
a
and
Code:
b
. In this case, the exact mathematical definition of the return value is
Code:
(float(math.floor(a / b)), a % b)
.

Code:
import math a = 5.0 b = 2.0 print((float(math.floor(a / b)), a % b)) print(divmod(a, b)) # OUTPUT: # (2.0, 1.0) # (2.0, 1.0)

Note that because of the imprecision of floating point arithmetic, the result may have a small floating point error in one of the lower decimal positions. You can read more about the floating point trap on the Finxter blog.

Related Tutorial: Floating Point Error Explained

Python divmod() Negative Numbers

Can you use the
Code:
divmod()
method on negative numbers for the dividend or the divisor?

You can use
Code:
divmod(a, b)
for negative input arguments
Code:
a
,
Code:
b
, or both. In any case, if both arguments are integers, Python performs integer division
Code:
a // b
to obtain the first element and modulo division
Code:
a % b
to obtain the second element of the returned tuple. Both operations allow negative inputs
Code:
a
or
Code:
b
. The returned tuple
Code:
(x, y)
is calculated so that
Code:
x * b + y = a
.

Here’s an example of all three cases:

Code:
>>> divmod(-10, -3) (3, -1) >>> divmod(-10, 3) (-4, 2) >>> divmod(10, -3) (-4, -2)
Python divmod() Performance — Is It Faster Than Integer Division // and Modulo % Operators?

There are two semantically identical ways to create a tuple where the first element is the result of the integer division and the second is the result of the modulo operation:
  • Use the
    Code:
    divmod(a, b)
    function.

  • Use the
    Code:
    (a // b, a % b)
    explicit operation with Python built-in operators.

Next, we measure the performance of calculating the elapsed runtime in milliseconds when performing 10 million computations for relatively small integers. Let’s start with
Code:
divmod()
:


Code:
import time import random # Small Operands operands = zip([random.randint(1, 100) for i in range(10**7)], [random.randint(1, 100) for i in range(10**7)]) start = time.time() for i, j in operands: divmod(i, j) stop = time.time() print('divmod() elapsed time: ', (stop-start), 'milliseconds') # divmod() elapsed time: 1.7654337882995605 milliseconds

Compare this to integer division and modulo:

Code:
import time import random # Small Operands operands = zip([random.randint(1, 100) for i in range(10**7)], [random.randint(1, 100) for i in range(10**7)]) start = time.time() for i, j in operands: (i // j, i % j) stop = time.time() print('(i // j, i % j) elapsed time: ', (stop-start), 'milliseconds') # (i // j, i % j) elapsed time: 1.9048900604248047 milliseconds

The result of this performance benchmark is that
Code:
divmod()
requires 1.76 milliseconds and the explicit way of using integer division and modulo requires 1.90 milliseconds for 10,000,000 operations. Thus,
Code:
divmod()
is 8% faster. The reason is that the explicit way performs many duplicate operations to calculate the result of the integer division and the modulo operation which internally uses integer division again. This effect becomes even more pronounced if you use larger integers.

[Image: image-36.png]

Python divmod() Implementation

For integer input arguments, here’s a semantically equivalent
Code:
divmod()
implementation:

Code:
>>> def divmod_own(x, y): return (x // y, x % y) >>> divmod_own(10, 3) (3, 1) >>> divmod(10, 3) (3, 1)

But note that this implementation still performs redundant computations (e.g., integer division) and, therefore, is less efficient than
Code:
divmod()
.

Summary

Python’s built-in
Code:
divmod(a, b)
function takes two integer or float numbers
Code:
a
and
Code:
b
as input arguments and returns a tuple
Code:
(a // b, a % b)
.
  • The first tuple value is the result of theinteger division
    Code:
    a//b
    .

  • The second tuple is the result of the remainder, also called modulo operation
    Code:
    a % b
    .

In case of float inputs,
Code:
divmod()
still returns the division without remainder by rounding down to the next round number.

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post Python divmod() — A Simple Guide with Video first appeared on Finxter.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: