How to create generator to merge values from iterables in Python? -
i want create generator, can merge values iterables on fly (continuously) in endless look.
the main idea, generator produce values output each time, when ask it. so, main function endless loop, ask generator values 1 one , print them output.
while values comes iterators generator returns values 1 one print them output.
now, in code i'm passing values 1 list . not necessary collect values 1 single list before print.
def merge(*iterables): # create generator generator = (iter(current) current in iterables) # convert generator list iters = list(generator) # while have iterable while iters: #loop through each iterable in iters: try: # yields values 1 one yield i.__next__() except stopiteration: iters.remove(i)
when i'm running this:
>>> callmerge([1,5,9],[2,5],[1,6,10,11]) result is: [1, 1, 2, 5, 5, 6, 9, 10, 11]
to clear have example:
lets imagine taking balls numbers (like bingo) several black boxes.
we don't know number of balls in each box. can take balls boxes 1 one.
we know, each next ball same black box have number greater previous.
so, should takes balls black boxes , give on each step 1 ball smallest number our assistant.
so, question how can create generator, can merge values iterables on fly (continuously) in endless look? (also won't use list because of memory- know maybe itertools.chain(*iterables) option don't know how use)
def get_vals(*iterables): vals = [] in iterables: try: vals.append(next(it)) except stopiteration: vals.append(none) #keep indices same return vals def sort_merge(*iterables): iterables = [iter(it) in iterables] vals = get_vals(*iterables) while any(v not none v in vals): i, m = min(filter(lambda x: x[1] not none, enumerate(vals)), key=lambda x: x[1]) yield m try: vals[i] = next(iterables[i]) except stopiteration: vals[i] = none
you have compare values in order sort them. i'm not sure going give real benefit on doing sorted(itertools.chain(...))
, keeps len(iterables)
items in memory @ given time.
edit: make (or other iterator matter) repeat indefinitely use itertools.cycle
itertools.cycle(sort_merge([1,5,9],[2,5],[1,6,10,11]))
Comments
Post a Comment