Danxe - 9 months ago 37

Python Question

Implement the function tree that takes a number of slices n and a rune as arguments, and generates a stack of runes (shape) scaled and overlayed on top of each other.

the shape at the top must be 1/n the size of the original shape. the shape at the second level must be 2/n the size of the original shape and so on. i.e. the shape at the bottom is the original shape.

So I tried to do this in a recursive manner using some ideas from mathematical induction.

`def tree(n, shape):`

a = n

if n == 1:

return scale(1/a, shape)

else:

return overlay_frac((n-1)/n, tree(n-1, shape) , scale(n/a, shape))

My question is how would you fix the initial value of

`n`

`a = n`

`n`

Is there a way for me to set the initial value of

`n`

Right now I'm not even sure if this code works. But without being able to fix it, I can't test it.

FYI: I am aware that you guys might not know what

`overlay_frac`

`scale`

My question really revolves around a way to set the initial input of a recursion so that it will not be affected as the process loops.

Answer

What you can do is add a third parameter that will keep track of the original size, and have your arguments in your `overlay_frac()`

function be based off of that variable, so that the values don't alter in recursion. Here's how I've done it:

```
def tree(n, initial_size, shape):
a = initial_size
if n == 1:
return scale(1/a, shape)
else:
return overlay_frac((n-1)/a, tree(n-1, initial_size, shape), \
scale(n/a, shape))
```

Source (Stackoverflow)