![](/img/trans.png)
[英]Why is it showing combination object instead of combination.I want to print all the possible combo of all lenghts
[英]I want the program to print all the possible combination
我希望 python 中的程序打印字符串的數字或字符的所有可能組合。 例如:123 213 231 132 321 312 金額為 !3 但我不知道如何處理。 我想過使用遞歸,但我不知道如何實現它。 提前致謝!
itertools.permutations
可以為你做到這一點。
import itertools
for c in itertools.permutations('123'):
print(''.join(c))
我們猜測
X="123"
我們想找到所有可能的組合。
import itertools
for c in itertools.permutations(X) :
print(''.join(c))
如果您不想導入 itertools 庫,可以使用GeeksForGeeks中的代碼:
def printCombination(arr, n, r):
data = [0]*r;
combinationUtil(arr, data, 0,
n - 1, 0, r);
def combinationUtil(arr, data, start,
end, index, r):
if (index == r):
for j in range(r):
print(data[j], end = " ");
print();
return;
i = start;
while(i <= end and end - i + 1 >= r - index):
data[index] = arr[i];
combinationUtil(arr, data, i + 1,
end, index + 1, r);
i += 1;
arr = [1, 2, 3, 4, 5];
r = 3;
n = len(arr);
printCombination(arr, n, r);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.