efficient idiomatic queue?

Paul Rubin phr-n2002a at nightsong.com
Tue Jan 15 01:41:44 EST 2002


How's this (untested; uses nested scopes).  It uses extra temp space
the size of the input, but runs in the correct order time.

def merge(a,b):
   ia, ib = 0, 0    # indices
   def next():
      # peel next element off a or b.
      m = 0         # selector between a and b
      if ia < len(a) and ib < len(b):
         m = a[ia] < b[ib]
      else:
         m = ia >= len(a)

      if m == 0:
         x, ia = a[ia], ia+1
      else: 
         # if both a and b are exhausted, this throws IndexError.
         x, ib = b[ib], ib+1  
   return x

   result = []
   try:
      while 1:
         result.append(next())
   except IndexError:
      return result



More information about the Python-list mailing list