[Tutor] exercise problem

Dave Angel davea at ieee.org
Fri Aug 27 20:27:34 CEST 2010


(Don't top-post, it loses all the context)

Roelof Wobben wrote:
> Hello, 
>
>  
>
> Now I have this :
>
>  
>
> def add_vectors(u, v):
>     """
>       >>> add_vectors([1, 0], [1, 1])
>       [2, 1]
>       >>> add_vectors([1, 2], [1, 4])
>       [2, 6]
>       >>> add_vectors([1, 2, 1], [1, 4, 3])
>       [2, 6, 4]
>       >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
>       [13, -4, 13, 5]
>     """
>     teller=0
>     getal1=0
>     getal2=0 
>     while teller < len(u):
>         getal1 = u[teller] + v[teller]
>         teller=teller+1
>     return uitkomst2
>              
> uitkomst= []
> uitkomst2=[]
> vector= [1, 2, 1], [1, 4, 3]
> v=vector[0]
> u=vector[1]
> uitkomst = add_vectors(u,v)
> print uitkomst         
>
>
> The only problem I have is to build up uitkomst2.
> on every loop getal1 has the value of the outcome.
> So I thought this would work
>
> uitkomst2 [teller] = getal1 
>
> But then i get a out of range.
>
>   
Where did you put that statement?  Was it indented like getal1= and 
teller= ?  I doubt it.  If you don't use the value till the loop is 
over, then the subscript will be wrong, and so will the value.

The other problem is you're confusing the variables inside the function 
with the ones declared outside.  While you're learning, you should use 
different names for the two sets of variables.  So create a new variable 
inside the function, called something like result.  Give it an initial 
value, a list of the desired size.  Then assign to one of its elements 
each time through the loop.  And don't forget to change the return 
statement to return that variable instead of the confused-named one.

DaveA



More information about the Tutor mailing list