[Tutor] exercise correct ??
Sander Sweers
sander.sweers at gmail.com
Mon Sep 6 21:45:17 CEST 2010
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
More information about the Tutor
mailing list