Scope Problem

Tom B. sbabbitt at commspeed.net
Thu Aug 5 08:34:09 EDT 2004


"Nickolay Kolev" <nmkolev at uni-bonn.de> wrote in message
news:cet6eh$tvq$1 at f1node01.rhrz.uni-bonn.de...
> 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


Try useing the self keyword,

def linearSearch(self, value, index = None):
>          self.index = index
>
>          if not self.index :
>              self.index = 0
>
>          try:
>
>              if self.sequence[self.index ] == value:
>
>                  return self.index
>
>              else:
>
>                  self.linearSearch(value, self.index + 1)
>
>          except IndexError:
>
>               return -1

Tom





More information about the Python-list mailing list