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

What is the difference between using a recursive function in Python and JS?

Trying to use recursive function in JS, but code isn`t work:

let arr = [6, 5, 3, 1, 1, 1, 1]

function sum(ars, i) {
  if (ars.length == i) {
    return 0
  }
  return ars[i] + sum(ars[1])
}
console.log(sum(arr, 0))

// Output: 6

But the same code works in python:

arr = [2,5,3,1,1,1,1]

def sum(array):
    if array==[]:
        return 0
    return array[0]+sum(array[1:])
    
print (sum(arr))

Can anyone explain what is the difference and what am I doing wrong in the JS code?

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 :

sum(ars[1])

ars[1] means "access the element at index 1". It does not get the tail of the array (ie, the sub-array from index 1 to n). Element 1 equals 5, so this is doing sum(5), which then gets messed up because the code expects an array, not a number.

To get the tail of an array you can use the slice method:

let arr = [6, 5, 3, 1, 1, 1, 1]

function sum(ars) {
  if (ars.length == 0) {
    return 0
  }
  return ars[0] + sum(ars.slice(1))
}

console.log(sum(arr))
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