Python程式查詢字串的所有子集
在Python中,字串的子集是原始字串的一部分字元序列。我們可以使用Python中的itertools模組找到字串的所有子集。在本文中,我們將瞭解如何透過組合字串中所有可能的字元來生成字串的所有子集。
語法
itertools.combination(string,r)
itertools模組的combination()函式接受字串和r作為輸入,r表示可能的不同字串組合的大小。它返回所有可能的字串字元組合。
演算法
初始化一個名為combination的空列表
使用for迴圈,使用itertools.combination函式生成字串中所有可能的字元組合。
過濾掉不是原始字串子集的組合
返回子集
示例
在下面的示例中,我們首先匯入itertools模組來生成字串中所有可能的字元組合。find_subsets()函式接受一個字串作為輸入,並返回字串的所有可能的子集。find_subset()方法首先建立一個空列表來儲存所有子集。然後,在for迴圈和itertools.combination()函式的幫助下,它生成字串的所有可能的子集並將它們儲存在combination列表中。在所有組合生成並存儲在combination列表中之後,我們需要過濾掉不是原始字串子集的字串,並將這些子集儲存在名為subset的列表中。然後,該函式將subset作為字串的所有可能的子集返回。
import itertools def find_subsets(string): # Get all possible combinations of characters in the string combinations = [] for i in range(len(string) + 1): combinations += itertools.combinations(string, i) # Filter out the ones that are not subsets of the original string subsets = [] for c in combinations: subset = ''.join(c) if subset != '': subsets.append(subset) return subsets # Test the function string = 'abc' subsets = find_subsets(string) print(subsets)
輸出
['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
結論
在本文中,我們討論瞭如何使用Python中的itertools模組生成字串的所有可能的子集。一旦生成了字串中所有可能的字元組合,我們就需要過濾掉不是原始字串子集的字串。結果,我們得到了字串的所有可能的子集。
廣告