Thursday, 12 September 2013

Python 3+ - for in range loop, multiply, product, list NOT using mul or lambda or for in loop

Python 3+ - for in range loop, multiply, product, list NOT using mul or
lambda or for in loop

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.

No comments:

Post a Comment