Guest User

列出一個列表中所有子集合

a guest
Dec 4th, 2022
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. def powerset(iterable):
  2.     # modified from itertools.combinations example:
  3.     # https://docs.python.org/ja/3/library/itertools.html#itertools.combinations
  4.     # powerset("ABCD") --> _ A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD
  5.     # powerset(range(4)) --> _ 0 1 2 3 01 02 03 12 13 23 012 013 023 123 0123
  6.    
  7.     pool = tuple(iterable)
  8.     n = len(pool)
  9.     for r in range(n + 1):
  10.         indices = list(range(r))
  11.         yield list(pool[i] for i in indices)
  12.         while True:
  13.             for i in reversed(range(r)):
  14.                 if indices[i] != i + n - r:
  15.                     break
  16.             else:
  17.                 break
  18.             indices[i] += 1
  19.             for j in range(i + 1, r):
  20.                 indices[j] = indices[j - 1] + 1
  21.             yield list(pool[i] for i in indices)
  22.  
  23. list(powerset([1, 2, 3, 4]))
  24.  
Tags: powerset
Advertisement
Add Comment
Please, Sign In to add comment