Skip to content

Instantly share code, notes, and snippets.

@tonyskapunk
Created January 15, 2019 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyskapunk/e7c4126e12fa6c5b4baaf5eea00fbdf7 to your computer and use it in GitHub Desktop.
Save tonyskapunk/e7c4126e12fa6c5b4baaf5eea00fbdf7 to your computer and use it in GitHub Desktop.
palindrome
#!/usr/bin/env python
# Write a method palindrome_chain_length which
# - takes a positive number and
# - returns the number of special steps needed to obtain a palindrome.
# The special step is:
# - "reverse the digits, and add to the original number".
# If the resulting number is not a palindrome,
# repeat the procedure with the sum
# until the resulting number is a palindrome.
#
# If the input number is already a palindrome, the number of steps is 0.
#
# Input will always be a positive integer.
#
# For example, start with 87:
#
# 87 + 78 = 165; 165 + 561 = 726; 726 + 627 = 1353; 1353 + 3531 = 4884
#
# 4884 is a palindrome and we needed 4 steps to obtain it, so palindrome_chain_length(87) == 4
import sys
def is_palindrome(num):
if num == int("".join(reversed(str(num)))):
return True
return False
def palindrome_chain_length(num, steps=0):
#print(f'Steps are now: {steps}')
#print(f'Number is now: {num}')
if is_palindrome(num):
return (num, steps)
steps += 1
# Reversing the number
mun = int("".join(reversed(str(num))))
num += mun
r = palindrome_chain_length(num, steps)
return (r[0], r[1])
def main():
if len(sys.argv) != 2:
print("Wrong number of arguments, expected exactly 1")
sys.exit(1)
num = int(sys.argv[1])
print(f'Received: {num}\nCalculating...')
pal = palindrome_chain_length(num)
print(f'Palindrome is {pal[0]}, after {pal[1]} steps')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment