My program isn't working.
It is meant to be
- you have an array and a code
- if the code is 0 then you have to add up the numbers
- if it is anything else then you have to multiply them
- I want it to use recursion but when you get to less then 5 numbers then I don't use more recursion, I just want do it normally
This is the problem I get
the_rest = sum_or_product(code, array[1:])
UnboundLocalError: local variable 'sum_or_product' referenced before assignment
This is the program
def sum_or_product(code, array):
if code == 0:
do = 'SUM'
else:
do = 'PRODUCT'
# THIS IS WITH THE RECURSION
if len(array) >= 5:
this_one = array[0]
the_rest = sum_or_product(code, array[1:])
if do == 'SUM':
return this_one + the_rest
if do == 'PRODUCT':
return this_one * the_rest
# THIS IS WITHOUT THE RECURSION
if do == 'SUM':
start = 0
if do == 'PRODUCT':
start = 1
sofar = start
for i in array:
if do == 'SUM':
total = sofar + i
sofar = total
if do == 'PRODUCT':
product = sofar * i
sofar = product
sum_or_product = sofar
return sum_or_product
print(sum_or_product(1, [1,2,3,4,5,6,7,8,9,10]))
It should mutiply all the numbers from 1 to 10. But it just gives an error.