-1

This is for an assignment. We have to translate some provided java code into Python. Most of it was simple however the last bit is messing with my head. The whole code is a menu with one of the options being 'To display Palindromes up to 1000'. They're wanting a translation rather than a re-write - I'm sure there is a million ways to do it. What am I getting wrong in the method part ...

    def isPalindrome(n):
        str_n = str(n)
        reverse = ""
        for i in range(len(str_n)-1, -1, -1):
            reverse = reverse + str_n[i]
            result = str_n == reverse
            return result

there is some other menu code here ......

    elif option == 3:
        print("PALINDROMES")
        for i in range(0, 1000):
            if isPalindrome(i):
                print(i)
            break

3 Answers3

2

As far as I understand your question you want to check if the numbers is palindromes? Such as 11 is but 13 is not?

Anyway the easiest way is to use [::-1], which will reverse a list or string, so you can code like:

def is_palindrome(text):
    if text == text[::-1]:
        print(f"({text} is a palindrome!)")
rustyhu
  • 1,912
  • 19
  • 28
Asbjorn
  • 31
  • 2
  • It needs to print all the palindromes in the (1, 1000) range. It also has to use this basic format ... I just think I have something wrong with in it .... – SingerNZ Oct 04 '21 at 08:21
0

You just have to find a way to reverse the given string, if its number you need to convert it into string then do it. here is one of the way to reverse string

a="Hello"
s=""
for i in a:
    s=i+s
print(s)

using the above reversing method in your case it will be

def isPalindrome(n):
    str_n = str(n)
    reverse = ""
    for i in str_n:
        reverse = i + reverse
    if(reverse==str_n):
        #palindrome
        return True
    else:
        #not palindrome
        return False
print(isPalindrome(111))

Output: True

Aviroxi
  • 115
  • 1
  • 9
0

All sorted now .. thanks guys .... I ended up with this - it works and follows our assignment task :D

    def isPalindrome(n):
        str_n = str(n)
        reverse = ""
        for i in range(len(str_n)-1, -1, -1):
            reverse = reverse + str_n[i]
        if(reverse == str_n):
            return True

    print("PALINDROMES")
    for i in range(0, 1000):
        if isPalindrome(i):
           print(i)