On Tue, Dec 10, 2013 at 4:06 PM, Asokan Pichai <paso...@talentsprint.com>wrote:
> > > > On Tue, Dec 10, 2013 at 3:09 PM, Rafael Knuth <rafael.kn...@gmail.com>wrote: > >> Hej there, >> >> > I don't know if everyone would consider this more elegant but it's >> > certainly shorter: >> >> Thanks! >> >> >>>> def DigitSum(YourNumber): >> > ... return sum(map(int, YourNumber)) >> > ... >> >>>> DigitSum('55') >> > 10 >> >> I don't understand yet what the "map" function does - can you explain? >> I read the Python 3.3.0 documentation on that topic but I frankly >> didn't really understand it >> http://docs.python.org/3/library/functions.html#map. My search for >> simple code examples using "map" wasn't really fruitful either. >> >> Other than that, I went through each of the 7 alternatives to my >> "Integer to Digit Sum" program you guys sent me, I understand what >> each of those programs does. My favorite one is: >> >> def DigSum (integer): >> s = 0 >> while integer != 0: >> integer, remainder = divmod(integer, 10) >> s += remainder >> print(s) >> >> DigSum(537) >> >> It's really a beautiful, elegant solution IMHO and way better than my >> original code (convert int to string, store each digit in an empty >> list, then convert them back to int and sum them). >> >> If you liked it, I will give you one that uses one less variable :-) > > def digitSum(n): > dsum = 0 > while n > 0: > dsum += n % 10 > n /= 10 > return dsum > > >> Again, thank you all! >> > You are welcome. > > > 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 > Stupid of me not to have mentioned that this Python 2.x only. Sorry
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor