[Tutor] product of all arguments passed to function call

Manprit Singh manpritsinghece at gmail.com
Mon May 31 10:21:36 EDT 2021


 Dear sir,

Coming to the same question , of finding the product of all arguments
passed to a function call . Actually I have seen so many times when getting
replies from python mailing list, those replies other than from you are
more focussed on using modules that are part of  python standard library.
My question is, if i had to perform the same task (finding the product of
argument in function call )  in a real world program, what should i choose
? a solution without using those modules or it will be better using those
modules?

Solution without using module (as given by you in previous mail):
def product(*x):
    result = 1 if x else 0
    for n in x:
      result *= n
    return result

Solution using python standard library modules :

>>> from functools import reduce
>>> from operator import mul
>>> def prod_num(*x):
           if not x or 0 in x:
               return 0
          else:
              return reduce(mul, x)

I feel there are overheads while you are importing , so better avoid using
this way...
I raised this question because sometime back, i saw one of my friend using
re module with string for very small problem that was even easy to handle
with string methods, i suggested him not to use re module for it, later on
he agreed. So what is the real picture ? what should i adopt ?

Need your guidance

Regards
Manprit Singh


On Mon, May 31, 2021 at 3:50 PM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 31/05/2021 10:56, Manprit Singh wrote:
> > Dear sir ,
> > Consider a problem where i have to find the product of all arguments
> passed
> > to function call , where the function must be capable of accepting any
> > number of arguments : My approach will be as follows :
> >
> > def product(x, *y):
> >     for ele in y:
> >         x *= ele
> >     return x
>
> You solution works for the case where at least 1 argument is passed.
> What if none are passed? A small change suffices:
>
> def product(*x):
>     result = 1 if x else 0
>     for n in x:
>       result *= n
>     return result
>
> If you don't like returning zero for an empty list you could
> raise an exception instead - ValueError perhaps?.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list