[Tutor] newbie looking for code suggestions

Magnus Lycka magnus@thinkware.se
Mon, 23 Sep 2002 12:06:38 +0200


I'll just make two notes about the first function:

At 00:12 2002-09-22 -0500, Bob Roher wrote:
>#This function will take an integer as input and return the sum of
>#its digits.
>def sum_of_digits(in_string):

I'd change this to

def sum_of_digits(number):
     in_string = str(number)

to make the function more resilient. Then it will work if
people call it with sum_of_digits(123) as well. It might not
matter a lot in this small program, but in general, I think
that it's better (in a dynamic language such as Python, where
it's possible) to let the function which is actually concerned
with calculating digits to make this conversion, since it's a
pure technicality. From the point of the caller, you typically
have an integer that you want to sum up digits in. I mean,
this is a matematical exercise rather than a string exercise.
You just happen to use some string functions to implement it.

>     sum = 0
>     t = 0

t=0 is pointless. Remove that line.

>     for n in in_string:
>         t = int(n)
>         sum = sum + t
>     return sum




-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se