Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sum of numeric palindromes

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading