Skip to content

Commit 0c5092f

Browse files
author
majid shahbaz
committed
Matrix and 2D list implementations with examples
1 parent 0221ef2 commit 0c5092f

File tree

3 files changed

+586
-1
lines changed

3 files changed

+586
-1
lines changed

src/datastructures/lists/advance_list.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"""
33
To create a list from a other collections we can use list()
44
"""
5+
56
print("\n----------- Some List Operations-------------\n")
67
from_tuple_to_list = list(("a","b","c"))
78

@@ -246,4 +247,5 @@
246247
print(f"Row{row_index} →", end=" ")
247248
for item in row:
248249
print(f"{item:<7}", end="") # left-aligned with fixed width
249-
print()
250+
print()
251+
Lines changed: 347 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,347 @@
1+
# Matrix Operations in Python
2+
3+
A comprehensive collection of Python examples demonstrating common matrix operations and algorithms. This repository contains practical implementations for working with 2D arrays (matrices) in Python.
4+
5+
## Table of Contents
6+
7+
- [Overview](#overview)
8+
- [Examples Included](#examples-included)
9+
- [Getting Started](#getting-started)
10+
- [Code Examples](#code-examples)
11+
- [Example Outputs](#example-outputs)
12+
- [Key Concepts](#key-concepts)
13+
- [Contributing](#contributing)
14+
15+
## Overview
16+
17+
This project demonstrates various matrix operations commonly used in programming interviews, data analysis, and algorithm development. Each example includes multiple solution approaches, from basic loops to advanced list comprehensions.
18+
19+
## Examples Included
20+
21+
### 1. Count Element Occurrences
22+
Count how many times each number appears in a matrix.
23+
24+
**Features:**
25+
- Dictionary-based counting
26+
- List comprehension approach
27+
- Efficient element tracking
28+
29+
### 2. Sum of All Elements
30+
Calculate the total sum of all numbers in a 2D array.
31+
32+
**Methods:**
33+
- Nested loop approach
34+
- List comprehension with `sum()`
35+
36+
### 3. Row Sum Calculation
37+
Print the sum of elements in each row.
38+
39+
**Output Format:**
40+
```
41+
Sum of Row 0 = 6
42+
Sum of Row 1 = 15
43+
Sum of Row 2 = 24
44+
```
45+
46+
### 4. Column Sum Calculation
47+
Calculate and display the sum of elements in each column.
48+
49+
**Algorithm:**
50+
- Iterate through column indices
51+
- Sum elements from the same column across all rows
52+
53+
### 5. Find Maximum and Minimum
54+
Identify the largest and smallest elements in the matrix.
55+
56+
**Approach:**
57+
- Initialize with first element
58+
- Compare with all other elements
59+
- Track both max and min simultaneously
60+
61+
### 6. Even/Odd Number Analysis
62+
Count and categorize numbers as even or odd.
63+
64+
**Features:**
65+
- Separate counters for even/odd numbers
66+
- Lists to store actual even/odd values
67+
- Modulo operation for classification
68+
69+
### 7. Matrix Transpose (Advanced)
70+
Convert rows to columns and vice versa.
71+
72+
**Two Solutions:**
73+
1. **Nested Loops:** Traditional approach with explicit row/column creation
74+
2. **List Comprehension:** Pythonic one-liner solution
75+
76+
## Code Examples
77+
78+
### 1. Count Element Occurrences
79+
80+
```python
81+
# Solution 1: Using Dictionary
82+
matrix_two = [
83+
[1, 2, 3],
84+
[4, 5, 2],
85+
[5, 8, 3]
86+
]
87+
88+
count = {}
89+
for row in matrix_two:
90+
for element in row:
91+
if element not in count:
92+
count[element] = 1
93+
else:
94+
count[element] += 1
95+
96+
print("Occurrences of elements in matrix:")
97+
for key, val in count.items():
98+
print(f"{key}{val}")
99+
```
100+
101+
```python
102+
# Solution 2: Using List Comprehension
103+
list_comp = [item for row in matrix_two for item in row]
104+
count = {}
105+
for element in list_comp:
106+
count[element] = count.get(element, 0) + 1
107+
```
108+
109+
### 2. Sum of All Elements
110+
111+
```python
112+
# Method 1: Nested loops
113+
sum_of_elements = 0
114+
for row in matrix:
115+
for element in row:
116+
sum_of_elements += element
117+
118+
print(f"The sum of all elements: {sum_of_elements}")
119+
```
120+
121+
```python
122+
# Method 2: List comprehension
123+
sum_of_elements = sum([item for row in matrix for item in row])
124+
print(f"The sum using comprehension: {sum_of_elements}")
125+
```
126+
127+
### 3. Row Sum Calculation
128+
129+
```python
130+
for i, row in enumerate(matrix):
131+
row_sum = sum(row)
132+
print(f"Sum of Row {i} = {row_sum}")
133+
```
134+
135+
### 4. Column Sum Calculation
136+
137+
```python
138+
num_col = len(matrix_two[0])
139+
140+
for col in range(num_col):
141+
total_sum = 0
142+
for row in matrix_two:
143+
total_sum += row[col]
144+
print(f"Sum of Column {col} = {total_sum}")
145+
```
146+
147+
### 5. Find Maximum and Minimum
148+
149+
```python
150+
max_element = matrix_two[0][0]
151+
min_element = matrix_two[0][0]
152+
153+
for row in matrix_two:
154+
for element in row:
155+
if element > max_element:
156+
max_element = element
157+
if element < min_element:
158+
min_element = element
159+
160+
print(f"Max element: {max_element}")
161+
print(f"Min element: {min_element}")
162+
```
163+
164+
### 6. Even/Odd Number Analysis
165+
166+
```python
167+
even_odd_dict = {"even": 0, "odd": 0}
168+
even_numbers = []
169+
odd_numbers = []
170+
171+
for row in matrix_two:
172+
for element in row:
173+
if element % 2 == 0:
174+
even_odd_dict["even"] += 1
175+
even_numbers.append(element)
176+
elif element % 2 == 1:
177+
even_odd_dict["odd"] += 1
178+
odd_numbers.append(element)
179+
180+
print(f"Number of Even elements: {even_odd_dict['even']}")
181+
print(f"Number of Odd elements: {even_odd_dict['odd']}")
182+
print(f"Even elements: {even_numbers}")
183+
print(f"Odd elements: {odd_numbers}")
184+
```
185+
186+
### 7. Matrix Transpose
187+
188+
```python
189+
# Solution 1: Using nested loops
190+
transpose_matrix = []
191+
rows = len(matrix_two)
192+
cols = len(matrix_two[0])
193+
194+
for col in range(cols):
195+
new_row = []
196+
for i in range(rows):
197+
new_row.append(matrix_two[i][col])
198+
transpose_matrix.append(new_row)
199+
200+
print("Transpose of matrix:")
201+
for row in transpose_matrix:
202+
print(row)
203+
```
204+
205+
```python
206+
# Solution 2: Using list comprehension
207+
transpose_matrix = [[matrix_two[i][j] for i in range(rows)]
208+
for j in range(len(matrix_two[0]))]
209+
print("Transpose of matrix:")
210+
for row in transpose_matrix:
211+
print(row)
212+
```
213+
214+
## Getting Started
215+
216+
### Prerequisites
217+
- Python 3.x
218+
- No external libraries required
219+
220+
### Running the Code
221+
222+
1. Clone or download the code file
223+
2. Run the Python script:
224+
```bash
225+
python matrix_operations.py
226+
```
227+
228+
### Sample Matrix Used
229+
```python
230+
matrix_two = [
231+
[1, 2, 3],
232+
[4, 5, 2],
233+
[5, 8, 3]
234+
]
235+
```
236+
237+
## Example Outputs
238+
239+
### Element Occurrence Count
240+
```
241+
Occurrences of elements in matrix:
242+
1 → 1
243+
2 → 2
244+
3 → 2
245+
4 → 1
246+
5 → 2
247+
8 → 1
248+
```
249+
250+
### Matrix Transpose
251+
**Original Matrix:**
252+
```
253+
[1, 2, 3]
254+
[4, 5, 2]
255+
[5, 8, 3]
256+
```
257+
258+
**Transposed Matrix:**
259+
```
260+
[1, 4, 5]
261+
[2, 5, 8]
262+
[3, 2, 3]
263+
```
264+
265+
### Even/Odd Analysis
266+
```
267+
Number of Even elements: 4
268+
Number of Odd elements: 5
269+
Even elements: [2, 4, 2, 8]
270+
Odd elements: [1, 3, 5, 5, 3]
271+
```
272+
273+
## Key Concepts
274+
275+
### Data Structures Used
276+
- **2D Lists:** For matrix representation
277+
- **Dictionaries:** For counting and key-value storage
278+
- **Lists:** For collecting specific elements
279+
280+
### Programming Techniques
281+
- **Nested Loops:** For matrix traversal
282+
- **List Comprehensions:** For concise, Pythonic solutions
283+
- **Enumerate:** For index tracking
284+
- **Dictionary Methods:** `.get()` for safe key access
285+
286+
### Algorithm Patterns
287+
- **Matrix Traversal:** Row-by-row and column-by-column access
288+
- **Element Counting:** Using dictionaries as counters
289+
- **Matrix Transformation:** Transpose operation
290+
- **Aggregation:** Sum, max, min operations
291+
292+
### Code Structure
293+
294+
Each example follows this pattern:
295+
1. **Problem Statement:** Clear description of the task
296+
2. **Algorithm Explanation:** Step-by-step approach
297+
3. **Implementation:** Working code with comments
298+
4. **Alternative Solutions:** Different approaches when applicable
299+
5. **Sample Output:** Expected results
300+
301+
### Complexity Analysis
302+
303+
| Operation | Time Complexity | Space Complexity |
304+
|-----------|----------------|------------------|
305+
| Element Count | O(m×n) | O(k) where k = unique elements |
306+
| Sum All Elements | O(m×n) | O(1) |
307+
| Row/Column Sums | O(m×n) | O(1) |
308+
| Find Max/Min | O(m×n) | O(1) |
309+
| Matrix Transpose | O(m×n) | O(m×n) |
310+
311+
Where m = number of rows, n = number of columns
312+
313+
### Learning Objectives
314+
315+
After studying this code, you'll understand:
316+
- Matrix manipulation fundamentals
317+
- Dictionary usage for counting
318+
- List comprehension patterns
319+
- Nested loop structures
320+
- Matrix transpose algorithms
321+
- Python best practices for 2D data
322+
323+
### Customization
324+
325+
You can easily modify the examples by:
326+
- Changing the sample matrix values
327+
- Adding new matrix operations
328+
- Implementing different algorithms
329+
- Extending to larger matrices
330+
331+
### Notes
332+
333+
- All solutions handle rectangular matrices (equal row lengths)
334+
- Dictionary approach is efficient for sparse counting
335+
- List comprehensions provide more Pythonic solutions
336+
- Examples include both basic and advanced implementations
337+
338+
### Contributing
339+
340+
Feel free to:
341+
- Add new matrix operations
342+
- Optimize existing solutions
343+
- Improve documentation
344+
- Add error handling
345+
- Extend to 3D arrays
346+
347+
---

0 commit comments

Comments
 (0)