Scope Problem

Daniel Dittmar daniel.dittmar at sap.com
Thu Aug 5 08:02:23 EDT 2004


You are not returning the value of the recursive call
self.linearSearch(value, index + 1).

Hmm, implementing a linear search through recursion. Is your first language
LISP?

Daniel

Nickolay Kolev wrote:
> Hi all,
>
> I have set to implementing a few basic algorithms in Python serving a
> twofold purpose: learning the algorithms and learning Python a little
> better.
>
> I have however encountered a strange (for me anyway) scoping problem.
>
> 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)
>
>          except IndexError:
>
>               return -1
>
>
> My problem is that this method always returns None regardless of
> whether the value was found or not. If I put print statements in
> there, all the values and indices are printed correctly though.
> Actually I have another parameter to this method called debug, if
> this is set, the single comparison steps are printed to STDOUT
> (omitted above to avoid clutter).
>
> What am I doing wrong?
>
> Many thanks in advance,
> Nicky





More information about the Python-list mailing list