Codingbat has a practice question Under Logic-1, Python. It's called near_10.
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
The solution on their GitHub is given as
def near_ten(num):
within = num%((num/10)*10) if num >= 10 else num
return within in [8,9,0,1,2]
This is accepted as the correct answer and produces a code-check table
However, when I execute this code in a Jupyter Notebook I get varying outcomes
I searched here on S.O. and found an answer by UltraInstinct that worked Python near_ten function/method
Curious if I'm missing something, or if I should contact CodingBat about the issue. Thanks for the input
CodePudding user response:
The solution you provided is indeed false and doesn't work in the slightest. Take a look at the first term ((num/10)*10)
: this evaluates to just num
. This means for all integers greater than 9 your result is num % num
which will always be 0. As well, because this code uses normal division it will convert all terms to floats.
The second solution you provided is correct since all you need is the first no-decimal digit.