Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding Variable
#1
Hey I have this homework problem set that I feel like should be very simple but I am stuck:

Write a function add(vals1, vals2) that takes as inputs two lists of 0 or more numbers, vals1 and vals2, and that uses recursion to construct and return a new list in which each element is the sum of the corresponding elements of vals1 and vals2. You may assume that the two lists have the same length.

For example:

>>> add([1, 2, 3], [3, 5, 8])
[4, 7, 11]
Note that:

The first element of the result is the sum of the first elements of the original lists (1 + 3 –> 4).
The second element of the result is the sum of the second elements of the original lists (2 + 5 –> 7).
The third element of the result is the sum of the third elements of the original lists (3 + 8 –> 11).


This is what I have:
def add(vals1, vals2):
   return (vals1 + vals2)
Reply
#2
if the lists have the same lenght you could use something like that:
[Vals1[i]+Vals2[i] for i in range(len(Vals1))]
Reply
#3
One of the key things to think about with a recursive function is "what is the termination state?" How does the function know it is done recursing, and is ready to return the final result? Generally, you are consuming something, and when that something is empty, you are done. What might you consume while adding up the lists? Another termination point is an invalid operation. Keep doing something until it is no longer a valid thing to do. What operation could you do that would eventually become invalid (when you are done adding up the items in the list)?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
@Lonewolf: that is a very non-pythonic way to do that. You should iterate over the list, not the indexes of the list, as shown here.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
(Feb-18-2019, 08:16 AM)Lonewolf Wrote: if the lists have the same lenght you could use something like that:
[Vals1[i]+Vals2[i] for i in range(len(Vals1))]

As ichabod801 already mentioned this is not Pythonic way i.e. needlessly complex and verbose. Just:

[sum(pair) for pair in zip(vals1, vals2)]
However, this is not recursive solution what OP needs.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020