[Tutor] newbie looking for code suggestions
Bob Roher
shiska@swbell.net
Sun, 22 Sep 2002 23:58:39 -0500
> #This function will take an integer as input and return the sum of
> #its digits.
> def sum_of_digits(in_string):
> sum = 0
> t = 0
> for n in in_string:
> t = int(n)
> sum = sum + t
> return sum
>
def sum_of_digits(in_string):
return reduce(lambda x,y: int(x) + int(y), in_string)
is another approach.
Here's another without the lambda:
def sum_of_digits(in_string):
import operator
return reduce(operator.add, map(int, in_string))
What this does is call 'map(int, in_string)' which call the function 'int'
on
each char in the string and put it in a new list:
>>> s = '1024'
>>> map(int, s)
[1, 0, 2, 4]
reduce then walks this new list and calls operator.add on it.
Thanks for the intro to reduce, lamda, and map. I did a little reading on
those today, but it will take me a while to fully understand them. I want
to
do some testing to see which function will execute the fastest when I get
time.