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 5 1450
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/Coo...n/Recipe/54159
Good luck!
--Irmen
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
Thanks guys,
I should have seen it myself, it´s stupid enough.
@Irmen: I am implementing the algorithms not for the purpose of using
them, but for the purpose of learning them. I thinks it is a bit early
for trying to outsmart the python dev-people. :-)
@Daniel: It should be pretty obvious form my mistake that it is not. A
real Lisper would never do such a thing. :-)
Thanks again,
Nicky
"Nickolay Kolev" <nm*****@uni-bonn.de> wrote in message
news:ce**********@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
Nickolay Kolev wrote:
Python doesn't support tail recursion; your algorithm is not only
inefficient but incorrect. The number of allowed recursion levels is
significantly below the maximum number of list entries. import sys sys.setrecursionlimit(10) # reduced for demonstration purposes def index(seq, value, n=0):
.... try:
.... if seq[n] == value:
.... return n
.... else:
.... return index(seq, value, n+1)
.... except IndexError:
.... return -1
.... index(range(5), "a")
-1 index(range(10), "a")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
File "<stdin>", line 6, in index
RuntimeError: maximum recursion depth exceeded
The
def f(value=None):
if value is None:
# set real default
idiom is only needed for mutable default values.
@Irmen @Daniel
I see finally someone is embracing the decorator style slated for 2.4 :-)
Peter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Arthur |
last post by:
>>>a=
>>> for p in a:
print p
1
2
3
>>> p
3
My naive expectation was that p would be 'not defined' from outside
|
by: Marc Tanner |
last post by:
Hello,
I am currently working on a eventhandling system or something similar,
and have the problem of loosing scope. I have read many interesting
posts on this group and the faq article about...
|
by: Gery D. Dorazio |
last post by:
Gurus,
If a static variable is defined in a class what is the scope of the variable
resolved to for it to remain 'static'? For instance, lets say I create a
class library assembly that is...
|
by: Dieter |
last post by:
Hi.
In the snippet of code below, I'm trying to understand why when the
struct dirent ** namelist
is declared with "file" scope, I don't have a problem freeing the
allocated memory. But...
|
by: Frank Silvermann |
last post by:
I have taken an extraordinary leap into the modern world by purchasing
webspace. In addition to my private concerns, I would like to make a
part to which others, e.g. my nieces and ex-wife, can...
|
by: Josiah Manson |
last post by:
I found that I was repeating the same couple of lines over and over in
a function and decided to split those lines into a nested function
after copying one too many minor changes all over. The only...
|
by: Frank |
last post by:
Hi,
I have the following problem with dynamic memory:
int main(){
for(){
int (**w)=new int *;
for(m = 0; m < N1; m++) {
|
by: Pantokrator |
last post by:
Hi all,
I've got a question about the scope of the constructor initialisation
list. First of all, let me explain my classes:
// *****************************************************
class...
|
by: David Mathog |
last post by:
I accidentally did this the other day (it was a lot less obvious in the
much longer actual program, hundreds of lines are omitted):
----------------------------------------------------------...
|
by: somenath |
last post by:
Hi All ,
I have one question regarding scope and lifetime of variable.
#include <stdio.h>
int main(int argc, char *argv)
{
int *intp = NULL;
char *sptr = NULL;
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |