1、 有四個數字:1、2、3、4,能組成多少個互不相同且無重複數字的三位數?各是多少?
total = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != j and i != k and j != k:
print(i,j,k)
total += 1
print("total: ",total)
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
total: 24
一般的思路如上面所示,使用迴圈巢狀,然後判斷三個數不相等,最後輸出;
這是乙個排列問題,我們可以直接用排列的方法來解決,使用itertools庫中的函式
from itertools import permutations
total = 0
for i in permutations(range(1,5),3):
print(i)
total += 1
print("total: ",total)
(1, 2, 3)
(1, 2, 4)
(1, 3, 2)
(1, 3, 4)
(1, 4, 2)
(1, 4, 3)
(2, 1, 3)
(2, 1, 4)
(2, 3, 1)
(2, 3, 4)
(2, 4, 1)
(2, 4, 3)
(3, 1, 2)
(3, 1, 4)
(3, 2, 1)
(3, 2, 4)
(3, 4, 1)
(3, 4, 2)
(4, 1, 2)
(4, 1, 3)
(4, 2, 1)
(4, 2, 3)
(4, 3, 1)
(4, 3, 2)
total: 24
Python練手程式 02
2 使用 列印直角三角形 3 使用 列印乙個倒三角形,要求倒三角形是等邊三角形。並且行數由使用者輸入 guess num 98 while true print please input a number num input ifnot num.isdigit print 請輸入乙個整數!conti...
python練手小程式
python小白 usr bin env python coding utf 8 time 2019 11 5 8 53 author october file py 整數序列求和 n input 請輸入整數n sum 0 for i in range int n sum i 1print 1到n求...
python練手題目 Python練手題目(七)
1.計算重複字母出現的次數 編寫乙個函式,該函式將返回在輸入字串 現多次 不同的不區分大小寫的 字母字元和數字的計數。可以假定輸入字串僅包含字母 大寫和小寫 和數字。例如 abcde 0 no characters repeats more than once aabbcde 2 a and b a...