Create an account


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

<div><p class="has-pale-cyan-blue-background-color has-background">Python’s built-in <code>divmod(a, b)</code> function takes two integer or float numbers <code>a</code> and <code>b</code> as input arguments and returns a tuple <code>(a // b, a % b)</code>. The first tuple value is the result of the<a href="https://blog.finxter.com/daily-python-puzzle-integer-division/" title="Python Integer Division [2-Min Tutorial]" target="_blank" rel="noreferrer noopener"> integer division</a> <code>a//b</code>. The second tuple is the result of the remainder, also called <a href="https://blog.finxter.com/python-modulo/" title="Python Modulo" target="_blank" rel="noreferrer noopener">modulo operation</a> <code>a % b</code>. In case of float inputs, <code>divmod()</code> still returns the division without remainder by rounding down to the next round number. </p>
</p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2021/01/divmod-1024x576.jpg" alt="Python divmod() visual explanation" class="wp-image-20392" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2021/01/divmod-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<h2>Usage</h2>
<p>Learn by example! Here are some examples of how to use the <code>divmod()</code> <a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions">built-in function</a> with <strong>integer arguments:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p>You can also use float arguments as follows:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<h2>Video divmod()</h2>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe loading="lazy" title="Python divmod() — A Simple Guide" width="1400" height="788" src="https://www.youtube.com/embed/BUsmyoeAn6g?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Syntax divmod()</h2>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>
<code>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. </code></pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Arguments</strong></td>
<td><code>integer</code></td>
<td>The <strong><em>dividend </em></strong>of the division operation.</td>
</tr>
<tr>
<td></td>
<td><code>integer</code></td>
<td>The <strong><em>divisor </em></strong>of the division operation.</td>
</tr>
<tr>
<td><strong>Return Value</strong></td>
<td><code>tuple</code></td>
<td>Returns a <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide To Python Tuples">tuple </a>of two numbers. The first is the result of the division without remainder. The second is the remainder (modulo).</td>
</tr>
</tbody>
</table>
</figure>
<h2>Interactive Shell Exercise: Understanding divmod()</h2>
<p>Consider the following interactive code:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/4b2905866a" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: </em>Guess the output before running the code.</p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<hr class="wp-block-separator"/>
<h2>Exact Mathematical Definition divmod()</h2>
<p>You can generally use the <code>divmod(a, b)</code> function with two integers, one integer and one float, or two floats. </p>
<p><strong>Two integers. </strong>Say you call <code>divmod(a, b)</code> with two integers <code>a</code> and <code>b</code>. In this case, the exact mathematical definition of the return value is <code>(a // b, a % b)</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 5
b = 2
print((a // b, a % b))
print(divmod(a, b))
# OUTPUT:
# (2, 1)
# (2, 1)</pre>
<p><strong>One integer and one float.</strong> Say you call <code>divmod(a, b)</code> with an integer <code>a</code> and a float <code>b</code>. 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>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 5.0
b = 2
print((a // b, a % b))
print(divmod(a, b))
# OUTPUT:
# (2.0, 1.0)
# (2.0, 1.0)</pre>
<p><strong>Two floats.</strong> Say you call <code>divmod(a, b)</code> with two floats <code>a</code> and <code>b</code>. In this case, the exact mathematical definition of the return value is <code>(float(math.floor(a / b)), a % b)</code>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)
</pre>
<p>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. </p>
<p><strong>Related Tutorial: </strong><a href="https://blog.finxter.com/decimal-pythons-float-trap-and-how-to-solve-it/" title="Decimal: Python’s Float Trap and How to Solve it" target="_blank" rel="noreferrer noopener">Floating Point Error Explained</a></p>
<h2>Python divmod() Negative Numbers</h2>
<p>Can you use the <code>divmod()</code> method on negative numbers for the dividend or the divisor? </p>
<p class="has-pale-cyan-blue-background-color has-background">You can use <code>divmod(a, b)</code> for negative input arguments <code>a</code>, <code>b</code>, or both. In any case, if both arguments are integers, Python performs integer division <code>a // b</code> to obtain the first element and modulo division <code>a % b</code> to obtain the second element of the returned tuple. Both operations allow negative inputs <code>a</code> or <code>b</code>. The returned tuple <code>(x, y)</code> is calculated so that <code>x * b + y = a</code>. </p>
<p>Here’s an example of all three cases:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> divmod(-10, -3)
(3, -1)
>>> divmod(-10, 3)
(-4, 2)
>>> divmod(10, -3)
(-4, -2)</pre>
<h2>Python divmod() Performance — Is It Faster Than Integer Division // and Modulo % Operators?</h2>
<p>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:</p>
<ul>
<li>Use the <code>divmod(a, b)</code> function.</li>
<li>Use the <code>(a // b, a % b)</code> explicit operation with Python built-in operators. </li>
</ul>
<p>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 <strong><code>divmod()</code>:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<p>Compare this to <strong>integer division and modulo</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
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</pre>
<p class="has-pale-cyan-blue-background-color has-background">The result of this performance benchmark is that <code>divmod()</code> 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()</code> 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. </p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="765" height="559" src="https://blog.finxter.com/wp-content/uploads/2021/01/image-36.png" alt="Performance difference divmod() vs Integer Division and Modulo" class="wp-image-20386" srcset="https://blog.finxter.com/wp-content/uploads/2021/01/image-36.png 765w, https://blog.finxter.com/wp-content/uplo...00x219.png 300w, https://blog.finxter.com/wp-content/uplo...50x110.png 150w" sizes="(max-width: 765px) 100vw, 765px" /></figure>
</div>
<h2>Python divmod() Implementation</h2>
<p>For integer input arguments, here’s a semantically equivalent <code>divmod()</code> implementation:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> def divmod_own(x, y): return (x // y, x % y) >>> divmod_own(10, 3)
(3, 1)
>>> divmod(10, 3)
(3, 1)</pre>
<p>But note that this implementation still performs redundant computations (e.g., integer division) and, therefore, is less efficient than <code>divmod()</code>. </p>
<h2>Summary</h2>
<p>Python’s built-in <code>divmod(a, b)</code> function takes two integer or float numbers <code>a</code> and <code>b</code> as input arguments and returns a tuple <code>(a // b, a % b)</code>. </p>
<ul>
<li>The first tuple value is the result of the<a href="https://blog.finxter.com/daily-python-puzzle-integer-division/" target="_blank" rel="noreferrer noopener"> integer division</a> <code>a//b</code>. </li>
<li>The second tuple is the result of the remainder, also called <a href="https://blog.finxter.com/python-modulo/" target="_blank" rel="noreferrer noopener">modulo operation</a> <code>a % b</code>. </li>
</ul>
<p>In case of float inputs, <code>divmod()</code> still returns the division without remainder by rounding down to the next round number.</p>
<hr class="wp-block-separator"/>
<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">Finxter Email Academy</a>:</p>
<p>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!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</p>
</p>
<p>The post <a href="https://blog.finxter.com/python-divmod/">Python divmod() — A Simple Guide with Video</a> first appeared on <a href="https://blog.finxter.com">Finxter</a>. </p>
</div>


https://www.sickgaming.net/blog/2021/01/...ith-video/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016