Rafael Knuth <rafael.knuth <at> gmail.com> writes: > > Hej there, > > I wrote a program that converts an integer into a digit sum: > > def DigitSum(YourNumber): > DigitList = [] > YourNumber = str(YourNumber) > for i in YourNumber: > DigitList.append(int(i)) > print(sum(DigitList)) > > DigitSum(55) > > >>> > 10 > > It actually works but I was wondering if that's the only way to solve > the task of converting an integer into a digit sum? I learned from > past conversations on this mailing list that often times there is a > better, more elegant and shorter way to write a program, and I was > wondering if that's the case here. > > Thanks! > > Raf >
Hi Raf, your way is legitimate, but can be improved slightly through the use of comprehensions as others have pointed out (one side note though since you are asking specifically for Python 3.3: you can simplify expressions like sum([int(digit) for digit in str(55)]) to just: sum(int(digit) for digit in str(55)) turning the comprehension into a generator expression.) A different approach avoiding the str conversion and working only in the domain of integer arithmetics would be: def digsum (integer): s = 0 while integer != 0: integer, remainder = divmod(integer, 10) s += remainder return s >From a quick and dirty test, i.e., comparing: for i in range(1000000): a=digsum(i) and for i in range(1000000): a=sum(int(c) for c in str(i)) the arithmetic solution also seems to be a bit faster. Best, Wolfgang _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor