Getting the subsets of a set in Python

前端 未结 7 2069
清歌不尽
清歌不尽 2020-12-03 23:19

Suppose we need to write a function that gives the list of all the subsets of a set. The function and the doctest is given below. And we need to complete the whole definitio

7条回答
  •  旧巷少年郎
    2020-12-03 23:55

    If you want to get all subsets without using itertools or any other libraries you can do something like this.

    def generate_subsets(elementList):
        """Generate all subsets of a set""" 
        combination_count = 2**len(elementList)
    
        for i in range(0, combination_count):   
            tmp_str = str(bin(i)).replace("0b", "")
            tmp_lst = [int(x) for x in tmp_str]
    
            while (len(tmp_lst) < len(elementList)):
                tmp_lst = [0] + tmp_lst
    
            subset = list(filter(lambda x : tmp_lst[elementList.index(x)] == 1, elementList))
            print(subset)
    

提交回复
热议问题