Reputation: 27
I have to write a function to find if a given number (num) within 2 of a multiple of 10. I use modulus (%) to get the remainder, but it doesn't seem to be working quite right. Help?
def nearten(num):
if num%10<=2:
return True
elif num%10>2:
return False
Upvotes: 0
Views: 4965
Reputation: 21
This method also works, just returning a bool value by using comparison operators in a single line to check both 'sides' of the cases:
def near_ten(num):
return (num % 10 <= 2 or num % 10 >= 8)
Upvotes: 0
Reputation: 67
This works:
def near_ten(num):
return num%10 <= 2 or num%10 >= (10 - 2 )
Upvotes: 1
Reputation: 19
Here is a little help:
def near_ten(num):
return num % 10 in [0,1,2,8,9,10]`
can also be:
return 0 <= (num % 10) <= 2 or 8 <= (num % 10) <= 10
Upvotes: 1
Reputation: 21
You can use Ternary operator and check for if num
is within 2 of multiple of 10:
def near_ten(num):
return True if num%10<3 or num%10>7 else False
Upvotes: 2
Reputation: 19
You can write this code as:
def near_ten(num):
a = num % 10
return 2 >= a or 8 <= a
Upvotes: 1
Reputation: 11
def near_ten(num):
if num%10<=2 :
return True
elif num%10 >=8:
return True
else:
return False
Upvotes: -1
Reputation: 77837
Most of all, you only checked to see whether the "ones" digit is 0, 1, or 2 -- you missed 8 and 9.
As a styling note, don't check a boolean expression and then hard-code the result you just found. Your function, as currently written, reduces to this:
def nearten(num):
return num%10 <= 2
Do you see how that works? First of all, the elif check doesn't give you any new information: you already know that the result must be >2 when you get past the if condition.
Then, your statement reads like
if this condition is true, return true
otherwise, we know it's false; return false.
That's redundant. You have a True/False value sitting right in your program's hand -- just return that one, instead of using a constant.
REPAIR ...
I'll leave this as an exercise for the student: "within" 2 means that you have to check both sides, so you have to pick up the cases where the ones digit is 8 or 9. Can you write the expression to do that?
Upvotes: 2