Recursion and Variable Scope

Ignacio Vazquez-Abrams ignacio at openservices.net
Fri Sep 7 01:33:46 EDT 2001


On 6 Sep 2001, mudpyr8 wrote:

> 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.

Here's your Evil Generator of Death:

---
def generator(sides, dice):
  if dice==1:
    return map(lambda x: [x], range(1, sides+1))
  else:
    import operator
    return reduce(operator.add, map(eval("lambda y: eval('map(lambda x: [x]+%%s, range(1, %%s+1))' %% (y,%s))" % sides), generator(sides, dice-1)))
---

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>






More information about the Python-list mailing list