รับตัวเลข 3 หลักจากผู้ใช้ แล้วแสดง Permutation ทั้งหมด 6 แบบ โดยใช้ Nested Loop
ตัวอย่างโค้ด
a = int(input("First digit: "))
b = int(input("Second digit: "))
c = int(input("Third digit: "))
digits = [a, b, c]
print("All permutations:")
for i in range(3):
for j in range(3):
for k in range(3):
if i != j and j != k and k != i:
print(digits[i], digits[j], digits[k])ผลลัพธ์
First digit: 3 Second digit: 5 Third digit: 8 All permutations: 3 5 8 3 8 5 5 3 8 5 8 3 8 3 5 8 5 3
คำอธิบาย
เก็บ 3 ตัวเลขในลิสต์
digits3 Nested loops index i, j, k = 0,1,2
เงื่อนไข
i!=j and j!=k and k!=iให้ index ทั้ง 3 ต่างกันได้ 3! = 6 permutation
วิธีสั้นกว่า:
itertools.permutations(digits)