Nab*_*ikh -2 python combinations permutation
from itertools import combinations
def n_length_combo(arr, n):
# using set to deal
# with duplicates
return list(combinations(arr, n))
# Driver Function
if __name__ == "__main__":
arr = '01'
n = 3
print (n_length_combo([x for x in arr], n) )
Run Code Online (Sandbox Code Playgroud)
想要 0 和 1 的 3 个组合。尝试了上面的示例,但它不起作用
您正在寻找笛卡尔积,而不是 的组合或排列[0, 1]。为此,您可以使用itertools.product.
from itertools import product
items = [0, 1]
for item in product(items, repeat=3):
print(item)
Run Code Online (Sandbox Code Playgroud)
这会产生您正在寻找的输出(尽管顺序略有不同):
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2073 次 |
| 最近记录: |