473,748 Members | 5,849 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recursive function return value problems

hi, i have the following recursive function (simplified to demonstrate
the problem):
def reTest(bool): .... result = []
.... if not bool:
.... reTest(True)
.... else:
.... print "YAHHH"
.... result = ["should be the only thing returned"]
.... print "printing result: "
.... print result
.... return result
.... reTest(False)

YAHHH
printing result:
['should be the only thing returned']
printing result:
[]
[]

I don't understand why results are returned twice? is there something
special i missed about recursive functions?

Dec 28 '05 #1
11 2771
ra********@gmai l.com wrote:
def reTest(bool):
... result = []
... if not bool:
... reTest(True)
... else:
... print "YAHHH"
... result = ["should be the only thing returned"]
... print "printing result: "
... print result
... return result
...
reTest(Fals e)
You're both printing the result and returning it. The interpreter just
happens to show both printed and returned variables.

An example of a shown return variable:
def returnb(): .... return 'b'
....returnb()

'b'

Hope that helps,
Brian

--
What if the Universe were a chrooted environment with everything
symlinked from the host?
Dec 29 '05 #2
On 28 Dec 2005 15:25:30 -0800,
ra********@gmai l.com wrote:
hi, i have the following recursive function (simplified to demonstrate
the problem):

def reTest(bool):

... result = []
... if not bool:
... reTest(True)


Don't do that. Do this instead:

result = reTest(True)

[ rest of example snipped ]

HTH,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Dec 29 '05 #3
the final returned value is: []

the two values printed is (note i only have one print statement
printing "print result",. however, in the actualality, it's printed
twice):
printing result:
['should be the only thing returned']
printing result:
[]

therefore, sadly, i don't thinkg you've understand my problem
correctly..

Dec 29 '05 #4
You have two calls to reTest and so reTest needs to return twice. One
return is from the reTest(True) call back to reTest(False). The second
return is from reTest(False) back to the prompt.

What were you expecting to happen?

Dec 29 '05 #5
On Wed, 28 Dec 2005 15:25:30 -0800, randomtalk wrote:
hi, i have the following recursive function (simplified to demonstrate
the problem):
def reTest(bool): ... result = []
... if not bool:
... reTest(True)
... else:
... print "YAHHH"
... result = ["should be the only thing returned"]
... print "printing result: "
... print result
... return result
... reTest(False)

YAHHH
printing result:
['should be the only thing returned']
printing result:
[]
[]

I don't understand why results are returned twice? is there something
special i missed about recursive functions?


No. What happens when you do this?

py> def test():
.... print "spam"
.... return "Spam"
....
py> test()
spam
'Spam'

I've deliberately spelt one in all lower case, and the other with an upper
case S, so it is easier to see the difference.

When you just call a function from the interactive interpreter without
assigning to a name, Python automatically prints the return value. In your
test above, you call reTest(False) without assigning the result to
anything, so after reTest prints all the various things it has to print,
the interpreter also prints the return result.

If you get that, you can stop reading. Otherwise, here is a more
careful analysis.

When you call reTest(False), it creates a local variable 'result' to the
empty list, then calls reTest(True).

reTest(True) then creates a new local variable 'result', sets it to the
empty list, prints "YAHHH", sets result to a string inside a list. It
prints "printing result", then prints ["should be the only thing..."], and
finally returns that string inside a list.

Control now returns to the *first* call to reTest(False). It accepts that
string inside list, *but throws the result away*. You didn't do anything
with the result! You probably want to change that line to
result=reTest(T rue).

Because this is inside a function, the result of reTest(True) doesn't get
printed, so you don't see it. (Python only automatically prints results of
things you type at the interactive prompt.)

Execution now continues past the if...else... block. It prints "printing
result", then it prints the value of 'result' which is still equal to the
empty list. Finally it returns the empty list, and the Python interpreter
prints the empty list as a convenience for you.

Calling a recursive function is no different from calling any other
function: you want to assign the result to something.

def factorial(n):
"""Returns n! = 1*2*3*...*(n-1)*n for non-negative int n"""
# this is inefficient code, but it does demonstrate recursion well
if n == 0:
result = 1
else:
result = n*factorial(n-1)
return result

--
Steven.

Dec 29 '05 #6
ah, result = reTest(True) works, thanks alot :D

Dec 29 '05 #7
On Wed, 28 Dec 2005 16:05:30 -0800, randomtalk wrote:
the final returned value is: []

the two values printed is (note i only have one print statement
printing "print result",. however, in the actualality, it's printed
twice):
printing result:
['should be the only thing returned']
printing result:
[]

therefore, sadly, i don't thinkg you've understand my problem
correctly..


I wonder what you think your problem is.

You make TWO calls to reTest (the first one you explicitly call, then the
recursive call). 'print "printing result:"' happens in *every* call to
reTest, regardless of the argument, so of course it gets printed twice.
What did you expect to happen?

By the way, it is Bad with a capital B to shadow the names of built-in
functions as you do:

