2
Posted April 1, 2013 by Hunter in General Tips & Tricks
 
 

Memory for Random Generation Scripts

memory
memory

Python scripts can be used to create many things – shoes and ships and sealing wax, cabbages and kings – and to do many things – to make the sea boiling hot, and give pigs some wings. You will perhaps want to randomly generate math problems, if you are a teacher, tutor, or designer of a Math Blaster game; you will perhaps want to randomly generate story ideas, if you are bored – ideas like Cowboy mummies battle psychic tigers in a post-apocalyptic Martian wasteland, only to find love in the most unexpected places, being of the form character(s) 1 verb character(s) 2 in setting, twist/theme and randomly selecting from a list of each type; you will perhaps want to encrypt a lot of files but each with a unique key. And you may, as the fancy strikes you, run a random [insert anything here] generator on Tuesday, and not run it again until Friday. But on Friday, you do not wish to recreate anything you randomly generated on Tuesday. How can you be sure that time after time of running a random generation script you do not double-generate? The answer, my friend, is much more accessible than whatever is blowing in the wind, because the answer is simply: memory.txt.

Say you have a random generation script that outputs math problems. You’re planning out the section on systems of equations for your algebra class, and over the course of this section you plan on giving out 5 worksheets. So you use your script to generate the 100 problems for these worksheets, ensuring uniqueness by storing every randomly generated problem in a variable and checking newly generated problems against this variable. But then you realize that the students would benefit from 2 more worksheets, so you go to generate those, but – the uniqueness of those 40 new problems are ensured only within those 40, but not between those 40 and the first 100. So you go back to your script and write this:

f = open('filepath/filepath/filepath/memory.txt','a+')
memory = f.read()

This opens memory.txt or, if memory.txt does not exist, creates it. Then, the contents are fed into the variable named memory.

Every time a new problem is generated, it is checked against memory:

if problem != memory:
    memory += problem
    f.write(problem)

This is assuming that problem is a string. If it isn’t, you’ll want to run problem through a function that converts the data it contains into a string. Writing every new and uniquely generated problem – or whatever it is you’re generating – to the file ensures that when you run the script again, and the variable named memory is fed the data in the file, then when you check problems generated from the script the second or fourth or hundredth time you run it, you are checking it against every single problem ever generated by the script. This way, everything generated is new, unique.


Hunter