Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type error when adding 1 to i (Recursion)

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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):
    limit = len(some_list)//2-1
    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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading