Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python lấy tất cả tập con kích thước n của một tập hợp

Bài toán: cho một tập hợp, liệt kê tất cả tập con kích thước n.

Có 3 cách:

Dùng itertools.combinations()

import itertools
def findsubsets(s, n):
    return list(itertools.combinations(s, n))

s = {1,2,3,4,5}
n = 4
print(findsubsets(s, n))
[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]

Dùng map() và combinations()

from itertools import combinations
def findsubsets(s, n):
    return list(map(set, itertools.combinations(s, n)))

s = {1, 2, 3, 4, 5}
n = 4
print(findsubsets(s, n))
[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]

Dùng list comprehension

import itertools
def findsubsets(s, n):
    return [set(i) for i in itertools.combinations(s, n)]

s = {1, 2, 3, 4, 5}
n = 4
print(findsubsets(s, n))
[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]

Kết luận

Đã học lấy tất cả tập con kích thước n của tập hợp.