[Tutor] exercise correct ??

Roelof Wobben rwobben at hotmail.com
Tue Sep 7 11:40:25 CEST 2010



 


Date: Tue, 7 Sep 2010 00:52:38 -0700
From: alan.gauld at btinternet.com
Subject: Re: [Tutor] exercise correct ??
To: rwobben at hotmail.com; tutor at python.org









Oke, the 4 is a starting point for the index.
 
Next problem.
 
The begin looks like this :
 
 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)

But in the module I get this result :
 
val = 5
seq = (1, 2, 4, 5, 6, 10, 5, 5
 
So the 4 is not avaible anymore.


Yes it is. It is the start parameter.

The function definition is

def index_of(val, seq, start=0):

val is the first value, 5, seq is the tuple and start is 4.
 



Now I can change the header to  index(val, seq, start=0) to index (val, seq, start)
But I think that's not what the exercise wants.


Why would you want to do that? It would force you to provide a start value 
for every call. The point of having a default value (=0) is so that you do not 
need to specify start every time you use the function. But eveb if you do not
use the start value it will still have a value, 0.
There is no difference, you can access it exactly like the other parameters.
Just use its name.
 
HTH,

Alan G.
 
Oke, 
 
Then this is the solution :
 
def index_of(val, seq, start=0):
    """
      >>> index_of(9, [1, 7, 11, 9, 10])
      3
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
      3
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
      6
      >>> index_of('y', 'happy birthday')
      4
      >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
      1
      >>> index_of(5, [2, 3, 4])
      -1
      >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
      -1
    """
    try:
        plek = seq.index(val, start)
    except:
        plek = -1
    return plek 
 
Roelof


  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100907/bea6ed96/attachment.html>


More information about the Tutor mailing list