Skip to content

Instantly share code, notes, and snippets.

@marskar
Last active November 13, 2019 03:24
Show Gist options
  • Save marskar/e7bb8fd9ae42052864125aaf82b33ad3 to your computer and use it in GitHub Desktop.
Save marskar/e7bb8fd9ae42052864125aaf82b33ad3 to your computer and use it in GitHub Desktop.
Ceci n'est pas une chaîne⛓!
from pathlib import Path
from functools import partial
def chaine(data, *funcs,
global_assign=False,
print_results=False,
write_results=False,
**kwargs):
chaine_options = any([global_assign, print_results, write_results])
if chaine_options:
fill_count = len(str(len(funcs)))
for i, f in enumerate(funcs):
try:
fname = f.__name__
except AttributeError:
fname = f.func.__name__
fargs = kwargs.get(fname, None)
if type(fargs) == dict:
data = f(data, **fargs)
elif isinstance(fargs, (list, tuple)):
data = f(data, *fargs)
elif fargs is not None:
data = f(data, fargs)
else:
data = f(data)
if chaine_options:
istring = str(i).zfill(fill_count)
if global_assign:
globals()[f"step{istring}_{fname}_result"] = data
if print_results:
print(f"The result of running {fname} (step {istring}) is {data}.")
if write_results:
Path(f"{istring}_{fname}_result.txt").write_text(data)
return data
fun_list = [
range,
partial(map, lambda x: str(x)),
" ".join
]
chaine(
4,
range,
partial(map, lambda x: str(x)),
" ".join
)
chaine(4, *fun_list)
" ".join(map(lambda x: str(x), range(4)))
# '0 1 2 3'
fun_list = [
range,
sum,
chr,
]
arg_dict = dict(range=[6, 2])
chaine(
1,
range,
sum,
chr,
range=[6, 2],
)
chaine(1, *fun_list, **arg_dict)
chr(sum(range(1, 6, 2)))
# '\t'
fun_list = [
range,
sum,
chr,
lambda x: x * 3 + "!"
]
chaine(
9,
range,
sum,
chr,
lambda x: x * 3 + "!",
)
chaine(9, *fun_list)
chr(sum(range(9))) * 3 + "!"
# '$$$!'
fun_list = [
range,
sum,
pow,
chr,
]
arg_dict = dict(pow=2)
chaine(
3,
range,
sum,
pow,
chr,
pow=2
)
chaine(3, *fun_list, **arg_dict)
chr(pow(sum(range(3)), 2))
# '\t'
fun_list = [
set,
list,
sorted,
enumerate,
dict,
]
arg_dict = dict(sorted={"reverse": True})
chaine(
"aabbbcc",
set,
list,
sorted,
enumerate,
dict,
sorted={"reverse": True}
)
chaine("aabbbcc", *fun_list, **arg_dict)
dict(enumerate(sorted(list(set("aabbbcc")), reverse=True)))
# {0: 'c', 1: 'b', 2: 'a'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment