patternpythonModerate
Return True if num is within 2 of a multiple of 10
Viewed 0 times
returntruewithinmultiplenum
Problem
Is there a way to make my code simpler/more pythonic?
Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod
near_ten(12) → True
near_ten(17) → False
near_ten(19) → True
Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod
near_ten(12) → True
near_ten(17) → False
near_ten(19) → True
def near_ten(num):
a = num % 10
if (10 - (10-a)) <= 2 or (10 - a) <= 2:
return True
else:
return FalseSolution
You could simplify your code to make it faster and also avoid the '
Here's another version: (Thanks to the comment of @mkrieger1)
I think the name of the function is misleading. Maybe you should rename it to something like:
if-else' construct:def near_ten(num):
a = num % 10
return 8 = aHere's another version: (Thanks to the comment of @mkrieger1)
def near_ten(num):
return not(2 < (num % 10) < 8)I think the name of the function is misleading. Maybe you should rename it to something like:
near_multiple_of_ten(num)Code Snippets
def near_ten(num):
a = num % 10
return 8 <= a or 2 >= adef near_ten(num):
return not(2 < (num % 10) < 8)Context
StackExchange Code Review Q#96467, answer score: 12
Revisions (0)
No revisions yet.