Jack
Jack

Reputation: 31

I want to write a function in python which returns true if all the digits are even

The function is all_even in which you input an int and it returns bool. It returns true if all the digits are even. e.g. all_even(2224) gives true and all_even(1362) gives false.

I wrote the code but it is not working properly.

This is what I have:

def is_very_even(num: int) -> bool: 
    even = False
    strnum = str(num)
    for ch in strnum:
       if int(ch)% 2==0:
          even = True
    return even

The code gives true even if the num has a single even num and the rest are odd e.g all_even(231) is true which is supposed to be false. Can somebody tell me what is wrong with it.

Upvotes: 2

Views: 1762

Answers (3)

Alain T.
Alain T.

Reputation: 42143

You could use a recursive approach (without converting to a string):

def allEven(N): return True if N==0 else N%2==0 and allEven(N//10)

output:

allEven(246) # True   
allEven(123) # False   

Note that the issue with your function is that you set even to True as soon as you encounter an even digit. If there is an odd digit after that, your even variable remains True. This will tell you that "at least one" digit is even, not that they are all even.

Upvotes: 3

Alexander Kosik
Alexander Kosik

Reputation: 669

I would solve it like this:

def is_very_even(s) -> bool:
    return all(int(x) % 2 == 0 for x in str(s))

This converts every character to an integer and checks if it is even with modulo. This is processed in a so called generator expression.

Then we use the builtin all method to check if the generator delivers only True values.

Upvotes: 1

Iftieaq
Iftieaq

Reputation: 1964

You are checking if all the numbers are even. So first assume that it's true, all the numbers are even and set even = True. Then check if there is any odd number in the string. If there is, then set even = False

Now, if there is any odd number in the string, even will be False and therefore we can verify it.

def is_very_even(num: int) -> bool: 
    even = True
    
    strnum = str(num)
    for ch in strnum:
       if int(ch)% 2 !=0:
          even = False
          
    return even

This code can also be improvised like this. We don't need to keep checking if we found a single odd number. We can just return false immediately. And if all the numbers checks out but none returns false, then it must be an all even string.

def is_very_even(num: int) -> bool: 
    for ch in str(num):
       if int(ch)% 2 !=0:
          return False
          
    return True

Upvotes: 2

Related Questions