Reputation: 1036
I'm taking this online Python course and a common theme in this course is to NOT use functions or libraries to solve solutions. The problem asks:
Define a function prod(L) which returns the product of the elements in a list L.
My attempt is below. This specific problem asks to use for in range, the next question uses for in. I understand how to use for in, but not for in range. How do use the range i of 0,1,2,3 to help calculate the product?
broken for in range loop:
def prod(L):
Llen = len(L)
for i in range (0,Llen):
print(L[-1]*L[-2]*L[-3]*L[-4])
prod([1,2,3,4])
My for in loop works fine.
def prod(L):
p = 1
for i in L:
p *= i
return p
prod([1,2,3,4])
Please no lambda or 'from operator import mul'! I understand those methods.
Upvotes: 0
Views: 2938
Reputation: 54330
Using math
library allowed? That will be easy (doing it in numpy
would be sort-of cheating):
>>> from math import *
>>> def prod(L):
if 0 in L:
return 0.
#elif len(L)==0:
# return 0.
elif sum([item<0 for item in L])%2==0
return exp(sum(map(log, L)))
else:
return -exp(sum(map(log, map(abs, L))))
Upvotes: 0
Reputation: 32429
Another way how to solve it (up to max recursion depth) using range
:
def prod (x):
range (42)
def prod_ (head, *tail):
return head if not tail else head * prod_ (*tail)
return 1 if not x else prod_ (*x)
print (prod ( [1, 2, 5, 19] ) )
Upvotes: 0
Reputation: 43235
>>> x = [2,3,4,7]
>>> len(x)
4
>>> range(0,len(x))
[0, 1, 2, 3]
>>> range(len(x))
[0, 1, 2, 3]
>>> def prod(L):
... p = 1
... for i in range(len(L)):
... p = p*L[i]
... return p
...
>>> prod(x)
168
Upvotes: 0
Reputation: 473793
The idea is pretty much the same as for in
. Note that you don't need to make a variable from the list length, also you don't need to specify a start for the range()
, it's 0
by default.
def prod(L):
p = 1
for i in range(len(L)):
p *= L[i]
return p
print(prod([1,2,3,4])) # prints 24
Upvotes: 1