How to get all subsets of a set? (powerset)

前端 未结 28 2462
庸人自扰
庸人自扰 2020-11-22 05:18

Given a set

{0, 1, 2, 3}

How can I produce the subsets:

[set(),
 {0},
 {1},
 {2},
 {3},
 {0, 1},
 {0, 2},
 {0, 3},
 {1, 2}         


        
28条回答
  •  伪装坚强ぢ
    2020-11-22 05:41

    Getting all the subsets with recursion. Crazy-ass one-liner

    from typing import List
    
    def subsets(xs: list) -> List[list]:
        return subsets(xs[1:]) + [x + [xs[0]] for x in subsets(xs[1:])] if xs else [[]]
    

    Based on a Haskell solution

    subsets :: [a] -> [[a]]
    subsets [] = [[]]
    subsets (x:xs) = map (x:) (subsets xs) ++ subsets xs
    

提交回复
热议问题