Generating Permutations of Digits 1-4 in Python Without Repetition
Given the digits 1, 2, 3, and 4, how many distinct three-digit numbers can be formed without repeating any digit? This is a classic combinatorial problem equivalent to calculating permutations of 4 items taken 3 at a time, denoted as P(4,3) = 4! / (4-3)! = 24.
Brute-force Approach with Nested Loops
A straightforward solution uses three nested loops to enumerate all possilbe combinations, filtering out those with repeated digits.
total = 0
for a in range(1, 5):
for b in range(1, 5):
for c in range(1, 5):
if a != b and a != c and b != c:
total += 1
print(f"Combination #{total}: {a},{b},{c}")
Using itertools.permutations
Python's itertools module simplifies this task. We can generate all ordered permutations of length 3 from the set {'1','2','3','4'} and convert each tuple into an integer.
from itertools import permutations
numbers = [int(''.join(x)) for x in permutations('1234', 3)]
print(f"Total numbers: {len(numbers)}")
print(numbers)
This returns a list of 24 integers, each representing a valid three-digit number.
Extension: Handling Repeated Digits
If repetition were alllowed, we would use itertools.product to generate the Cartesian product.
from itertools import product
# With repetition: each position can be 1-4
numbers_with_rep = [int(''.join(x)) for x in product('1234', repeat=3)]
print(f"Total with repetition: {len(numbers_with_rep)}")
This produces 4^3 = 64 numbers.
Summary of itertools Combinatorial Iterators
| Iterator | Arguments | Description | Example |
|---|---|---|---|
product(p, q, ..., repeat=1) |
p, q, ... [repeat=1] | Cartesian product, equivalent to nested for loops | product('ABCD', repeat=2) gives AA, AB, ... DD |
permutations(p[, r]) |
p[, r] | r-length tuples, all possible orderings, no repeated elements | permutations('ABCD', 2) gives AB, AC, ... DC |
combinations(p, r) |
p, r | r-length tuples in sorted order, no repeated elements | combinations('ABCD', 2) gives AB, AC, AD, BC, BD, CD |
combinations_with_replacement(p, r) |
p, r | r-langth tuples in sorted order, with repeated elements allowed | combinations_with_replacement('ABCD',2) gives AA, AB, ... DD |