Sum of Every Digit of a Number in Python
Inspired by yet another homework question posted in one of Baidu's forum.
此文靈感來自於百度貼吧一問功課帖子。
Python Newbie, ex-C Programmer
#int n = 1952, s = 0; n = 1952; s = 0; #do while (n): s += n % 10; n /= 10; #while (n /= 10); print("%d\n" % s);
Two hours later...
#int n = 1952, s = 0; n = 1952; s = 0; #do while (n): s += n % 10; # need this to be compatible with python 3, I HATE python!!! n = (int)(n/10); #n /= 10; #while (n /= 10); print("%d\n" % s);
Two weeks later...
n = 1952 s = 0 string = "%d" % n for c in string: s += (int)(c) print(s)
Yet another week...
s = 0 for c in str(1952): s += int(c) print(s)
Python Newbie, ex-Lisp Programmer
print (sum (map (int, (list (str (1952))))))
Two days later...
>>> sum(map(int, str(1952))) 17
Python Newbie, ex-Lisp Expert
print (reduce (int.__add__, (map (int, (list (str (1952)))))))
Perl Programmer
$ python -c 'print sum(map(int,str(1952)))'
Python Newbie, ex-Java Programmer
import sys class Accumulator(object): def __init__(self, num): self.setTotal(num) def addNum(self, num): self.checkType(num) tmp = self.getTotal() self.setTotal(tmp + num) def checkType(self, num): if type(num) != int: raise ValueError("num must be number") def getTotal(self): return self._total def setTotal(self, num): self.checkType(num) self._total = num def toString(self): return str(self.getTotal()) class Main(object): def main(self, args): num = 1952 total = Accumulator(0) while num > 0: total.addNum(num % 10) num = int(num / 10) result = total.toString() result = result + '\n' sys.stdout.write(result) sys.exit(0) Main().main(sys.argv)
Hipster, Just Learned List Comprehension
print sum([int(i) for i in str(1952)])
Python Veteran
print sum(int(i) for i in str(1952))
Me, Arty Dude(文藝青年), Python 2 Version
(lambda (i): (sum (map (int ,(list (str (i)))))) (1952))
Yours Truly, again, Python 3 Version
(print ((lambda i: (sum (map (int ,(list (str (i))))))) (1952)))