I am creating a fractal called an L-System which uses a kind of pseudo recursive replacement method. I need to replace all occurrences of each letter with its key, but only one generation at a time. As an example, we start with the string
AXIOM = "f"
and we have the dictionary
rule_dict = {"f":"h-f-h", "h":"f+h+f"}
we apply this rule to the axiom in successive iterations such that we see a progression like this
"f"
"h-f-h"
"f+h+f-h-f-h-f+h+f"
and on.
My initial method simply used a for loop like this:
for i in range(GENERATION):
for key in rule_dict.keys():
axiom = axiom.replace(key, rule_dict[key])
The problem with this method is that once it replaces the "f" in the first iteration, it will then check for "h", resulting in it replacing the "h" characters which should not be affected until the next generation.
I would prefer to avoid simply creating a duplicate string to work with and was wondering if anyone knew of an effective way to handle this issue. The program is somewhat memory sensitive in that it is a kind of recursion. Because of that I would like to minimize memory usage if possible. Thanks for the help!