I’m stuck on a problem test.
The prompt is:
A palindrome is a word, number, phrase, or another sequence of characters which
reads the same backward as forward, such as madam, racecar, or the number
10801.What is the sum of all numeric palindromes that are less than 10,000?
My code so far is:
def is_numeric_palindrome(number):
"""
:param number: an integer
:return: true if number is a numeric palindrome
"""
number_as_string = str(number)
number_digit_length = len(number_as_string)
for i in range(0, int(number_digit_length / 2)):
# print(i)
# print(f"number_as_string[i]={number_as_string[i]},"
# f" number_as_string[:i]={number_as_string[number_digit_length - i - 1]}")
if not number_as_string[i] is number_as_string[number_digit_length - i - 1]:
return False
return True
def sum_numeric_palindromes(upper_limit):
"""
:param upper_limit: maximum number
:return: the sum of all numeric palindrome between 0 and upper_limit (upper_limit not included)
"""
palindrome_sum = 0
# upper limit not included
for i in range(0, upper_limit - 1):
if is_numeric_palindrome(i):
palindrome_sum += i
return palindrome_sum
I’ve tried, with and without counting single digit numbers as palindromes.
I get either 535041 or 534996 but both options are rejected.
What am I doing wrong??
>Solution :
From the documentation of range you can see that the last item is excluded so the upper_limit - 1 is a bug, also is is a weird operator that does not behave as you expect, use == instead in most cases, in your case != (different than) is the best choice. Tell me if the code is correct after fixing both possible sources of the bug.