[Tutor] exercise correct ??

Roelof Wobben rwobben at hotmail.com
Mon Sep 6 22:28:19 CEST 2010



 

> Date: Mon, 6 Sep 2010 21:45:17 +0200
> Subject: Re: [Tutor] exercise correct ??
> From: sander.sweers at gmail.com
> To: rwobben at hotmail.com
> CC: tutor at python.org
> 
> On 6 September 2010 19:32, Roelof Wobben <rwobben at hotmail.com> wrote:
> > 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
> >     """
> >     plek = 0
> >     if type(seq) == type([]):
> >         plek = seq.index(val)
> >     elif type(seq) == type(()):
> >         seq = list (seq)
> >         plek = seq.index(val)
> >     else :
> >         plek = seq.find(val)
> >     return plek
> 
> Not sure if this is correct but why don't you check for the index
> attribute? It is part of both lists and strings. Also you can use
> try/except to catch a ValueError. My version below, but I dislike the
> list() usage...
> 
> def index_of(val, seq, start=0):
> if hasattr(seq, 'index'):
> try:
> return seq.index(val, start)
> except ValueError:
> return -1
> else:
> try:
> return list(seq).index(val, start)
> except ValueError:
> return -1
> 
> > File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in
> > __main__.index_of
> >
> > Failed example:
> >
> > index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> >
> > Expected:
> >
> > 6
> >
> > Got:
> >
> > 3
> >
> > But in that tuple 5 is on position 3.
> >
> > Is the exercise here wrong ?
> 
> Looks like it, or it's a typo.
> 
> Greets
> Sander


Hello Sander, 

 

I agree that index is a part of string and list.

But not a part of a tuple.

As far as I know index is not a part of tuple so I have to convert it to a list so I can use index.

 

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


More information about the Tutor mailing list