Skip to content

Instantly share code, notes, and snippets.

@julian-savage
Created May 20, 2017 14:02
Show Gist options
  • Save julian-savage/e54e5bd628ec4b8eb7b32b0f6addac4b to your computer and use it in GitHub Desktop.
Save julian-savage/e54e5bd628ec4b8eb7b32b0f6addac4b to your computer and use it in GitHub Desktop.
Create all possible expansions for a string containing variables
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