From 70f777aae4f6d4dfd61667ce4e2c573c02741471 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Mon, 8 Feb 2016 14:21:07 +0100 Subject: [PATCH] Happy numbers --- happynumbers.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100755 happynumbers.py diff --git a/happynumbers.py b/happynumbers.py new file mode 100755 index 0000000..f14ee2c --- /dev/null +++ b/happynumbers.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +def happynumbers_step(n): + s = 0 + for c in str(n): + s += int(c)**2 + return s + +def happynumbers(n): + founds = [] + s = n + while True: + founds.append(s) + s = happynumbers_step(s) + if s == n: + return False + elif s in founds: + return False + elif s == 1: + return True + +if __name__ == '__main__': + from sys import argv + if len(argv) > 1: + n = int(argv[1]) + else: + n = 4 + print("%d is a %s number" % (n,"happy" if happynumbers(n) else "unhappy"))