0

I've been at it for hours now yet I still don't know what to put in these blanks. I have an idea on how it will work but I don't know how to apply it. Help!

Basically, I need to find out what are the blanks in order for the program to run. It's a recursion problem where the program would just basically get the sum of all the elements in the list.

enter image description here

  • What is the point of `size`? The function can calculate it internally – TheRavenSpectre May 22 '22 at 14:30
  • I'm trying to really solve the problem through recursion. I know it can easily be solve by just using sum(numbers), I just really want to practice recursion. – Steven Universe May 22 '22 at 14:33
  • @TheRavenSpectre It looks like the point of the recursion is to split `numlist` in half in each new recursive call and do the recursion on both halves .... – fireshadow52 May 22 '22 at 14:33
  • Yup, I know it that far. I just don't know what to put in the blanks in order for the program to run. – Steven Universe May 22 '22 at 14:36
  • it's a practice problem in our class. I've been at it for hours now, and I tried several things that I know of but still it wouldn't run. – Steven Universe May 22 '22 at 14:38
  • @Jay What sorts of things have you tried that didn't work for you? Also, have you considered [array slicing](https://stackoverflow.com/questions/509211/understanding-slicing)? – fireshadow52 May 22 '22 at 14:40
  • Yes. Tried that. It sort of worked. but it just brought back all the elements from the numbers list. Maybe I'm doing something wrong I don't know – Steven Universe May 22 '22 at 14:44

1 Answers1

0

Without having to fill in the blanks:

def listsum(numlist):
  size=len(numlist)
  if(size==1): return numlist[0]
  else: 
    mid=size//2
    return listsum(numlist[:mid])+listsum(numlist[mid:])

numbers=[3, 5, 4, 1, 7, 2, 9, 8, 0, 6]

Having to fill in the blanks:

def listsum(numlist, size):
  if size==0:
    return 0
  elif size==1:
    return numlist[0]

  mid=size//2

  return listsum(numlist[:mid], mid)+listsum(numlist[mid:], size-mid)

numbers=[3, 5, 4, 1, 7, 2, 9, 8, 0, 6]
print(listsum(numbers, len(numbers)))

I highly question why such a piece of homework would be meted out to students

TheRavenSpectre
  • 367
  • 2
  • 11
  • Thank you for the input. I already though of this. It's just that the instruction is specific that I need to just fill in the blanks and not make my own version for the solution. A Also, yes, I questioned the len of the list being 0 as there is no need for it for the program to work. – Steven Universe May 22 '22 at 14:49
  • I have included a solution which solely fills in the blanks, but it is fairly simple to do so from the first solution I gave – TheRavenSpectre May 22 '22 at 14:59
  • Thank you! Sorry, I wasn't able to say thank you earlier. I got an idea from your initial answer on how to solve the problem. – Steven Universe May 22 '22 at 15:06