fork(1) download
  1. from itertools import combinations, count
  2.  
  3. def interleave(a, b):
  4. empty = object()
  5. n = len(a) + len(b)
  6. # enumerate placements of a's items into n seats
  7. for a_indices in combinations(range(n), len(a)):
  8. L = [empty] * n
  9. for i, x in zip(a_indices, a): # put a's items into place
  10. L[i] = x
  11. it = iter(b)
  12. for i, x in enumerate(L): # fill empty seats with b's items
  13. if x is empty:
  14. L[i] = next(it)
  15. yield L
  16.  
  17. print(list(interleave([1,2], [3,4])))
  18.  
  19. def where(a, b, a_indices):
  20. """Yield a+b's items putting a's items at a_indices positions."""
  21. a, b, a_indices = iter(a), iter(b), iter(a_indices)
  22. ia = next(a_indices, -1)
  23. for i in count():
  24. if i == ia:
  25. yield next(a)
  26. ia = next(a_indices, -1)
  27. else:
  28. yield next(b)
  29.  
  30. def interleave_where(a, b):
  31. for a_indices in combinations(range(len(a) + len(b)), len(a)):
  32. yield where(a, b, a_indices)
  33.  
  34. print([list(g) for g in interleave_where([1,2], [3,4])])
Success #stdin #stdout 0.06s 9568KB
stdin
Standard input is empty
stdout
[[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 4, 2], [3, 1, 2, 4], [3, 1, 4, 2], [3, 4, 1, 2]]
[[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 4, 2], [3, 1, 2, 4], [3, 1, 4, 2], [3, 4, 1, 2]]