[Tutor] exercise problem

Dave Angel davea at ieee.org
Fri Aug 27 21:32:59 CEST 2010



Roelof Wobben wrote:
>> Date: Fri, 27 Aug 2010 14:27:34 -0400
>> From: davea at ieee.org
>> To: rwobben at hotmail.com
>> CC: alan.gauld at btinternet.com; tutor at python.org
>> Subject: Re: [Tutor] exercise problem
>>
>> <snip>
>> 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
>>
>>     
>
>
> Hello, 
>
>  
>
> I put in right after getal1 = 
>
> I have tried another solution nl. 
>
>  
>
> Put every outcome in a string.
>
> Then convert the string into a list like 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
>     uitkomst=""
>     while teller < len(u):
>         getal1 = u[teller] + v[teller]
>         uitkomst = uitkomst + str(getal1) 
>         teller=teller+1
>     uitkomst2 = list(uitkomst)
>     return uitkomst2
>              
> uitkomst= []
> uitkomst2=[]
> vector= [1, 2, 1], [1, 4, 3]
> v=vector[0]
> u=vector[1]
> uitkomst = add_vectors(u,v)
> print uitkomst     
>
>  
>
> But then I get a list of string instead of integers.
>
>   
You're close.  Now that you've initialized the result variable to [], 
you can use + just as you're doing.  Just take out the str() function in 
that line.  You've still got duplicate names there between that function 
and the outer level code.

There's also no need to convert uitkomst to a list, since it already is.


DaveA



More information about the Tutor mailing list