So I have this question that I have to do for homework.
Next, write ind( e, L ). Here is its description:
Write ind(e, L), which takes in a sequence L and an element e. L might be a string or, more generally, a list. Your function ind should return the index at which e is first found in L. Counting begins at 0, as is usual with lists. If e is NOT an element of L, then ind(e, L) should return the integer equal to len(L). Here are a few examples:
ind(42, [ 55, 77, 42, 12, 42, 100 ]) returns 2
ind(42, range(0,100)) returns 42
ind('hi', [ 'hello', 42, True ]) returns 3
ind('hi', [ 'well', 'hi', 'there' ]) returns 1
ind('i', 'team') returns 4
ind(' ', 'outer exploration') returns 5
In this last example, the first input to ind is a string of a single space character, not the empty string.
Hint: Just as you can check whether an element is in a sequence with
if e in L: you can also check whether an element is not in a sequence with
if e not in L: This latter syntax is useful for the ind function! As with dot, ind is probably most similar to mylen from the class examples.
And here it once of the many codes I have written for this problem.
def ind( e, L):
num = 0
if e not in L and num == 0:
return len(L)
else:
if e == L[0]:
num += 1 + ind( e, L[1:] )
return num
else:
return ind( e, L[1:] )
So the problem is that everytime e is no longer in the list. It takes the length of the remainder of the list and adds that to num. How do I fix this???
num += 1 + ind( e, L[1:] )
to your rubber duck?