Scope Problem

Irmen de Jong irmen at -nospam-remove-this-xs4all.nl
Thu Aug 5 08:06:47 EDT 2004


Nickolay Kolev wrote:
> I have however encountered a strange (for me anyway) scoping problem.

This has nothing to do with scoping.

> Here is my implementation of linear search as a method in a class, hence 
> all the self's (self.sequence is the sorted sequence we are searching in 
> and value is, well, the value we are searching for):
> 
> def linearSearch(self, value, index = None):
> 
>         if not index:
>             index = 0
>         try:
>             if self.sequence[index] == value:
>                 return index
>             else:
>                 self.linearSearch(value, index + 1)
In this line, you don't return a value from the recursive call.
Change it to:
                   return self.linearSearch(value, index + 1)

>         except IndexError:
>              return -1

The algorithm should now work, although it is very inefficient.
Now, you're learning Python, so it's probably good to point
out that a containment test is usually done like so:

	if value in sequence: ...

If you want to have the index:

	idx = sequence.index(value)

And for quick (much quicker than linear) search in a sorted sequence,
have a look at the bisect module etc:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54159

Good luck!
--Irmen



More information about the Python-list mailing list