def reTest(bool): # don't use bool as the name of an argument!

bool is a built-in type. By using that name as an argument, you now
have made the built-in type inaccessible to your code, which is a potent
source of hard-to-track-down bugs.

--
Steven.

Dec 29 '05 #8
ra********@gmai l.com wrote:
... if not bool:
... reTest(True) I don't understand why results are returned twice? is there something
special i missed about recursive functions?


Yes, although it is not clear *what* it is that you are missing.

Here is my guess: you fail to see that reTest *continues* after
the recursive call returns. So you get this

reTest(False)
result = []
reTest(True)
result = []
print "YAHH"
result = ["should be the only thing returned"]
print "printing result: "
print ["should be the only thing returned"]
return ["should be the only thing returned"]
# result value discarded by caller
print "printing result: "
print []
return []
# interactive shell prints result value: []

If you agree that this is what happens, please explain what it is
that you were missing.

Alternative guesses what it is that you are missing:
- there is one result variable per reTest call, as result is
not global
- you forgot to assign the result of the recursive call
- you missed the fact that the interactive shell also prints
the final result.

Possible corrections:
1. you only want a single print statement executed. Write
.... if not bool:
.... return reTest(True)
2. you never want the empty list printed. Write
.... if not bool:
.... result = reTest(True)
3. you don't want the interactive shell to print the value.
Write
res = reTest(False)


HTH,
Martin
Dec 29 '05 #9
ra********@gmai l.com writes:
hi, i have the following recursive function (simplified to demonstrate
the problem):
def reTest(bool): ... result = []
... if not bool:
... reTest(True)
... else:
... print "YAHHH"
... result = ["should be the only thing returned"]
... print "printing result: "
... print result
... return result
... reTest(False)

YAHHH
printing result:
['should be the only thing returned']
printing result:
[]
[]

I don't understand why results are returned twice? is there something
special i missed about recursive functions?


Depends on what you're complaining about. If it's the two []'s at the
end, one is printed by "print result", and the other is printed by the
interactive interpreter as the return value of retest.

If, on the other hand, it's that you get "printing result:" twice,
with two different values, it's because you called reTest twice: once
from the interactive interpreters prompt (bool = False in this case)
which returns [], and once recursively (bool = True in this case)
which returns ["should be the only thing returned"]. If the latter,
there's something you are missing about recursive functions.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 29 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3157
by: Derek Rhodes | last post by:
using Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32 OK, I have a recursive function that should return a list, but doesn't <start session> def test(word): if type(word) == str:
9
2074
by: peter | last post by:
Hello all, Recently I've started to refactor my code ...(I'm using python 2.3.4) I tried to add extra functionality to old functions non-intrusively. When I used a construct, which involves renaming functions etc... I came across some recursive problems. (a basic construct can be found under the section BASIC CODE) These problems do not occur when renaming objects. (see section EXTRA CODE)
8
6189
by: Andrew Edwards | last post by:
The following function results in an infinite loop! After 5+ hours of debugging, I am still unable to decipher what I am incorrectly. Any assistance is greatly appreciated. Thanks in advance, Andrew ==========>Code<========== //--------------------------------------------------------------------
2
2888
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays a sequence of spaces; recursive function 2 uses input to display ascending sequence of digits; likewise, recursive function 3 uses input to display descending sequence of digits. I have not followed the instructions completely regarding the...
4
9054
by: Victor | last post by:
Hello, I've got a situation in which the number of (valid) recursive calls I make will cause stack overflow. I can use getrlimit (and setrlimit) to test (and set) my current stack size. However, it is not as straightforward to determine the base address for my stack space. The approach I have taken is to save the address of an automatic variable in main( ), and assume this is a fairly good indicator of my base address. Then, I can...
10
6184
by: zahy[dot]bnaya[At]gmail[dot]com | last post by:
Hi, I am trying to come up with a c style string reverser, I want it to take 1 argument Altough I would never do this in real life. Is there a way to do it? I wrote this function that fails : Any idea why it fails? char * C_recReverse(char * str)
7
2109
by: =?Utf-8?B?RGF2aWQgQ29sbGl2ZXI=?= | last post by:
Hi all, using C#, .NET 1.1, ASP.NET I have created a recursive??? function. It looks a little like... MyContext.Current.Folder.Parent.Parent.Parent.Parent.Name As you can see, Parent is the recursive??? part.
41
3373
by: Harry | last post by:
Hi all, 1)I need your help to solve a problem. I have a function whose prototype is int reclen(char *) This function has to find the length of the string passed to it.But the conditions are that no local variable or global variable should be used.I have to use recursive functions.
10
2568
by: AsheeG87 | last post by:
Hello Everyone! I have a linked list and am trying to include a recursive search. However, I am having trouble understanding how I would go about that. I don't quite understand a recursive search....would any of you be so kind to explain it to me...maybe include some examples. I would GREATLY appreciate it!!!
0
8984
marktang
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9530
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9363
jinu1996
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8237
agi2029
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.