Friday, November 12, 2010

allcombinations - generating combinations of python structures

Alright, on a whim I decided to make another tricky thing in Python. This one is less of a hack, and is more likely to be useful.

So let's say you want to do something with all combinations of... something.

[5, 6, oneOf(7,8,9), oneOf(10, 11, "shazaam")]

So you want to turn this structure into all the possibilities represented within:

[
[5, 6, 7, 10],
[5, 6, 7, 11],
[5, 6, 7, "shazaam"],
[5, 6, 8, 10],
[5, 6, 8, 11],
[5, 6, 8, "shazaam"],
[5, 6, 9, 10],
[5, 6, 9, 11],
[5, 6, 9, "shazaam"],
]

Well with allcombinations, you can do just that:

from allcombinations import allCombinations

allCombinations( [5, 6, oneOf(7,8,9), oneOf(10, 11, 12)] )

Here it is. The gist includes more complicated example.

Features
The oneOf should be able to reside almost anywhere in your expression. It can be in a list (as seen here), in a dict, or even in the attribute of an object. It can also reside in a list within a dict within an object's attribute, etc, as long as it's nowhere within an unsupported container type.

Limitations:
This will only work if oneOf resides in a list, dict, or an object's attributes. It shouldn't work anywhere within a set, or any other structure I can't think of. If you try it in something unsupported, the oneOf object should just stick around in all your combinations.

I'm probably actually going to use this, particularly (again) for testing. Anyone else think they'd find it useful? Should I package it?

No comments: