Skip to content

Instantly share code, notes, and snippets.

@nijotz
Created November 21, 2013 21:27
Show Gist options
  • Save nijotz/7589986 to your computer and use it in GitHub Desktop.
Save nijotz/7589986 to your computer and use it in GitHub Desktop.
Figure out if a number is happy
# -*- coding: utf-8 -*
def ishappy_recurse(num):
if num == 1:
print "{} is so happy!".format(num)
digits_str = [str(d) for d in str(num)]
digits_int = [int(d) for d in str(num)]
summ = sum([d * d for d in digits_int])
math_str = '² + '.join(digits_str) + '² = ' + str(summ)
print math_str
ishappy_recurse(summ)
def ishappy_loop(num, max_iterations=10000):
starting_num = num
iterations = 0
while num != 1 and iterations < max_iterations:
iterations += 1
digits_str = [str(d) for d in str(num)]
digits_int = [int(d) for d in str(num)]
num = sum([d * d for d in digits_int])
math_str = '² + '.join(digits_str) + '² = ' + str(num)
print math_str
if num == 1:
print "{} is so happy! :D".format(starting_num)
else:
print "{} is UNHAPPY!! >:(".format(starting_num)
def ishappy(num, **kwargs):
ishappy_loop(num, **kwargs)
if __name__ == '__main__':
import sys
kwargs = {}
if len(sys.argv) > 2:
kwargs['max_iterations'] = int(sys.argv[2])
ishappy(sys.argv[1], **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment