I have long running program that I want to keep responsive. The algorithm is recursive, so sometimes even the sub-tasks in longer running calls can be longer than shorter whole runs. I have tried to make it to use yield but only ended up with list full of generators in various levels of recursive list structure (list also multilevel hierarchy, recording depth of calls). I finally made simple print the answers version, but it prints the answers in the end. I must not print the recursive calls results only, also the results need post processing before printing.
Is there simple pattern to make top level function call to yield values, but recursive calls to return the answers? Should I use for loops over recursive call results or make list() of the aswers from recursive calls? Should I just put depth parameter and return with depth > 0 and yield at depth 0?
Anyway, is there easy way to turn one answer per line outputing call to yield the lines back to main Python program? Or should I still return the full list from module call? I could easily run the os call version in separate interpreter with 'bg' in Linux system couldn't I?
The problem is complete covering problem, an example useful to my application would be for example to do same as this without the combinations, only adding numbers until they go over the limit recursively returning the exact sums:
from __future__ import print_function
def subset(seq, mask):
""" binary mask of len(seq) bits, return generator for the sequence """
return (c for ind,c in enumerate(seq) if mask & (1<<ind))
numbers = [1, 5, 3, 9, 4]
print('Numbers: ',numbers)
print('Possible sums',min(numbers),'..',sum(numbers))
for i in range(1,2**len(numbers)):
sub = list(subset(numbers, i))
print(sum(sub),'=',' + '.join(str(s) for s in sub))
print()
target = 11
print ('Finding subsequence for sum = %i' % target)
check = None
for check in (subset(numbers, mask)
for mask in range(1,2**len(numbers))
if sum(subset(numbers, mask))==target):
print (' + '.join(str(s) for s in check), ' = ', target)
if not check:
print('No solutions')