[Tutor] cross sum toying

Lloyd Kvam pythontutor at venix.com
Wed Oct 8 13:27:04 EDT 2003


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)

Both versions 3 and 4 can be easily generalized to support other number bases.

I added a 0 to initialize reduce, the other alternative I considered was to
have an else with the while in the generator to always produce a (leading) zero.
	else:
		yield 0

Hope this helps.

Gregor Lingl wrote:

> Hi!
> 
> Within one hour of cross sum toying with Python 2.3 ;-)
> I came up with four functions for calculating the crossum
> of a nonnegative integer:
> 
> def cross_sum4(a):
>    # drawback: (almost) classical
>    s = 0
>    while a:
>        a, digit = divmod(a, 10)
>        s += digit
>    return s
> 
> 
> Do you have a more beautiful, a substantially
> different or even a more Pythonic one?
> 
> Gregor
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list