-1

I was given a task in python to write a code which contains a function which receives an input number from the user and if it isn't a palindrome - it finds the nearest (lower) palindrome number, for example:

findprevpalindrom(100) to 99

findprevpalindrom(99) to 88

findprevpalindrom(11) to 9

  • We presume the input is int and above 0, so no need to fix that part.
  • Singular numbers are palindrome.
  • I am required to use another function for finding the proper number.

This is what I've done so far. It isn't correct and I'm having a hard time understanding what's next: screenshot

Thanks in advance to all helpers!

helpme
  • 39
  • 1
  • 1
    [Do no post pictures of code, post code as text](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Ani Mar 31 '21 at 16:51

2 Answers2

0
def findprevpalindrom(numb):
    s = str(numb - 1)
    l = len(s)
    if s[:l//2][::-1] > s[(l+1)//2:]:
        top = str(int(s[:(l+1)//2])-1)
    else:
        top = s[:(l+1)//2]
    if len(top) < l/2:
        return int(top + '9' + top[:l//2][::-1]) #tricky part
    else:
        return int(top + top[:l//2][::-1]) #the generic return

The above method should give you the desired output

findprevpalindrom(100) -> 99

findprevpalindrom(99) -> 88

findprevpalindrom(11) -> 9

  • Hi Sagar, how do I go about solving it if I want to use my code? What's problematic in it right now? Am I correct assuming that my problem is in the prev - 1? – helpme Apr 01 '21 at 20:04
0

Watch out, your examples are wrong. Both 99 and 11 are palindrome, so the function (according to the specific) should return respectively 99 and 11.

def is_palindrome(number: int):
    return str(number) == str(number)[::-1]


def findprevpalindrom(number: int):
    assert number > 0, "Cannot find non-positive palindrome!"
    if is_palindrome(number):
        return number
    else:
        return findprevpalindrom(number - 1)

These are assertions that pass without raising exceptions:

assert findprevpalindrom(100) == 99
assert findprevpalindrom(99) == 99
assert findprevpalindrom(98) == 88
assert findprevpalindrom(11) == 11
assert findprevpalindrom(10) == 9
crissal
  • 2,547
  • 7
  • 25
  • Hi crissal, how do I go about solving it if I want to use my code? What's problematic in it right now? Am I correct assuming that my problem is in the prev - 1? – helpme Mar 31 '21 at 22:02