Odp: Creating variables on the fly...

Tomek Lisowski Lisowski.Tomasz at sssa.nospam.pl
Fri Apr 7 00:23:52 EDT 2000


U¿ytkownik Joachim Kaeber <kaeber at gmd.de> w wiadomooci do grup dyskusyjnych
napisa³:38E8EFF0.D71D0415 at gmd.de...
> Hi,
>
> what about this:
>
> def add(*args):
>    sum=0
>    for arg in args:
>      sum=sum+arg
>    return sum
>
> add(1,2,3,4)
> => 10
>
> add (1,2,3,4,5,6,7)
> => 28

Why not:

def add(*args):
  return reduce(lambda x, y: x+y, args)

I am not completely sure, but it may be faster, than a Python for loop

Tomasz Lisowski

>
>
> Matthew Hirsch wrote:
> >
> > Hi All,
> >
> > Let's say I have four variables:
> >
> > a=1
> > b=2
> > c=3
> > d=4
> >
> > And I have a function that adds these variables together:
> >
> > def add(a,b,c,d):
> >    return a+b+c+d
> >
> > But now let's say I have twenty variables that I want to add together.
> > This function will no longer work.  I would have to rewrite it as
> > a+b+c+d+e+f+g+...+(20th letter).  Is there a way to dynamically create a
> > variable name?  So that my add function can automatically determine how
> > many variable names to create and then add the values together.  In
> > other words, I'd ideally like something like:
> >
> > def add(number_of_variables):
> >    return a+b+c+...+(letter corresponding to number_of_variables)
> >
> > Thanks for your help,
> >
> > Matt
>
> --
> Joachim Kaeber (kaeber at gmd.de) (http://imk.gmd.de/~kaeber)
> GMD - Forschungszentrum Informationstechnik GmbH
>     - German National Research Center for Information Technology
> Schloss Birlinghoven                    email: kaeber at gmd.de
> D-53757 Sankt Augustin 1, Germany       phone: (+49 2241) 14-2546




More information about the Python-list mailing list