In my last post I wrote a program to print the Collatz Conjecture for a particular number. In this program I had to check if the number is odd or not(even). For my next program I will need to do this check again so I have decided to write a very short function to check if a number is odd, the algorithm the function is simply:
f(n)= \begin{cases} true &\text{if } n\%2\neq 0 \\ false &\text{otherwise} \end{cases}
In structured English this gives the algorithm:
if not n % 2 = 0 then
return True
else
return False
Translated into Python this gives the function:
def isodd(n): if not (n%2==0): return True else: return False
A better question however would be is even? with this function all we need to return is the boolean result of n%2==0, giving:
def iseven(n): return n%2==0
Less code is always better. We can now save this code in a separate file which i have decided to call myfuncs.py. Now we can simply import this function into any project using:
from myfuncs import iseven
The updated Collatz function would be:
def collatz(n): if n == 1: return 1 elif iseven(n): return n / 2 else: return (3 * n) + 1