在這個簡單的 python 程序中,我們需要讀取三位數並列印所有的組合。這是一個中級 python 程序。
要理解這個例子,您應該了解以下 Python 編程主題:
- Python 語法
- Python 循環
- Python 決策語句
python 中三位數的所有組合怎麼列印?
在這個 python 程序中,我們需要接受三個數字,並且我們必須列印這些數字的所有組合。所以檢查這個 python 程序的唯一條件是數字中不會有任何重複。我們通過在 python 中使用 if 條件來保證這一點。
讓我們舉一個三位數 1,2,3 的例子來說明,那麼可能的組合是 1 2 3,1 3 2,2 3 1,我們永遠不會得到任何像 1 1 2 這樣重複的數字。
為了解決這個 python 問題,我們從用戶那裡獲取數字,並使用 python 語言中的append
方法將數字追加到列表中。我們使用三個 for 循環嵌套來獲取每個數字,並列印這些數字的所有組合。If
嵌套中的條件 for loop
將檢查組合數字中的任何重複。如果我們發現任何重複,那麼我們不會列印該組合。
演算法
步驟 1: 輸入 3 個輸入數字,使用輸入法將數字保存到變數中,並使用 Python 編程語言中的int()
將該字元串轉換為整數。
步驟 2: 用零值初始化列表。
第三步:使用append
方法,我們給 python 列表賦值。
STEP 4: 從零到 3 打開三個嵌套for loop
。數字的長度是取每一個數字,用 3 個數字檢查每一個組合。
步驟 5: 使用 python 語言中的if
條件檢查數字的值是否相同。如果不一樣,那麼用 python 列印那個組合。
Python 源代碼
a=int(input("Enter first number:"))
b=int(input("Enter second number:")) # accept the digits from the user
c=int(input("Enter third number:"))
d=[]
d.append(a)
d.append(b) # append the digits into the list
d.append(c)
for i in range(0,3):
for j in range(0,3): # nested for loop to take each combination
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(d[i],d[j],d[k])
輸出
Enter first number : 1
Enter second number : 2
Enter third number : 3
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/236707.html