Recursion and Variable Scope

mudpyr8 mudpyr8 at yahoo.com
Thu Sep 6 23:11:30 EDT 2001


I'm writing a simple function. It is recursive. Here's the code:

##########################
def generate(sides, dice, roll):
	if dice > 0:
		for x in range(sides):
			roll.append(x+1)
			generate(sides, dice - 1, roll)
			roll.pop()
	else:
		print roll
##########################

When calling it: generate(4, 2, [])
will generate output of 16 pairs of values, 1-4 each. However, I
cannot get that result stored in an object; I can only print it.

The last line is the tricky part. Where it says   # print roll #   I
want it to do something like:   # rolls.append(roll) #  .
Unfortunately, creating a variable   # rolls = [] #   outside of the
function definition, and even stating   # global rolls #   on the
first line of the block doesn't seem to matter.

I've tried to wrap my mind around this but am stuck. I need to perform
further manipulation on the results, but have no object with which to
do so. I know I could write to a file (maybe, if the file handle works
within the recursion) and then read it but that seems like a waste of
time.

I hope I'm just missing something obvious. Please, any help would be
appreciated.



More information about the Python-list mailing list