On Mon, Dec 9, 2013 at 1:38 PM, Rafael Knuth <rafael.kn...@gmail.com> wrote:
> 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. > Why extract the digit and then store it and then sum it? def digitSum(n): return sum([int(digit) for digit in str(n)]) Or def num2Digits(n): return [int(ch) for ch in str(n)] def digitSum(n): return sum(num2Digits(n)) Asokan Pichai "So, if I look into my foggy crystal ball at the future of computing science education, I overwhelmingly see the depressing picture of "Business as usual". The universities will continue to lack the courage to teach hard science, they will continue to misguide the students, and each next stage of infantilization of the curriculum will be hailed as educational progress." Edsger W Dijkstra in Dec 1988, in an article titled "on the cruelty of really teaching Computer Science" Link: http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor