Skip to content

Instantly share code, notes, and snippets.

@dela3499
Last active March 1, 2016 09:50
Show Gist options
  • Save dela3499/f14aa05e249dc1324ca0 to your computer and use it in GitHub Desktop.
Save dela3499/f14aa05e249dc1324ca0 to your computer and use it in GitHub Desktop.
Generates combinations of elements in multiple lists. https://repl.it/BrPA/0 https://twitter.com/dela3499/status/704220067387437056
def thread_last(val, *forms):
""" Thread value through a sequence of functions/forms
>>> def double(x): return 2*x
>>> def inc(x): return x + 1
>>> thread_last(1, inc, double)
4
If the function expects more than one input you can specify those inputs
in a tuple. The value is used as the last input.
>>> def add(x, y): return x + y
>>> def pow(x, y): return x**y
>>> thread_last(1, (add, 4), (pow, 2)) # pow(2, add(4, 1))
32
So in general
thread_last(x, f, (g, y, z))
expands to
g(y, z, f(x))
>>> def iseven(x):
... return x % 2 == 0
>>> list(thread_last([1, 2, 3], (map, inc), (filter, iseven)))
[2, 4]
See Also:
thread_first
"""
def evalform_back(val, form):
if callable(form):
return form(val)
if isinstance(form, tuple):
func, args = form[0], form[1:]
args = args + (val,)
return func(*args)
return ft.reduce(evalform_back, forms, val)
import itertools as it
import functools as ft
# from toolz import thread_last
def println(x):
for xi in x:
print(xi)
def all_unique(x):
return len(x) == len(set(x))
# List (List String) -> List String
def generate_combinations(xs):
return thread_last(
it.product(*xs),
(filter, all_unique), # drop repeats
# (map, lambda x: ' '.join(x)),
list)
format_string = "Create a {business} around {interest1} and {interest2}."
interests = "golf, generative art, programming, puerto rico".split(', ')
business_models = "subscription, pdf, gadget".split(', ')
keys = ["interest1","interest2","business"]
xs = [interests, interests, business_models]
# String -> List String -> List String -> String
def create_string(format_string, keys, replacements):
return format_string.format(**dict(zip(keys, replacements)))
strings = [create_string(format_string, keys, replacements)
for replacements in generate_combinations(xs)]
println(strings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment