'Enter an integer and find all palindromes lesser than or equal to the given number
I do not understand why my code is not working, could anyone help me with this one? It is supposed to print a list of palindromes (numbers that are equal to themselves if read backwards) lesser than or equal to the input. When I try to execute it, it writes: /bin/sh: python: command not found.
w = input('Enter a number: ')
n = int(w)
g = []
for n in range(n, 0, -1):
r = 0
while n != 0:
a = n % 10
r = r * 10 + a
n //= 10
if n == r:
g.append()
print(g)
Solution 1:[1]
You're almost there. Actually your if n == r: is always computing like if 0 == r:. Hence, in your for loop assign your n to a temp variable. Try this:
w = input('Enter a number: ')
n = int(w)
g = []
for n in range(n, 0, -1):
temp = n
r = 0
while n != 0:
a = n % 10
r = r * 10 + a
n //= 10
if temp == r:
g.append(temp)
print(g)
Solution 2:[2]
You can use the following solution, which is simpler than using a while loop:
n = int(input("Enter a number:\n"))
g = []
for i in range(0, n+1):
if str(i)==str(i)[::-1]:
g.append(i)
print(g)
Solution 3:[3]
I don't think your code works anyway. Here is another way to find palindromes less than w:
w = input('Enter a number: ')
n = int(w)
palindromes = []
for i in range(n+1):
if str(i) == str(i)[::-1]:
palindromes.append(i)
print(palindromes)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Nin17 |
