Solution:
def reverse_int(N):
"""
Returns reverse of N if it's a positive integer. Otherwise returns -1.
"""
if N <= 0:
return 0
R = 0
while N > 0:
R = R * 10 + N % 10
N = N // 10
return R
def palindrome(N):
"""
Returns True if N is a positive integer and a palindrome. Otherwise
returns False.
"""
if N <= 0:
return False
return N == reverse_int(N)
def palindrome_generator():
"""
Reads in a positive integer from the user and informs him if the integer
is a palindrome or not. If it is not, applies the standart procedure
to obtain a palindrome
"""
while True:
try:
N = int(input('Enter a positive integer: '))
if (N <= 0):
raise ValueError()
if (palindrome(N)):
print('\n{} is a palindrome.\n'.format(N))
else:
print('\n{} is not a palindrome.'.format(N))
print('Generating a palindrome....\n')
iters = 0
while True:
N = N + reverse_int(N)
iters += 1
print('{}\n'.format(N))
if (palindrome(N)):
break
print('{} iterations were needed to get to a palindrome.\n'
.format(iters))
while True:
again = input('Do it again? [y/n] ')
if again in {'y', 'n'}:
break
else:
continue
if again is 'y':
continue
elif again is 'n':
print('Goodbye!')
break
except ValueError:
print("That is not a positive integer!")
Comments
Leave a comment