Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. def unzip(seq):
  3.     start = True
  4.     for next in seq:
  5.         if start:
  6.             result = [[] for _ in xrange(len(next))]
  7.             start = False
  8.         for i,v in enumerate(next):
  9.             result[i].append(v)
  10.     return result
  11.  
  12. def xunzip(seq):
  13.     it = iter(seq)
  14.     next = it.next()
  15.     width = len(next)
  16.     results = []
  17.     buffer_ = [{"tuple": next, "consumed": 0}]
  18.     # This is a list to workaround the non-existence
  19.     # of the "nonlocal" keyword in python 2
  20.     buffer_base = [0]
  21.     for i in xrange(width):
  22.         def freeze_i(j):
  23.             def unzipper():
  24.                 offset = 0
  25.                 while True:
  26.                     index = offset - buffer_base[0]
  27.                     if not (offset < len(buffer_) + buffer_base[0]):
  28.                         buffer_.append({"tuple": it.next(), "consumed": 0})
  29.                     buffer_[index]["consumed"] += 1
  30.                     value = buffer_[index]["tuple"][j]
  31.                     if buffer_[index]["consumed"] == width:
  32.                         buffer_.pop(0)
  33.                         buffer_base[0] += 1
  34.                     yield value
  35.                     offset += 1
  36.             unzipper.func_name = "seq_%d" % j
  37.             return unzipper
  38.         results.append(freeze_i(i)())
  39.     return results
  40.    
  41.  
  42. if __name__ == "__main__":
  43.     import random
  44.     a = zip(range(10), range(10,20), range(20,30))
  45.     print unzip(a)
  46.     b = xunzip(a)
  47.     finished_count = [0,0,0]
  48.     unpack = [-1, -1, -1]
  49.     while sum(finished_count) < len(b):
  50.         index = random.randrange(len(b))
  51.         try:
  52.             unpack[index] = b[index].next()
  53.             buffer_lenght = len(b[index].gi_frame.f_locals["buffer_"])
  54.         except StopIteration:
  55.             finished_count[index] = 1
  56.             buffer_lenght = "Unknown"
  57.         print unpack, "Buffer lenght: ", buffer_lenght
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement