3種方法求子集_python ???

approach 1

def PowerSetsBinary(items):
    N = len(items)
    # generate all combination of N items
    # enumerate the 2**N possible combinations
    for i in range(2 ** N):
        combo = []
        for j in range(N):  # jth bit of Integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo
"""
[]
['a']
['b']
['a', 'b']
['c']
['a', 'c']
['b', 'c']
['a', 'b', 'c']
"""        

Question 1

  • 爲什麼是向右移動j位
  • 答:對二進制數向右移動j位, 是在減小該數字
  • 爲什麼是判斷除以2 餘1
  • 答: Explore it yourself !
  • 爲啥通過j下標來去items的值
  • 答:一方面, j的取值範圍和數組的對應關係, 另一方面, 每次向右移動j次,判斷結果除以2 餘1 來得到是否要取當前的下標對應的值很神奇

a_2(能不能把它修改成尾遞歸)

def PowerSetsRecursive(items):
    """Use recursive call to return all subsets of items, include empty set"""

    if len(items) == 0:
        # if the lsit is empty, return the empty list
        return [[]]

    subsets = []
    first_elt = items[0]  # first element
    rest_list = items[1:]

    # Strategy: Get all subsets of rest_list; 
    # for each of those subsets,a full subset list will contain both the original subset 
    # as well as a version of the subset that contains the first_elt(according to my a_2 思路,you will understand this)

    for partial_subset in PowerSetsRecursive(rest_list):
        subsets.append(partial_subset)
        next_subset = partial_subset[:] + [first_elt]
        subsets.append(next_subset)
    return subsets   # 遞歸退層中都要返回遞歸進層的那一個子集

a_2 思路

在這裏插入圖片描述

a_3

def PowerSetsRecursive2(items):
	# 我和你賭,不是看你要什麼,而是看我有什麼(items combine with results which the former need to depend on)
    result = [[]]   # the power set of the empty set has one element: the empty set
    for x in items:
    	# 兩個列表相加和extend同理
        result.extend([subset + [x] for subset in result])  # extend 會遍歷args/kwargs,然後將其加入到列表中
    return result

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章