[Tutor] product of all arguments passed to function call
Peter Otten
__peter__ at web.de
Tue Jun 1 01:50:23 EDT 2021
On 31/05/2021 12:19, Alan Gauld via Tutor wrote:
> def product(*x):
> result = 1 if x else 0
> for n in x:
> result *= n
> return result
The result of an empty product is usually the "multiplicative identity",
i. e. 1 in the majority of cases. If there were a result for the
no-arguments case I'd pick that.
Another problem with your implementation is that you are making
assumptions about the arguments, thus defeating Python's duck typing. I
admit the example is a bit farfetched, but anyway:
>>> class S(str):
def __imul__(self, other):
return S(f"{self}*{other.strip()}")
>>> def product(*x):
result = 1 if x else 0
for n in x:
result *= n
return result
>>> product(S("a"), "b ", " c ")
Traceback (most recent call last):
File "<pyshell#367>", line 1, in <module>
product(S("a"), "b ", " c ")
File "<pyshell#366>", line 4, in product
result *= n
TypeError: can't multiply sequence by non-int of type 'str'
Whereas:
>>> def product(x, *y):
for yy in y:
x *= yy
return x
>>> product(S("a"), "b ", " c ")
'a*b*c'
There is prior art (sum() and strings), I don't like that either ;)
More information about the Tutor
mailing list