Answer to Question #65140 in Python for andy

Question #65140
Add 1635 and its reverse, 5361, to get 6996
• A function called palindrome that has a single parameter N (a positive integer) and returns True if N is a palindrome and False otherwise.
• A function called reverse int that has a single parameter N (a positive integer) and returns its reverse.
• A function called palindrome generator without any parameters which reads in a pos- itive integer from the user and informs him if the integer is a palindrome or not. If it is not, apply the procedure described above to obtain a palindrome. This should be done by making appropriate calls to the functions palindrome and reverse int. The function should print out every intermediate integer generated by the procedure until the final palindrome. It should also state the number of iterations that were required to go from the original integer to the palindrome. You should allow the user to repeatedly enter integers. See the sample runs for some examples.
1
Expert's answer
2017-02-09T12:13:51-0500
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!")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS