File indexing completed on 2025-01-18 09:15:42
0001 from itertools import chain, cycle, dropwhile, starmap, tee
0002
0003
0004 def skip_common_prefix(iters: list):
0005 """Given a list of iterators, skips values until at least one iterator differs from the others. Returns the remaining iterators.
0006
0007 >>> [list(iter) for iter in skip_common_prefix(["hello"])]
0008 [['h', 'e', 'l', 'l', 'o']]
0009 >>> [list(iter) for iter in skip_common_prefix(["hello", "world!"])]
0010 [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd', '!']]
0011 >>> [list(iter) for iter in skip_common_prefix([[3, 2, 1], [1, 2, 3, 4]])]
0012 [[3, 2, 1], [1, 2, 3, 4]]
0013 >>> [list(iter) for iter in skip_common_prefix([[1, 2, 3], [1, 2, 3, 4]])]
0014 [[], [4]]
0015 """
0016
0017 iters = list(map(iter, iters))
0018 if len(iters) == 0:
0019 raise ValueError("iters must not be empty")
0020 elif len(iters) == 1:
0021 tuple_iters = [zip(*iters)]
0022 else:
0023 tuple_iters = tee(
0024 dropwhile(lambda vals: all(val == vals[0] for val in vals), zip(*iters)),
0025 len(iters),
0026 )
0027 return list(starmap(
0028 lambda ix, tuple_iter: chain(map(lambda t: t[ix], tuple_iter), iters[ix]),
0029 enumerate(tuple_iters)
0030 ))