My actual problem is much larger, but the gist of it is something like:
def rec_func(it, newit, idx=0, seen_5=False, even_seen=0):
num = next(it, None)
if num is None:
return newit
elif num == 5: seen_5 = True
elif num&1==0: even_seen +=1
else: num*=20
newit.append(num)
print '[{}] seen_5 = {}, even_seen = {}'.format(idx, seen_5, even_seen)
return rec_func(it, newit, idx+1, seen_5, even_seen)
Run with (http://ideone.com/4kBbhn):
a = []
rec_func(iter(xrange(10)), a)
print 'a =', a
But there are some serious problems with this design, recursion isn't that efficient in Python and a list is being created and passed through just for its result (which isn't a generator). Trying to get this:
a = tuple(itertools.<something>(func, iter(xrange(10)))
print a # same answer as before
How do I? - All I can think of is:
def func(num, state):
if num == 5: state['seen_5'] = True
elif num&1==0: state['even_seen'] +=1
else: num*=20
print '[?] seen_5 = {}, even_seen = {}'.format(state['seen_5'],
state['even_seen'])
return num
_state = {'seen_5': False, 'even_seen': 0}
print tuple(imap(partial(func, state=_state), xrange(10)))
Which works, but seems kind of horrible... is there a functional solution?