[Tutor] newbie looking for code suggestions
Sean 'Shaleh' Perry
shalehperry@attbi.com
Sat, 21 Sep 2002 22:24:42 -0700
On Saturday 21 September 2002 22:12, Bob Roher wrote:
>
> #This function will take an integer as input and return the sum of
> #its digits.
> def sum_of_digits(in_string):
> sum =3D 0
> t =3D 0
> for n in in_string:
> t =3D int(n)
> sum =3D 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=20
each char in the string and put it in a new list:
>>> s =3D '1024'
>>> map(int, s)
[1, 0, 2, 4]
reduce then walks this new list and calls operator.add on it.
>
> One thing I would like to do is be able to have the user re-enter
> digit_total if they enter one that is too big without re-running the
> program. I tried a few things, but am having trouble passing control b=
ack
> to the main while loop if I add another prompt in there. I would also =
like
> to compute max_possible independently so that I could run all possible
> digit_totals for a range, but I think it would have to run through the
> entire range to compute that first. Sorry if I am confusing you, I kno=
w
> what I want it to do, but I'm finding it hard to describe.
I often find that if I sit down away from the computer and sketch out the=
plan=20
things make more sense. Do not write in python code, just ideas or psued=
o=20
fragments.
Any time we learn something new we also have to learn a vocabulary. =20
Mechanics, doctors, knitting circles, etc all have their jargons.
This is actually a pretty good program that has several places for you to=
=20
learn new things.