I am trying to write a recursion that sums the product of items in a list, in the pattern of:
(some_list[i] * some_list[j]) + (some_list[i+1] * some_list[j-1]) +
(some_list[i+2] * some_list[j-2]) + ........
The limit being once every number has been accounted for between i and j.
I believe I have set up the recursion correctly (correct me if I am wrong), however I am getting the following error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
def sum_product(some_list, i, j):
limit = len(some_list)//2
if j <= limit:
return ' '
else:
result = some_list[i] + some_list[j]
return result + sum_product(some_list, i + 1, j - 1)
print(sum_product([1, 2, 3, 4, 5, 6, 7, 8], 1, 6))
Change to return 0 and change the + to *. The limit should also be adjusted to include all numbers with indexes between i and j. Assuming j > i.
def sum_product(some_list, i, j):
if j < i:
return 0
else:
result = some_list[i] * some_list[j]
return result + sum_product(some_list, i + 1, j - 1)
print(sum_product([1, 2, 3, 4, 5, 6, 7, 8], 1, 7))
Output: 86
= 2*8+3*7+4*6+5*5