GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Write a Python function to determine if an integer value is even.

Constraints:

Use of multiplication, modulo, or division operators is prohibited.

One of the approaches known by bitwise operators is as follows:

def is_even(k):
    """(int) -> bool

    Returns True if k is even,
    else False

    >>>is_even(6)
    True
    >>>is_even(3)
    False
    """
    return (k & 1) == 0

print is_even(6)
print is_even(3)

I would like to know if anyone can suggest some python specific alternative solution to this problem.

asked Sep 16, 2015 by akjlucky4all

2 Answers

One thought is as follows:

def is_even(k):
    """(int) -> bool
 
    Returns True if k is even,
    else False
 
    >>>is_even(6)
    True
    >>>is_even(3)
    False
    """
    return ((-1)**k) == 1
 
print is_even(6)
print is_even(3)

By this,I wanted to introduce the "exponentiation" operator available in python which was missing in C and C++.

answered Sep 16, 2015 by akjlucky4all
def is_even(k):
    i = 0
    while i<k:
        i += 2
    
    return i==k
 
print is_even(6)
print is_even(3)

May not be good, but an alternate solution :)

answered Sep 16, 2015 by learner
...