Python 3 - cumulative functions alternatives -
i wondering if there more pythonic, or alternative, way this. want compare results out of cumulative functions. each functions modifies output of previous , see, after each of functions, effect is. beware in order actual results after running main functions, 1 last function needed calculate something. in code, thing looks (just kind of pseudocode):
for textfile in path: data = dostuff1(textfile) calculateandprint() textfile in path: data = dostuff1(textfile) data = dostuff2(data ) calculateandprint() textfile in path: data = dostuff1(textfile) data = dostuff2(data ) data = dostuff3(data ) calculateandprint()
as can see, n
functions need 1/2(n(n+1))
manually made loops. there, said, more pythonic (for example list functions?) clean code , make shorter , manageable when added more , more functions?
the actual code, documents
custom object:
for doc in documents: doc.list_strippedtext = preparedata(doc.text) bow = createbow(documents) doc in documents: doc.list_strippedtext = preparedata(doc.text) doc.list_strippedtext = preprocess(doc.list_strippedtext) bow = createbow(documents) doc in documents: doc.list_strippedtext = preparedata(doc.text) doc.list_strippedtext = preprocess(doc.list_strippedtext) doc.list_strippedtext = abbreviations(doc.list_strippedtext) bow = createbow(documents)
while small part, more functions need added.
you define set of chains, applied functools.reduce()
from functools import reduce chains = ( (dostuff1,), (dostuff1, dostuff2), (dostuff1, dostuff2, dostuff3), ) textfile in path: chain in chains: data = reduce(lambda data, func: func(data), chain, textfile) calculateandprint(data)
the reduce()
call func3(func2(func1(textfile))
if chain
contained 3 functions.
i assumed here wanted apply calculateandprint()
per textfile in path after chain of functions has been applied.
each iteration of for chain in chains
loop represents 1 of dostuffx
loop bodies in original example, loop through for textfile in path
once.
you can swap loops; adjusting example:
for chain in chains: doc in documents: doc.list_strippedtext = reduce(lambda data, func: func(data), chain, doc.text) bow = createbow(documents)
Comments
Post a Comment