[Tutor] cross sum toying
Gregor Lingl
glingl at aon.at
Wed Oct 8 14:13:44 EDT 2003
Lloyd Kvam schrieb:
> Not sure why you're unhappy with version 4. It can be split into a
> digit generator and a summer:
>
> >>> def digit_generator(a,base=10):
> ... a = abs(a)
> ... while a:
> ... a,d = divmod(a,base)
> ... yield d
>
> (import operator)
> >>> def cross_sum(a):
> ... return reduce(operator.add,digit_generator(a),0)
Very interesting, very nice!
When working with Python 2.3, I can use the now built in sum:
def cross_sum5(a):
return sum([digit for digit in digit_generator(a)])
Thanks for the idea!
I've added this to my collection.
BTW, I was not really unhappy but interested in different
ways to handle this problem.
Maybe the cross sum zoo will continue growing ...
... although there should be one -- and preferably only one --
obvious way to do it? ;-)
Regards, Gregor
More information about the Tutor
mailing list