Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Accept Three Digits and Print all Possible Combinations from the Digits
When generating all possible combinations of three digits, we can use nested loops to create permutations where each digit appears exactly once in different positions. This approach uses three nested loops with conditional checks.
Example
first_num = int(input("Enter the first number..."))
second_num = int(input("Enter the second number..."))
third_num = int(input("Enter the third number..."))
digits = []
print("The first number is")
print(first_num)
print("The second number is")
print(second_num)
print("The third number is")
print(third_num)
digits.append(first_num)
digits.append(second_num)
digits.append(third_num)
print("All possible combinations:")
for i in range(0, 3):
for j in range(0, 3):
for k in range(0, 3):
if(i != j and j != k and k != i):
print(digits[i], digits[j], digits[k])
Output
Enter the first number...3 Enter the second number...5 Enter the third number...8 The first number is 3 The second number is 5 The third number is 8 All possible combinations: 3 5 8 3 8 5 5 3 8 5 8 3 8 3 5 8 5 3
How It Works
The algorithm uses three nested loops to generate all possible arrangements:
The three digits are taken as input from the user
An empty list called
digitsis created to store the numbersThe input numbers are displayed and appended to the list
Three nested loops iterate through indices 0, 1, and 2
The condition
i != j and j != k and k != iensures each digit appears only once per combinationValid combinations are printed using the list indices
Alternative Using itertools
Python's itertools module provides a built-in function for permutations ?
import itertools
digits = [3, 5, 8]
print("All possible combinations using itertools:")
for combo in itertools.permutations(digits):
print(combo[0], combo[1], combo[2])
All possible combinations using itertools: 3 5 8 3 8 5 5 3 8 5 8 3 8 3 5 8 5 3
Conclusion
Using nested loops with conditional checks generates all permutations of three digits. The itertools.permutations() function provides a more concise alternative for the same result.
