Tutorial :Avoid IF statement after condition has been met



Question:

I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible.

I have an if condition to test the divisor value in order to avoid the div by zero, but I am wondering that there is a performance impact that evaluating this if will have for each run in subsequent loops, especially since I know it's of no use anymore.

How should this be coded? in Python?


Solution:1

I would wrap your call in try/except blocks. They are very cheap in python, and cost about as much as a pass statement if an exception isn't thrown. Python is designed so that you should make your calls and parse any errors instead of always asking permission.

Example code:

def print_divide(x,y):      try:          print x/y      except ZeroDivisionError:          pass  


Solution:2

Don't worry. An if (a != 0) is cheap.

The alternative (if you really want one) could be to split the loop into two, and exit the first one once the divisor gets its value. But that sounds like it would make the code unnecessarily complex (difficult to read).


Solution:3

I'm with Thilo: I think it should be pretty cheap.

If you really care, you should time the code and find out whether the slight overhead is unacceptable. I suspect not.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »