0% found this document useful (0 votes)
4 views3 pages

Python 1

The document provides Python code examples for handling sparse matrices, including displaying all elements of a sparse matrix and counting non-zero elements. It also includes a method to create a specific array structure based on given dimensions. The examples illustrate how to initialize matrices, fill them with values, and print the results.

Uploaded by

Md Farhan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Python 1

The document provides Python code examples for handling sparse matrices, including displaying all elements of a sparse matrix and counting non-zero elements. It also includes a method to create a specific array structure based on given dimensions. The examples illustrate how to initialize matrices, fill them with values, and print the results.

Uploaded by

Md Farhan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Write a python program to show all elements of sparse matrix

# Sparse matrix representation using list of tuples

# Format: (row, column, value)

sparse_matrix = [

(0, 1, 5),

(1, 2, 8),

(2, 0, 3)

# Define matrix size

rows = 3

cols = 3

# Initialize full matrix with zeros

matrix = [[0 for _ in range(cols)] for _ in range(rows)]

# Fill non-zero values

for r, c, v in sparse_matrix:

matrix[r][c] = v

# Display full matrix

print("Full Matrix:")

for row in matrix:


for element in row:

print(element, end=" ")

print()

2. Also count how many non zero elements are there

# Sparse matrix

matrix = [

[0, 0, 3],

[0, 5, 0],

[7, 0, 0]

count = 0

print("Matrix elements are:")

for row in matrix:

for element in row:

print(element, end=" ")

if element != 0:

count += 1

print()

print("Number of non-zero elements =", count)


3. 1. Create an array of n xm dimensions using python to show following structure

10000
11000
11100
11110
11111

n=5
m=5

arr = []

for i in range(n):
row = []
for j in range(m):
if j <= i:
[Link](1)
else:
[Link](0)
[Link](row)

for row in arr:


for val in row:
print(val, end="")
print()

You might also like