HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Return True if num is within 2 of a multiple of 10

Submitted by: @import:stackexchange-codereview··
0
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

def near_ten(num):

    a = num % 10
    if  (10 - (10-a)) <= 2 or (10 - a) <= 2:
        return True
    else:
        return False

Solution

You could simplify your code to make it faster and also avoid the 'if-else' construct:

def near_ten(num):
    a = num % 10
    return 8 = a


Here'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 >= a
def near_ten(num): 
    return not(2 < (num % 10) < 8)

Context

StackExchange Code Review Q#96467, answer score: 12

Revisions (0)

No revisions yet.