> Date: Mon, 6 Sep 2010 21:45:17 +0200 > Subject: Re: [Tutor] exercise correct ?? > From: sander.swe...@gmail.com > To: rwob...@hotmail.com > CC: tutor@python.org > > On 6 September 2010 19:32, Roelof Wobben <rwob...@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor