FDS Unit - 2
FDS Unit - 2
FDS Unit - 2
Cont...
Sequential Organization
Disadvantages:
1. Insertion and deletion of elements becomes complicated
due to sequential nature.
2. For sorting the data large continuous free block of memory
is required
3. Memory fragmentation occurs if we remove the elements
randomly.
Array as an Abstract Data Type
• The abstract data type is written with the help of instances and
operations.
• We make use of the reserved word AbstractDataType while
writing an ADT.
AbstractDataType Array
{
Instances: An array A of some size, index i and total number of
elements in the array n.
Operations:
1. Create () : This operation creates array.
2. Insert () : This operation is for inserting the elements in an array.
3. Delete () : This operation is for deleting the elements from the array. Only
logical deletion of the elements is possible.
4. Display () : This operation displays the elements of the array.
}
One and Two Dimensional Array
• The arrays can be one dimensional, two dimensional or
multidimensional.
10 20 30 40 50 60 …
100 102 104 106 108 110
a[2][3] = 1072
Solution: Column Major Representation
a[2][3] = 1072
Example 2 - Consider integer array int arr[4][5] declared in program, If the
base address is 1020, find the address of the element arr[3][4] with row
major and column major representation of array. SPPU: Dec-09, Marks 6
a[3][4] = 1058
Solution: Column Major Representation
a[3][4] = 1058
Examples to Solve
a[2][4] = 2108
Example 4 - Consider integer array int arr[5][6] declared in program, If the base
address is 1010, find the address of the element arr[4][3] with row major and
column major representation of array.
a[4][3] = 1048
Inserting an Element in an Array
Inserting an element in an array is complex activity because we
have to shift the elements ahead in order to create a space for
new element.
That means after inserting an element array size gets
incremented by one.
0 10
0 10
1 20
1 20
2 30
2 30
3 40
40 New element
3 44 at
4 44
50 position 4
4
5 50
Before
Insertion After
Insertion
Inserting an Element in an Array
We can implement array using Python program. Python does
not support the concept of array, but we can implement the
array using List.
List is a sequence of values.
String is also sequence of values. But in string this sequence is
of characters. On the other hand, in case of list the values can
be of any type.
The values in the list are called elements or items. These
elements are separated by commas and enclosed within the
square bracket.
For e.g. [10,20,30,40] # list of integers
[‘aaa’, ‘bbb’, ‘ccc’] # list of strings
The list that contains no element is called empty list. The empty
list is represented by []
Inserting an Element in an Array - Python Program
– Position = 4
– Element to be inserted = 44
Traversing List
The loop is used in list for traversing purpose. The for loop is
used to traverse the list elements.
Syntax: for VARIABLE in LIST :
BODY
Example:
a=[‘a’,’b’,’c’,’d’,’e’] #List a is created
i=0
for i in a:
print(i)
will result into:
a
b
c
d
e
Traversing List
We can traverse the list using range() function. Using range()
function we can access each element of the list using index of a
list.
If we want to increment each element of the list by one, then we
must pass index as argument to for loop. As follows:
Example:
a=[10,20,30,40]
for i in range(len(a)):
a[i]=a[i]+1 #incremented each number by one
print(a)
Output:
a [11, 21, 31, 41]
Deleting an element from Array
Deleting an element from array is complex activity because we
have to shift the elements to previous position.
That means after deleting an element size gets decremented by
one.
0 10 0 10
1 20 Element 1 20
at
2 30 position 2 is 2 40
deleted
3 40 3 50
4 50
Deleting an element from Array - Python Program
a1 = []
n = int(input(“Enter total number of Output:
elements in first array:”)) Enter total number of elements
for i in range(0,n): in first array:4
item = int(input(“Enter the Enter the element: 10
element: ”)) Enter the element: 30
a1.append(item) Enter the element: 50
a2 = [] Enter the element: 70
m = int(input(“Enter total number of Enter total number of elements
elements in second
in second array:4
array:”))
Enter the element: 20
for i in range(0,m):
item = int(input(“Enter the Enter the element: 40
element: ”)) Enter the element: 60
a2.append(item) Enter the element: 80
Merged Array is ...
mergeArr(a1,a2,n,m) 10 30 20 50 40 70 60 80
Multidimensional (n dimensional) Array
Output:
Input number of rows: 3
Input number of columns: 3
Enter the element:10
Enter the element:20
Enter the element:30
Enter the element:40
Enter the element:50
Enter the element:60
Enter the element:70
Enter the element:80
Enter the element:90
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
Addition of Two Matrices
def add_matrix(arr1,arr2):
result = [[arr1[i][j] + arr2[i][j] for j in range(len(arr1[0]))] for i in
range(len(arr1))]
print(“The Addition of Two Matrices...”)
print(result)
Cont…
Addition of Two Matrices
Cont…
Addition of Two Matrices
arr2 = [[0 for col in range(col_num)] for row in
range(row_num)]
for row in range(row_num):
for col in range(col_num):
item = int(input(“Enter the elements in second
matrix: ”))
arr2[row][col]= item
print(“The second matrix is...”)
print(arr2)
#Driver Code
add_matrix(arr1,arr2)
Cont…
Addition of Two Matrices - Output
Cont…
Matrix Multiplication
Cont…
Matrix Multiplication
A= [[1,2,3],
#iterate through rows of X
[4,5,6],
for i in range(len(A)):
[7,8,9]]
for j in range(len(B[0])):
B= [[1,1,1],
for k in range(len(B)):
[2,2,2],
result[i][j] +=
[3,3,4]] A[i][k] * B[k][j]
result= [[0,0,0], print(“Matrix Multiplication is ...”)
[0,0,0], for r in result:
[0,0,0]] print(r)
print(“Matrix A is ...”)
print(A)
print(“Matrix B is ...”)
print(B) Cont…
Matrix Multiplication - Output
Matrix A is...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix B is...
[[1, 1, 1], [2, 2, 2], [3, 3, 4]]
Matrix Multiplication is...
[14, 14, 17]
[32, 32, 38]
[50, 50, 59]
Cont…
Transpose of Matrix
Cont…
Transpose of Matrix
A= [[1,2,3],
[4,5,6],
[7,8,9]] Output:
result= [[0,0,0], Original Matrix is...
[0,0,0], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[0,0,0]] Transposed Matrix is...
print(“Original Matrix is...”) [1, 4, 7] [2, 5, 8] [3, 6, 9]
print(A)
#iterate through rows
for i in range(len(A)):
for j in range(len(A[0])):
result[j][i] = A[i][j]
print(“Transposed Matrix is ...”)
for r in result:
print(r)
Multidimensional Array
Three Dimensional Array
• The multidimensional array is similar to the two dimensional
array with multiple dimensions for example Here is 3-D array
Three Dimensional Array - Program
row_num = int(input(“Input number of rows: ”))
col_num = int(input(“Input number of columns: ”))
dim_num = int(input(“Input number of dimensions: ”))
arr1 =[] #creating an empty list
for dim in range(dim_num):
arr1.append([])
for row in range(row_num):
arr1[dim].append([])
for col in range(col_num):
item = int(input(“Enter Element: ”))
arr1[dim][row].append(item)
print(“\n Elements in 3D Array are...”)
for dim in range(dim_num):
for row in range(row_num):
for col in range(col_num):
print(arr1[dim][row][col],end =" “)
print()
print(“——————-”)
Three Dimensional Array - Output
Enter Element: 11
Enter Element: 12
Input number of rows: 2 Enter Element: 13
Input number of columns: 3 Enter Element: 14
Input number of dimensions: 3 Enter Element: 15
Enter Element: 1 Enter Element: 16
Enter Element: 2 Enter Element: 17
Enter Element: 3 Enter Element: 18
Enter Element: 4
Enter Element: 5 Elements in 3D Array are...
Enter Element: 6 123
Enter Element: 7 456
Enter Element: 8 ——————-
Enter Element: 9 789
Enter Element: 10 10 11 12
——————-
13 14 15
16 17 18
——————-
Concept of Ordered List
1. append :
The append method adds the element at the end of the list.
a=[10,20,30]
a.append(40) #adding element 40 at the end
Output: a [10, 20, 30, 40]
b=[‘A’,’B’,’C’]
b.append(‘D’) #adding element D at the end
Output: b [‘A’, ‘B’, ‘C’, ‘D’]
Ordered List Methods:
2. extend :
The extend method takes the list as an argument and
appends this list at the end of the old list.
a=[10,20,30]
b=[‘a’,’b’,’c’]
a.extend(b)
3. sort :
The sort method arranges the elements in increasing order.
a=[‘x’,’z’,’u’,’v’,’y’,’w’]
a.sort()
• The methods append, extend and sort does not return any value.
These methods simply modify the list.
• These are void methods.
Ordered List Methods:
4. insert :
This method allows us to insert the data at desired position
in the list.
Syntax: insert (index, element)
a=[10,20,40]
a.insert(2,30)
print(a)
5. delete :
The deletion of any element from the list is carried out using
various functions like pop, remove, del.
If we know the index of the element to be deleted then just
pass that index as an argument to pop function.
a=[‘u’,’v’,’w’,’x’,’y’,’z’]
val=a.pop(1) #the element at index 1 is v, it is deleted
a [‘u’, ‘w’, ‘x’, ‘y’, ‘z’] #list after deletion
val #deleted element is present in variable val
‘v’
Cont…
Ordered List Methods:
a =[‘u’,’v’,’w’,’x’,’y’,’z’]
val=a.pop()
a [‘u’, ‘v’, ‘w’, ‘x’, ‘y’]
val
‘z’
Cont…
Ordered List Methods:
Cont…
Ordered List Methods:
a=[‘a’,’b’,’c’,’d’,’e’]
del a[2:4]
print(a)
Cont…
Ordered List – Built in Functions
There are various built in functions in python for supporting the list
operations. Following table shows these functions:
Built-in function Purpose
If all the elements of the list are true or if the list is
all ()
empty then this function returns true.
If the list contains any element true or if the list is
any ()
empty then this function returns true.
len () This function returns the length of the string.
This function returns maximum element present in
max ()
the list.
This function returns minimum element present in
min ()
the list.
This function returns the sum of all the elements in
sum ()
the list.
sorted () This function returns a list which is sorted one.
Ordered List – Built in Functions
Example:
myList = [10,20,30,40,50]
print("The length of list is: ",len(myList))
print("The maximum of list is: ",max(myList))
print("The minimum of list is: ",min(myList))
print("The sum of all elements of the list is : ",sum(myList))
Output:
The length of list is: 5
The maximum of list is: 50
The minimum of list is: 10
The sum of all elements of the list is : 150
Ordered List – List Comprehension
This is mainly useful to make new list where each element is obtained
by applying some operations to each member of another
sequence.
Syntax :
new_list = [expression for_loop_one_or_more conditions]
List Comprehension- Example
Write a python program find the squares of a number using the for loop.
numbers = [1, 2, 3, 4]
squares = []
for n in numbers:
squares.append(n**2)
print(squares)
Output: [1, 4, 9, 16]
Write a python program to find common numbers from two lists using for loop
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = []
for a in list_a:
for b in list_b:
if a == b:
common_num.append(a)
print(common_num)
Output [2, 3, 4]
using list comprehensions:
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num)
Output: [2, 3, 4]
List Comprehension- Example
Write a python program to create a list of even numbers from 0 to 10
Representation:
For representing a single variable
polynomial one can make use of one
dimensional array.
In single dimensional array the index of
an array will act as the exponent and the
coefficient can be stored at that
particular index which can be
represented as follows:
For e.g.: 3x4 + 5x3 + 7x2 + 10x – 19
This polynomial can be stored in single
dimensional array.
Polynomial Addition
Algorithm :
Assume that the two polynomials say A and B and the resultant
polynomial storing the addition result is stored in one large array.
1. Set a pointer i to point to the first term in a polynomial A.
2. Set a pointer j to point to first term in a polynomial B.
3. Set a pointer k to point to the first position in array C.
4. Read the number of terms of A polynomial in variable t1 and read the number of
terms of B polynomial in variable t2.
5. While i < t1 and j < t2 then
{
if exponent at ith position of A poly is equal to the exponent at jth position of
polynomial B then
Add the coefficients at that position from both the polynomial and store the
result in C arrays coefficient field at position k copy the exponent either pointed by i
or j at position k in C array.
Increment i, j and k to point to the next position in the array A, B and C.
}
Polynomial Addition
else
{
if the exponent position i is greater than the exponent at position j in polynomial
B then
{
copy the coefficient at position i from A polynomial into coefficient field at
position k of array C copy the exponent pointed by i into the exponent field at
position k in array C.
Increment i, k pointers.
}
else
{
Copy the coefficient at position j of B polynomial into coefficient field at position
k in C array.
Copy the exponent pointed by j into exponent field at position k in C array.
Increment j and k pointers to point to the next position in array B and C.
}
}
Polynomial Addition
6. While i < t1
{
Copy the coefficient at position i of into the coefficient field at position k in C.
Copy the exponent pointed by i into the exponent field at position k in C array.
Increment i and k to point to the next position in arrays A and C.
}
7. While j < t2
{
Copy the coefficient at position j of B into the coefficient field at position k in.
Copy the exponent pointed by j into exponent field at position k in C.
Increment j, k to point to the next position in B and C arrays.
8. Display the complete array C as the addition of two given polynomials.
9. Stop.
Polynomial Addition- Logic
Let us take polynomial A and B as follows:
3x3 + 2x2 +x+1
5x3 + 7x
Polynomial Addition- Logic
As the terms pointed by i and j shows that both the terms have equal exponent, we
can perform addition of these terms and we will store the result in polynomial C.
Polynomial Addition- Logic
Now increment i, j, and k pointers.
Polynomial Addition- Logic
Now pointer i points to 2x2 and pointer j points to 7x. As 2x2 > 7x. We will copy 2x2
in the polynomial C. And we will simply increment i and k pointers
Polynomial Addition- Logic
Now terms in polynomial B are over. Hence we will copy the remaining terms from
polynomial A to polynomial C.
Polynomial Addition- Logic
#Driver Code
if __name__ == ‘__main__’:
C = mul(A, B, m, n)
print(“\n Multiplication of polynomial is...”)
display(C, m+n-1)
Polynomial Evaluation
Now, we will discuss the algorithm for evaluating the polynomial
Consider the polynomial for evaluation-
-10x7 + 4x5 + 3x2
Where, x = 1,
= -10 + 4 + 3 = - 6 + 3
= 3 is the result of polynomial evaluation.
Algorithm:
Step 1: Read the polynomial array A
Step 2: Read the value of x.
Step 3: Initialize the variable sum to zero.
Step 4: Then calculate coeff * pow (x, exp) of each term and add the
result to sum.
Step 5: Display “sum”
Step 6: Stop
Polynomial Evaluation – Python Program
def evalPoly(A,n,x):
result = A[0]
for i in range(1,n):
result = result + A[i]*x**i
return result
def display(poly, n):
for i in range(n):
print(poly[i], end = “”)
if (i != 0):
print(“x^”, i, end = “”)
if (i != n - 1):
print(“ + ”, end = “”)
#Driver Code Output:
if __name__ == ‘__main__’:
Polynomial is:
#The following array represents
#polynomial 1 + 1x +2x^2+ 3x^3 1 + 1x^ 1 + 2x^ 2 + 3x^ 3
A = [1, 1, 2, 3] Enter the value of x: 2
n = len(A) The result of evaluation of
print(“\n Polynomial is: ”); polynomial is: 35
display(A,n)
x = int(input(“\n Enter the value of x: ”))
print(“\n The result of evaluation of polynomial is: ”,evalPoly(A,n,x))
Sparse Matrix
In a matrix, if there are m rows and n columns then the space required
to store the numbers will be m*n*s where s is the number of bytes
required to store the value.
Suppose, there are 10 rows and 10 columns and we have to store the
integer values then the space complexity will be bytes.
It is observed that, many times we deal with matrix of size m*n and
values of m and n are reasonably higher and only a few elements are
non zero. Such matrices are called sparse matrices.
temp.append(i)
temp.append(j)
temp.append(matrix[i][j])
#appending the sublist into
#the sparse matrix list
SP.append(temp)
#displaying the sparse matrix
print(“\nSparse Matrix: ”) Output:
print(“Row Col Non_Zero_Value”) 10 0 0 0
display(SP) 0 20 0 0
#Driver code 0 0 30 0
#Original Matrix 0 0 0 40
A =[ [10, 0, 0, 0], 0 50 0 0
[0, 20, 0, 0],
[0, 0, 30, 0], Sparse Matrix:
[0, 0, 0, 40], Row Col Non_Zero_Value
[0, 50, 0, 0] ] 0 0 10
#displaying the matrix 1 1 20
display(A) 2 2 30
#converting the matrix to sparse 3 3 40
convert(A) 4 1 50
Sparse Matrix Addition
Algorithm:
1. Start
2. Read the two sparse matrices say SP1 and SP2 respectively.
3. The index for SP1 and SP2 will be i and j respectively. Non zero elements are
n1 and n2 for SP1 and SP2.
4. The k index will be for sparse matrix SP3 which will store the addition of two
matrices.
5. If SP1 [0][0] > SP2 [0][0] i.e. total number of rows then
SP3 [0][0] = SP1 [0][0]
else SP3 [0][0] = SP2 [0][0]
Similarly check in SP1 and SP2 the value of total number of columns which ever
value is greater transfer it to SP3.
Set i = 1, j = 1, k = 1.
6. When i < n1 and j < n2.
Sparse Matrix Addition
7. a) If row values of SP1 and SP2 are same then check also column values are
same, if so add the non-zero values of SP1 and SP2 and store them in SP3,
increment i, j, k by 1.
b) Otherwise if colno of SP1 is less than colno of SP2 copy the row, col and
nonzero value of SP1 to SP3. Increment i and k by 1.
c) Otherwise copy the row, col and non-zero value of SP2 to SP3. Increment j
and k by 1.
8. When rowno of SP1 is less than SP2 copy row, col and non-zero element of
SP1 to SP3. Increment i and k by 1.
9. When rowno of SP2 is less than SP1 copy row, col and non-zero element of
SP2 to SP3. Increment j, k by 1. Repeat step 6 to 9 till condition is true.
10. Finally whatever k value that will be total number of non-zero values in
SP3 matrix.
∴ SP3 [0][2] = k
11. Print SP3 as a result.
12. Stop.
Sparse Matrix Addition – Python Program
def create(s,row_num,col_num,non_zero_values):
s[0][0]= row_num
s[0][1] = col_num
s[0][2] = non_zero_values
for k in range(1,non_zero_values+1):
row = int(input(“Enter row value: ”))
col = int(input(“Enter col value: ”))
element = int(input(“Enter the element: ”))
s[k][0]= row
s[k][1] = col
s[k][2] = element
def display(s):
print(“Row\tcol\t Non_Zero_values”)
for i in range(0,(s[0][2]+1)):
for j in range(0,3):
print(s[i][j], “\t”, end=’’)
print()
Sparse Matrix Addition – Python Program
def add(s1,s2):
i=1
j=1
k=1
s3 = []
if ((s1[0][0] == s2[0][0]) and (s1[0][1] == s2[0][1])):
#traversing thru all the terms
while ((i <= s1[0][2]) and (j <= s2[0][2])):
if (s1[i][0] == s2[j][0]):
temp =[]
if (s1[i][1] == s2[j][1]):
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2]+s2[j][2])
s3.append(temp)
i += 1
j += 1
k += 1
elif (s1[i][1]<s2[j][1]):
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2])
s3.append(temp)
i += 1
k += 1
Sparse Matrix Addition – Python Program
else:
temp.append(s2[j][0])
temp.append(s2[j][1])
temp.append(s2[j][2])
s3.append(temp)
j += 1
k += 1
elif (s1[i][0]<s2[j][0]):
temp =[]
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2])
s3.append(temp)
i +=1
k +=1
else:
temp =[]
temp.append(s1[j][0])
temp.append(s1[j][1])
temp.append(s1[j][2])
s3.append(temp)
j +=1
k +=1
Sparse Matrix Addition – Python Program
#copying remaining terms
while (i <= s1[0][2]): #s1 is greater than s2
temp = []
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2])
s3.append(temp)
i += 1
k += 1
while (j <= s2[0][2]): #s2 is greater than s1
temp = []
temp.append(s2[j][0])
temp.append(s2[j][1])
temp.append(s2[j][2])
s3.append(temp)
j += 1
k += 1
#assigning total rows, total columns
#and total non zero values as a first row
#in resultant matrix
s3.insert(0,[s1[0][0],s1[0][1],k-1])
else:
print(“\n Addition is not possible”)
Sparse Matrix Addition – Python Program
print(“Addition of Sparse Matrix ...”)
print(“\nRow Col Non_Zero_values”)
for row in s3:
for element in row:
print(element, end =" “)
print()
#Driver Code
row_num1 = int(input(“Input total number of rows for first matrix: ”))
col_num1 = int(input(“Input total number of columns for first matrix: ”))
non_zero_values1 = int(input(“Input total number of non-zero values: ”))
cols =3
s1 = [[0 for col in range(cols)] for row in range(non_zero_values1+1)]
#creating first sparse matrix
create(s1,row_num1,col_num1,non_zero_values1)
print(“First sparse matrix is”)
display(s1)
row_num2 = int(input(“Input total number of rows for second matrix: ”))
col_num2 = int(input(“Input total number of columns for second matrix: ”))
non_zero_values2 = int(input(“Input total number of non-zero values: ”))
s2 = [[0 for col in range(cols)] for row in range(non_zero_values2+1)]
#creating second sparse matrix
create(s2,row_num2,col_num2,non_zero_values2)
print(“Second sparse matrix is”)
display(s2)
#Performing and displaying addition of two sparse matrices
add(s1,s2)
Sparse Matrix Addition – Python Program Output
E.g.
Before Transpose After Transpose
Row Col Row Col
Index Value Index Value
No. No. No. No.
0 6 7 8 0 7 6 8
1 0 6 -10 1 0 1 55
2 1 0 55 2 0 5 99
3 2 5 -23 3 1 3 67
4 3 1 67 4 3 4 14
5 3 6 88 5 4 4 -28
6 4 3 14 6 5 2 -23
7 4 4 -28 7 6 0 -10
8 5 0 99 8 6 3 88
During the transpose of matrix (i) Interchange rows and columns (ii) Also maintain
the rows in sorted order.
Transpose of Sparse Matrix – Python Program
row_num = int(input(“Input number of rows: ”))
col_num = int(input(“Input number of columns: ”))
non_zero_values = int(input(“Input total number of non-zero values: ”))
cols =3
s1 = [[0 for col in range(cols)] for row in range(non_zero_values+1)]
s2 = [[0 for col in range(cols)] for row in range(non_zero_values+1)]
def create(s1,row_num,col_num,cols,non_zero_values):
s1[0][0]= row_num
s1[0][1] = col_num
s1[0][2] = non_zero_values
for k in range(1,non_zero_values+1):
row = int(input(“Enter row value: ”))
col = int(input(“Enter col value: ”))
element = int(input(“Enter the element: ”))
s1[k][0]= row
s1[k][1] = col
s1[k][2] = element
def display(s,cols,non_zero_values):
print(“Row\tcol\t Non_Zero_values”)
for i in range(0,non_zero_values+1):
for j in range(0,cols):
print(s[i][j], “\t”, end=’’)
print()
Transpose of Sparse Matrix – Python Program
def transpose(s1,row_num,col_num,s2,cols,non_zero_values):
s2[0][0]= col_num
s2[0][1] = row_num
s2[0][2] = non_zero_values
nxt=1
for c in range(0,col_num):
#for each column scan all the terms for a ‘term’ in that column
for Term in range(1,non_zero_values+1):
if (s1[Term][1] == c):
#Interchange Row and Column
s2[nxt][0] = s1[Term][1]
s2[nxt][1] = s1[Term][0]
s2[nxt][2] = s1[Term][2]
nxt=nxt+1
#Driver Code
create(s1,row_num,col_num,cols,non_zero_values)
print(“Original sparse matrix is”)
display(s1,cols,non_zero_values)
transpose(s1,row_num,col_num,s2,cols,non_zero_values)
print(“Transposed sparse matrix is”)
display(s2,cols,non_zero_values)
Transpose of Sparse Matrix – Python Program Output
In above program we look for column values of s1 array starting from 0 to total
number of column value and interchange row and column one by one. For
instance – Consider the output of above program
s1[0][0] =10, the column value is 0 here, we swap the row and column and
copy the column, row and non zero value to s2 array
Locate zero in Col, swap row, col and copy it to s2. At the same time copy
corresponding non-zero-value to s2
S1 S2
Non_Zero Non_Zero
Row Col Row Col
_Values _Values
0 0 10 0 0 10
0 2 20
1 1 30
2 1 40
Transpose of Sparse Matrix- Logic
Locate 1 in Col, swap row, col and copy it to s2. At the same time copy
corresponding non-zero-value to s2
Non_Zero Non_Zero
Row Col Row Col
_Values _Values
0 0 10 0 0 10
0 2 20 1 1 30
1 1 30
2 1 40
Non_Zero Non_Zero
Row Col Row Col
_Values _Values
0 0 10 0 0 10
0 2 20 1 1 30
1 1 30 1 2 40
2 1 40
Transpose of Sparse Matrix- Logic
Locate 2 in Col, swap row, col and copy it to s2. At the same time copy corres
ponding non-zero-value to s2
Non_Zero Non_Zero
Row Col Row Col
_Values _Values
0 0 10 0 0 10
0 2 20 1 1 30
1 1 30 1 2 40
2 1 40 2 0 20
cols =3
Non-Zero
Index Row Col
Values
0 3 3 4
1 0 1 10
2 1 0 20
3 2 0 30
4 2 1 40
• We will first consider one dimensional array, named rterm[]. In this array we
will store non zero terms present in each column.
rterm
• At 0th column there are two non zero terms. At 1st column 0 2
also there are two non zero terms but there is no non
zero term in 2nd column. 1 2
2 0
Fast Transpose of Sparse Matrix - Logic
Similarly we will take another one dimensional array named rpos[]. We initialize
0th location of rpos[] by 1. so,
rpos
Now we use following formula to fill up the rpos array.
0 1
rpos[i] = rpos[i-1] + rterm[i-1]
rpos
0 1
1 3
2 5
3 5
Fast Transpose of Sparse Matrix - Logic
rpos [0] = 1
Fast Transpose of Sparse Matrix - Logic
rpos
rpos [0] = 2
S2
Non_Zero
Row Col
_Values
That means place triplet (0, 2, 30) at 0
index 2 in S2 array. 1 0 1 20
2 0 2 30
3 1 0 10
4
Fast Transpose of Sparse Matrix - Logic
rpos
Since rpos[0] is read just now increment rpos[0] by 1.
0 23
rpos [1] = 4
S2
Non_Zero
Row Col
_Values
That means place triple (1, 2, 40) at 0
index 2 in S2 array. 1 0 1 20
2 0 2 30
3 1 0 10
4 1 2 40
Fast Transpose of Sparse Matrix - Logic
a=[10,20,30,40,50]
b=[]
print("The elements in descending order(By method 1) are....")
for i in range(4,-1,-1):
b.append(a[i])
for j in range(5):
print(b[j])