-1

I want the final number as returned by the function, the following code is running, but not returning the correct value, the correct value is printed by the print statement above return satatement, how can return it ?? the correct answer is 22. but 13 is too printed.

def palindrome(num):
    num = num+1
    num = str(num)
    if num[::-1]!=num:
        palindrome(int(num))
    else:
        print(int(num))
    return int(num)

palindrome(12)

>RESULT---
22
13
busybear
  • 10,194
  • 1
  • 25
  • 42
Arshad Shaikh
  • 23
  • 1
  • 4

3 Answers3

0

Your recursive function returns 13 because this is the result of the first call to your function. The other iterations from your recursion are lost since you don't save it in your recursive call to palindrome.

You'll want to set your call to palindrome as your return also:

if num[::-1] != num:
    return palindrome(int(num))
busybear
  • 10,194
  • 1
  • 25
  • 42
0

Seems that this could be done in a better way.

def palindrome(num):
    if str(num) == str(num)[::-1]:
        print(num)
        return num
    else:
        palindrome(num+1)
busybear
  • 10,194
  • 1
  • 25
  • 42
dmg2
  • 38
  • 5
  • Although this prints the correct number, it doesn't return anything. – busybear Dec 29 '18 at 05:08
  • It returns num as a summary to the fulfilled condition. – dmg2 Dec 29 '18 at 05:18
  • Your solution was much better, though. – dmg2 Dec 29 '18 at 05:19
  • It's essentially the same actually--you've just flipped the condition in the if statement. But you do need to have `return palindrome(num+1)` in your `else` clause for it to return the correct value. Otherwise, it has the same problem as the original post. – busybear Dec 29 '18 at 05:27
0
a = int(input("enter the no. of choices"))

for i in range(a):
    b = int(input("enter all no."))

    for j in range(b , 10000000000000000):
        count = 0
        pal = str(j)
        b += 1
        if (pal == pal[::-1]):
            print(j)
            break 
        else:
            continue
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • 1
    Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. – ChrisGPT was on strike May 07 '20 at 19:39