Created
May 20, 2017 14:02
-
-
Save julian-savage/e54e5bd628ec4b8eb7b32b0f6addac4b to your computer and use it in GitHub Desktop.
Create all possible expansions for a string containing variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def expand_vars(value, vars): | |
return [vars.get(seg, [ seg ]) for seg in re.split('(\$\w+)', value)] | |
def join_segments(segments): | |
return [reduce(lambda acc, seg: (acc[0]+seg[acc[1]%len(seg)], acc[1]/len(seg)), | |
segments, | |
("", val))[0] | |
for val in range(0, reduce(lambda n, seg: n * len(seg), segments, 1))] | |
if __name__ == '__main__': | |
expanded=expand_vars("foo $bar bas $bam", | |
{'$bar': ["fee", "fie", "foe"], '$bam': ["tick", "tock"]}) | |
joined=join_segments(expanded) | |
print "\n".join(joined) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment