0

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???

1
  • 1
    Can you explain the line num += 1 + ind( e, L[1:] ) to your rubber duck?
    – Jasper
    Sep 11, 2016 at 9:19

2 Answers 2

1

When working with indicies in sequence, Python has great built-in named enumerate which helps a lot with keeping track of index in consise and simple manner.

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

Sample:

seq = ['hello', 42, True]
for index, obj in enumerate(seq):
    print index, obj

Output:

0 hello
1 42
2 True

We can use it to ease up processing significantly. Since we can iterate over L and retrieve both index and value of current element, we have to do do comparison with requested value now. When value is found, we may simply return it and skip searching through rest of sequence

def ind(e, L):
    for index, value in enumerate(L):
        if value == e:
            return index

What's missing now is case when value is not found, but adding support for it is fairly simple:

def ind(e, L):
    for index, value in enumerate(L):
        if value == e:
            return index
    return len(L)  # this will be executed only if any value wasn't found earlier

It passes all testcases:

assert ind(42, [ 55, 77, 42, 12, 42, 100 ]) == 2
assert ind(42, range(0,100)) == 42
assert ind('hi', [ 'hello', 42, True ]) == 3
assert ind('hi', [ 'well', 'hi', 'there' ]) == 1 
assert ind('i', 'team') == 4 
assert ind(' ', 'outer exploration') == 5

And bonus, with using all tricks Python provides:

def ind(e, L):
    return next((idx for idx, obj in enumerate(L) if obj == e), len(L))

Have fun with figuring out what happens here :)

1
  • looks like the OP have to do it with recursion Sep 11, 2016 at 17:28
0

And here it(!) once(!) of the many codes I have written for this problem.

You should pay more attention to what you're writing and probably also to what you are coding.

Unless you are explicitly asked to write a recursive function for this task, I'd advise against it.

Try to break down the task to smaller subproblems. Some of them are already solved:

  • If the element is not contained in the list, return the length of the list (done)
  • Loop over the list, keeping track of the current index
    • if the current list element is the one you are looking for, return the current index
    • else, look at the next element
  • since you can be sure that the element is in the list once you enter the loop (why?), you are done.

If you have to do it recursively, the "hints" are rather misleading. The not in syntax is not useful. Did you look at the mylen function? I suppose it looks like

def mylen(s):
  if not s:
    return 0
  return 1 + mylen(s[1:])

Now, to find the (first) index of a given element:

 def ind(e, l):
   if not l:        # list is exhausted, element was not found
     return 0
   elif l[0] == e:  # element found
     return 0
   else             # element not found yet
     return 1 + ind(e, l[1:])
2
  • Sadly, the homework is on recursive problems and I am supposed to solve it recursively.. Sep 11, 2016 at 14:18
  • You should state that in the question.
    – Jasper
    Sep 11, 2016 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.