Generate a python program to compute the cartesian product of two lists. list1 = [1,2,3]…
- User
Generate a python program to compute the cartesian product of two lists. list1 = [1,2,3] list2 = [4,5]
Assistant
Generate a python program to compute the cartesian product of two lists. list1 = [1,2,3] list2 = [4,5]
Problem: Generate a python program to compute the cartesian product of two lists. list1 = [1,2,3] list2 = [4,5]
Approach: supporting N iterables.
Time: O(∏|list_i|)
Space: O(depth) for recursion stack
Pros: Works with any number of input lists
Cons: Recursion overhead, stack depth limit
"""
Key considerations:
list1 = [1, 2, 3] and list2 = [4, 5]:Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
Output size: |A| × |B| = 3 × 2 = 6 pair
Time: O(n × m) Space: O(n × m) when converted to list
Pros: Optimized C implementation, handles edge cases Cons: Returns iterator, mu
Time: O(∏|list_i|) Space: O(depth) for recursion stack
Pros: Works with any number of input lists Cons: Recursion overhead, stack dep
Args:
list1: First iterable
list2: Second iterable
lazy: If True, returns generator; if False, returns list
Returns
Strings as iterables:") print(f" cartesian_eager('AB', '12') = {cartesian_eager('AB', '12')}")
Performance note print("\n" + "=" 6
Strings as iterables: cartesian_eager('AB', '12') = [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
Summary
| Method | Use Case | Memory |
Complexity: | O(n × m) — must visit each pair once |
Let me implement this solution.
</think>
# Cartesian Product Calculator
## Detailed Reasoning and Analysis
### Understanding the Problem
The **Cartesian product** of two sets A × B produces all possible ordered pairs (a, b) where a ∈ A and b ∈ B.
For `list1 = [1, 2, 3]` and `list2 = [4, 5]`:
Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
**Output size**: |A| × |B| = 3 × 2 = 6 pairs
---
### System Design Considerations
| Consideration | Analysis |
|---------------|----------|
| **Time Complexity** | O(n × m) — must visit each pair once |
| **Space Complexity** | Eager: O(n × m), Lazy: O(1) |
| **Memory** | For large lists (e.g., 10,000 × 10,000 = 100M pairs), eager evaluation could exhaust memory |
| **Type Flexibility** | Should handle any iterable, not just lists |
| **Empty Input** | Cartesian product with empty list = empty result |
| **Order Preservation** | Maintains input order in output pairs |
---
## Implementation
```python
"""
Cartesian Product Calculator
============================
Computes the Cartesian product of two iterables with multiple implementation
strategies for different use cases.
"""
from itertools import product
from typing import Iterable, List, Tuple, Generator, TypeVar, Union
# Type variables for generic typing
T = TypeVar('T')
U = TypeVar('U')
def cartesian_eager(list1: Iterable[T], list2: Iterable[U]) -> List[Tuple[T, U]]:
"""
Eager evaluation using list comprehension.
Time: O(n × m)
Space: O(n × m) - stores all pairs in memory
Pros: Simple, readable, fast for small datasets
Cons: Memory-intensive for large datasets
"""
return [(a, b) for a in list1 for b in list2]
def cartesian_generator(list1: Iterable[T], list2: Iterable[U]) -> Generator[Tuple[T, U], None, None]:
"""
Lazy evaluation using generator.
Time: O(n × m) total, O(1) per iteration
Space: O(1) - only holds current pair
Pros: Memory efficient, can process infinite iterables
Cons: Can only iterate once, slightly slower per iteration
"""
for a in list1:
for b in list2:
yield (a, b)
def cartesian_itertools(list1: Iterable[T], list2: Iterable[U]) -> List[Tuple[T, U]]:
"""
Using Python's built-in itertools.product.
Time: O(n × m)
Space: O(n × m) when converted to list
Pros: Optimized C implementation, handles edge cases
Cons: Returns iterator, must convert if list needed
"""
return list(product(list1, list2))
def cartesian_recursive(*iterables: Iterable) -> Generator[Tuple, None, None]:
"""
Recursive approach supporting N iterables.
Time: O(∏|list_i|)
Space: O(depth) for recursion stack
Pros: Works with any number of input lists
Cons: Recursion overhead, stack depth limit
"""
if not iterables:
yield ()
return
first, *rest = iterables
for item in first:
for remaining in cartesian_recursive(*rest):
yield (item,) + remaining
def cartesian_product(list1: Iterable[T],
list2: Iterable[U],
lazy: bool = False) -> Union[List[Tuple[T, U]], Generator[Tuple[T, U], None, None]]:
"""
Main interface with automatic selection strategy.
Args:
list1: First iterable
list2: Second iterable
lazy: If True, returns generator; if False, returns list
Returns:
List of tuples (eager) or generator (lazy)
Raises:
TypeError: If inputs are not iterable
"""
# Input validation
try:
iter(list1)
iter(list2)
except TypeError as e:
raise TypeError(f"Both inputs must be iterable: {e}")
if lazy:
return cartesian_generator(list1, list2)
return cartesian_eager(list1, list2)
# ============= DEMONSTRATION =============
if __name__ == "__main__":
# Test data
list1 = [1, 2, 3]
list2 = [4, 5]
print("=" * 60)
print("CARTESIAN PRODUCT CALCULATOR")
print("=" * 60)
print(f"\nInput Lists:")
print(f" list1 = {list1}")
print(f" list2 = {list2}")
print(f"\nExpected pairs: {len(list1)} × {len(list2)} = {len(list1) * len(list2)}")
# Method 1: Eager (List Comprehension)
print("\n" + "-" * 40)
print("Method 1: Eager Evaluation (List Comprehension)")
result_eager = cartesian_eager(list1, list2)
print(f"Result: {result_eager}")
# Method 2: Lazy (Generator)
print("\n" + "-" * 40)
print("Method 2: Lazy Evaluation (Generator)")
result_gen = cartesian_generator(list1, list2)
print(f"Generator object: {result_gen}")
print(f"Result: {list(result_gen)}")
# Method 3: itertools.product
print("\n" + "-" * 40)
print("Method 3: itertools.product (Recommended)")
result_itertools = cartesian_itertools(list1, list2)
print(f"Result: {result_itertools}")
# Method 4: Recursive (N-ary)
print("\n" + "-" * 40)
print("Method 4: Recursive (supports N lists)")
result_recursive = list(cartesian_recursive(list1, list2))
print(f"Result: {result_recursive}")
# Using main interface
print("\n" + "-" * 40)
print("Main Interface (lazy=False)")
result_main = cartesian_product(list1, list2, lazy=False)
print(f"Result: {result_main}")
# Edge cases
print("\n" + "=" * 60)
print("EDGE CASES")
print("=" * 60)
print("\n1. Empty list:")
print(f" cartesian_eager([], [1,2]) = {cartesian_eager([], [1, 2])}")
print("\n2. Different types:")
print(f" cartesian_eager([1, 2], ['a', 'b']) = {cartesian_eager([1, 2], ['a', 'b'])}")
print("\n3. Strings as iterables:")
print(f" cartesian_eager('AB', '12') = {cartesian_eager('AB', '12')}")
# Performance note
print("\n" + "=" * 60)
print("PERFORMANCE RECOMMENDATION")
print("=" * 60)
print("""
• Small datasets (< 10,000 pairs): Use eager evaluation
• Large datasets (> 10,000 pairs): Use lazy evaluation (generators)
• Production code: Use itertools.product (optimized C implementation)
• N-way products: Use recursive or itertools.product(*lists)
""")
============================================================
CARTESIAN PRODUCT CALCULATOR
============================================================
Input Lists:
list1 = [1, 2, 3]
list2 = [4, 5]
Expected pairs: 3 × 2 = 6
----------------------------------------
Method 1: Eager Evaluation (List Comprehension)
Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
----------------------------------------
Method 2: Lazy Evaluation (Generator)
Generator object: <generator object cartesian_generator at 0x...>
Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
----------------------------------------
Method 3: itertools.product (Recommended)
Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
----------------------------------------
Method 4: Recursive (supports N lists)
Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
----------------------------------------
Main Interface (lazy=False)
Result: [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
============================================================
EDGE CASES
============================================================
1. Empty list:
cartesian_eager([], [1,2]) = []
2. Different types:
cartesian_eager([1, 2], ['a', 'b']) = [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
3. Strings as iterables:
cartesian_eager('AB', '12') = [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
| Method | Use Case | Memory | Speed |
|---|---|---|---|
itertools.product | Production (recommended) | O(n×m) | ⭐ Fastest (C-optimized) |
| List comprehension | Small datasets, readability | O(n×m) | Fast |
| Generator | Large datasets, streaming | O(1) | On-demand |
| Recursive | N-way products | O(depth) | Slower (overhead) |