pythonoptimization

Getting Floor Division and Remainder at same time in 2 separate variables


Is there a python built-in (or just optimized) function to get the floor division and remainder at the same time in two separate variables?

Example:

a, b = 10 divided by 4

Desired results:

a = 2
b = 2

I need this to be an optimized solution.

Performance results:

First piece of code:

for i in range(10000000):
    a, b = divmod(i, 5)
took 3.99 seconds to run

Second piece of code:

for i in range(10000000):
    a = i // 5
    b = i % 5
took 2.56 seconds to run

Remarks:

Read @casevh answer for a more detailed explanation.

tldr: divmod() works better if numbers are big.


Solution

  • Use this. this will help you.

    a,b = divmod(10,2)
    

    it will return both value