Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

FDS Unit - 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 119

Unit-II

Linear Data Structure Using


Sequential Organization
Sequential Organization
 Array is referred as the sequential organization
that means the data in arrays is stored in some
sequence
 For E.g. If we want to store names of all the
students in a class we can make use of an array
to store the names in sequential form.
 Definition of Arrays: Array is a set of
consecutive memory locations which contains
similar data elements.
 Array is basically a set of pair-index and value
 Syntax:
data_type name_of_array [size]

Cont...
Sequential Organization

 For e.g. int a [10]; double b [10] [10];


 Here, ‘a’ is the name of the array inside the
square bracket size of the array is given. This
array is of integer type i.e. all the elements are of
integer type in array ‘a’.
Sequential Organization
 Advantages:
1. Elements can be retrieved or stored very efficiently in
sequential organization with the help of index or memory
location.
2. All the elements are stored at continuous memory locations.
Hence searching of element from sequential organization is
easy.

 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.

 One dimensional array:


The one dimensional array ‘a’ is declared as int a [10];
One and Two Dimensional Array
 Two dimensional array:
If we declare a two dimensional array as
int a[10] [3];
Then it will look like this -

• The two dimensional array should be in row-column form.


Memory(Storage) Representation and Address Calculation
SPPU : Dec- 06,09,16,18 Marks 6

• The arrays can be represented using


i) Row Major ii) Column Major Representation
 Row Major Representation:
If the elements are stored in rowwise manner then it is
called row major representation.
For E.g. If we want to store elements
10 20 30 40 50 60 then
in a two dimensional array
 To access any element in two
dimensional array we must
specify both its row number
and column number. That is
why we need two variables
which act as row index and
column index
Memory(Storage) Representation and Address Calculation
SPPU : Dec- 06,09,16,18 Marks 6

 Column Major Representation:


If the elements are stored in column wise manner then it is
called column major representation.
For E.g. If we want to store elements
10 20 30 40 50 60 then the elements will be
filled up by columnwise manner as follows (consider array a[3] [2]).
Here 3 represents number of rows and 2 represents number of
columns.

 Each element is occupied at


successive locations if the element
is of integer type then 2 bytes of
memory will be allocated, if it is of
floating type then 4 bytes of
memory allocated and so on.
For Example-
int a [3] [2] =
{ {10,20}
{30, 40}
{50,60} }
Then in row major matrix
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1]

100 102 104 106 108 110

Then in column major matrix


a[0][0] a[1][0] a[2][0] a[0][1] a[1][1] a[2][1]

10 20 30 40 50 60 …
100 102 104 106 108 110

Here each element occupies 2 bytes of memory base address will


be 100.
Cont….
For Example-

Address Calculation for any element will be as follows:

In row major matrix, the element a[i] [j] will be at


base address + (col_index * total number of rows + row_index) * element_size.

In column major matrix, the element at a[i] [j] will be at


base address + (row_index * total number of columns + column_index) *
element_size

In any programming language normally the row major representation is used.


Example 1- Consider integer array int arr[3][4] declared in program, If the
base address is 1050, find the address of the element arr[2][3] with row
major and column major representation of array. SPPU: Dec-06, Marks 6

Solution: Row Major Representation

The element a[i][j] will be at


a[i][j] = base address + (col_index * total number of rows +
row_index) * element_size
= (base address + (j * row_size + i) * element size)

When i = 2 and j = 3, element_size = int occupies 2 bytes of memory


hence it is 2, total number of rows = 3

a[2][3] = 1050 + (3*3+2) *2


= 1050 + 22 = 1072

a[2][3] = 1072
Solution: Column Major Representation

The element a[i][j] will be at


a[i][j] = base address + (row_index * total number of columns +
column_index) * element_size
= (base address + (i * col_size + j) * element size)

When i = 2 and j = 3, element_size = int occupies 2 bytes of memory


hence it is 2, total number of columns = 4

a[2][3] = 1050 + (2*4+3) *2


= 1050 + 22 = 1072

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

Solution: Row Major Representation

The element a[i][j] will be at


a[i][j] = base address + (col_index * total number of rows +
row_index) * element_size
= (base address + (j * row_size + i) * element size)

When i = 3 and j = 4, element_size = int occupies 2 bytes of memory


hence it is 2, total number of rows = 4

a[3][4] = 1020 + (4*4+3) *2


= 1020 + 38 = 1058

a[3][4] = 1058
Solution: Column Major Representation

The element a[i][j] will be at


a[i][j] = base address + (row_index * total number of columns +
column_index) * element_size
= (base address + (i * col_size + j) * element size)

When i = 3 and j = 4, element_size = int occupies 2 bytes of memory


hence it is 2, total number of columns = 5

a[3][4] = 1020 + (3*5+4) *2


= 1020 + 38 = 1058

a[3][4] = 1058
Examples to Solve

Example 3 - Consider float array float arr[3][5] declared in


program, If the base address is 2052, find the address of the
element arr[2][4] with row major and column major
representation of array.

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.
Example 3 - Consider float array float arr[3][5] declared in program, If the base
address is 2052, find the address of the element arr[2][4] with row major and
column major representation of array.

Solution: Row Major Representation

The element a[i][j] will be at


a[i][j] = base address + (col_index * total number of rows +
row_index) * element_size
= (base address + (j * row_size + i) * element size)

When i = 2 and j = 4, element_size = float occupies 4 bytes of memory


hence it is 4, total number of rows = 3

a[2][4] = 2052 + (4*3+2) *4


= 2052 + 56 = 2108

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.

Solution: Row Major Representation

The element a[i][j] will be at


a[i][j] = base address + (col_index * total number of rows +
row_index) * element_size
= (base address + (j * row_size + i) * element size)

When i = 4 and j = 3, element_size = int occupies 2 bytes of memory


hence it is 2, total number of rows = 5

a[4][3] = 1010 + (3*5+4) *2


= 1010 + 38 = 1048

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

print(“\nHow many elements are there in Array?”)


n = int(input())
array = []
i=0
for i in range(n):
print(“\n Enter element in Array”)
item = int(input())
array.append(item)
print(“Enter the location where you want to insert an element”)
position = int(input())
print(“Enter the value to insert”)
value = int(input())
array=array[:position]+[value]+array[position:]
print(“Resultant array is\n”)
print(array)
Inserting an Element in an Array - Python Program Output

How many elements are there in Array?


5
Enter element in Array
10
Enter element in Array
20
Enter element in Array
30
Enter element in Array
40
Enter element in Array
50
Enter the location where you want to insert an element
4
Enter the value to insert
44
Resultant array is
[10, 20, 30, 40, 44, 50]
Inserting an Element in an Array - Python Program Logic

 For insertion of any element in the array, we can make use of


list slicing technique. Here is an illustration.
 Suppose the array is as follows:

– 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

print(“\nHow many elements are there in Array?”)


n = int(input())
array = []
i=0
for i in range(n):
print(“\n Enter element in Array”)
item = int(input())
array.append(item)
print(“Enter the index from where you want to delete an element”)
position = int(input())
array=array[:position]+array[position+1:]
print(“Resultant array is\n”)
print(array)
Deleting an element from Array - Python Program Output

How many elements are there in Array?


5
Enter element in Array
10
Enter element in Array
20
Enter element in Array
30
Enter element in Array
40
Enter element in Array
50
Enter the index from where you want to delete an element
2
Resultant array is
[10, 20, 40, 50]
Deleting an element from Array - Python Program Logic

 Suppose the array is as follows:

 Position = 2. That means we want to delete an element 30, then


Merging of Two Arrays
 Merging of two arrays result into a single array in which
elements are arranged in sorted order.
For E.g. – Consider two arrays as follows:
Merging of Two Arrays
Merging of Two Arrays- Python Program
def mergeArr(a1,a2,n,m):
a3 = [None]*(n+m) #if elements of first array are remaining
i=0 #then transfer them to third array
j=0 while i < n:
k=0 a3[k] = a1[i]
#traverse both arrays k=k+1
#if element of first array is less then i=i+1
store it in third array #if elements of second array are
#if element of second array is less then remaining #then transfer them to third
store it in third array array
while i < n and j < m: while j < m:
if a1[i] < a2[j]: a3[k] = a2[j]
a3[k] = a1[i] k=k+1
k=k+1 j=j+1
i=i+1 #display the resultant merged array
else: print(“Merged Array is ...”)
a3[k] = a2[j] for i in range (n+m):
k=k+1 print(str(a3[i]), end = “ ”)
j=j+1
Cont…
Merging of Two Arrays- 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

 Multidimensional array is an array having more than one


dimension.
 Popularly, two and three dimensional arrays are used.

 Two Dimensional Array


• The two dimensional array is used to represent the matrix.
• Various operations that can be performed on matrix are –
(1) Matrix Addition
(2) Matrix Multiplication and
(3) Transpose of Matrix

Let us discuss the implementation of various matrix operations


Two Dimensional Array- Example

Write a python program for representation two dimensional matrix.

#This program stores and displays the elements of two dimensional


Array
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
arr = [[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 element:"))
arr[row][col]= item
print(arr)
Two Dimensional Array- Example-Output

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

Write a python program for performing 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

row_num = int(input(“Input number of rows: ”))


col_num = int(input(“Input number of columns: ”))
arr1 = [[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 first
matrix: ”))
arr1[row][col]= item
print(“The first matrix is...”)
print(arr1)

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

Input number of rows: 3 Enter the elements in second matrix: 1


Input number of columns: 3 Enter the elements in second matrix: 1
Enter the elements in first matrix: 1 Enter the elements in second matrix: 1
Enter the elements in first matrix: 2 Enter the elements in second matrix: 2
Enter the elements in first matrix: 3 Enter the elements in second matrix: 2
Enter the elements in first matrix: 4 Enter the elements in second matrix: 2
Enter the elements in first matrix: 5 Enter the elements in second matrix: 3
Enter the elements in first matrix: 6 Enter the elements in second matrix: 3
Enter the elements in first matrix: 7 Enter the elements in second matrix: 3
Enter the elements in first matrix: 8 The second matrix is...
Enter the elements in first matrix: 9 [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
The first matrix is... The Addition of Two Matrices...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[2, 3, 4], [6, 7, 8], [10, 11, 12]]

Cont…
Matrix Multiplication

Write a python program to implement matrix multiplication operation.

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

Write a Python program for performing 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

• Ordered List is nothing but a set of elements.


• Such a list sometimes called as Linear List.
For E.g.
1. List of one digit numbers – (0,1,2,3,4,5,6,7,8,9)
2. Days in a week – (Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday)

Definition: An ordered list is a set of elements where set may be


empty or it can be written as a collection of elements such as
(a1,a2,a3…………an)
Concept of Ordered List

Operations on Ordered List:


1. Display of list
2. Searching a particular element from the list
3. Insertion of any element in the list
4. Deletion of any element from the list

• Ordered list can be implemented using the List data structure in


Python.
Ordered List Methods:

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)

Output: a [10, 20, 30, ‘a’, ‘b’, ‘c’]


Ordered List Methods:

3. sort :
The sort method arranges the elements in increasing order.

a=[‘x’,’z’,’u’,’v’,’y’,’w’]
a.sort()

Output: a [‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]

• 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)

Output: [10, 20, 30, 40]


Ordered List Methods:

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:

If we do not provide any argument to the pop function then


the last element of the list will be deleted.

a =[‘u’,’v’,’w’,’x’,’y’,’z’]
val=a.pop()
a [‘u’, ‘v’, ‘w’, ‘x’, ‘y’]
val
‘z’

Cont…
Ordered List Methods:

 If we know the value of the element to be deleted then the


remove function is used.
 That means the parameter passed to the remove function is the
actual value that is to be removed from the list.
 Unlike, pop function the remove function does not return any
value.
a=[‘a’,’b’,’c’,’d’,’e’]
a.remove(‘c’)
print(a)

Output: [‘a’, ‘b’, ‘d’, ‘e’]

Cont…
Ordered List Methods:

 In python, it is possible to remove more than one element at a


time using del function.

a=[‘a’,’b’,’c’,’d’,’e’]
del a[2:4]
print(a)

Output: [‘a’, ‘b’, ‘e’]

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

 List comprehension is an elegant way to create and define new lists


using existing lists.

 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]

Finding squares using list comprehensions:


numbers = [1, 2, 3, 4]
squares = [n**2 for n in numbers]
print(squares)
Output: [1, 4, 9, 16]
List Comprehension- Example

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

even = [] #creating empty list


for i in range(0,11):
if i% 2 ==0:
even.append(i)
print(“Even Numbers List: ”,even)
Output: Even Numbers List: [0,2,4,6,8,10]

using list comprehensions:


even = [ i for i in range (0,11) if i%2 == 0 ]
print(“Even Numbers List: ”,even)
Output: Even Numbers List: [0,2,4,6,8,10]
Single Variable Polynomial SPPU: May-17, Marks 3

 Definition : Polynomial is the sum of terms where each term


consists of variable, coefficient and exponent.
 Various operations on polynomial are – addition, subtraction,
multiplication and evaluation.

 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

Thus, the addition of polynomials A and B is in polynomial C.


Polynomial Addition- Python Program
#A[] represents coefficients of first polynomial
#B[] represents coefficients of second polynomial
#m and n are sizes of A[] and B[] respectively
def add(A, B, m, n):
size = max(m, n);
C = [0 for i in range(size)]
for i in range(0, m, 1):
#Each term from first polynomial to C array
C[i] = A[i]
#Add each term of second poly and add it to C
for i in range(n):
C[i] += B[i]
return C
# A function to print a polynomial
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 = “”)
Polynomial Addition- Python Program

#Driver Code
if __name__ == ‘__main__’:

#The following array represents


#polynomial 1 + 1x +2x^2+ 3x^3
A = [1, 1, 2, 3]
#The following array represents polynomial 7x + 5x^3
B = [0, 7,0, 5]
m = len(A)
n = len(B)
print(“\nFirst polynomial is”)
display(A, m) Output:
print(“\nSecond polynomial is”) First polynomial is
display(B, n) 1 + 1x^ 1 + 2x^ 2 + 3x^ 3
C = add(A, B, m, n) Second polynomial is
size = max(m, n) 0 + 7x^ 1 + 0x^ 2 + 5x^ 3
print(“\n Addition of polynomial is”) Addition of polynomial is
display(C, size) 1 + 8x^ 1 + 2x^ 2 + 8x^ 3
Polynomial Multiplication
 Now, we will discuss another operation on polynomials and that is
multiplication
For E.g. :
If two polynomials are given as
3x3 + 2x2 + x + 1
* 5x3 + 7x
Then we will perform multiplication by multiplying each term of
polynomial A by each term of polynomial B.
3x3 + 2x2 + x + 1
* 5x3 + 7x
(15x6 + 10x5 + 5x4 + 5x3) + (21x4 + 14x3 + 7x2 + 7x)
Multiplied poly A by 5x3 Multiplied poly A by 7x

Now, rearranging the terms,


15x6 + 10x5 + 26x4 + 19x3 + 7x2 +7x
Polynomial Multiplication – Python Program
#A[] represents coefficients of first polynomial
#B[] represents coefficients of second polynomial
#m and n are sizes of A[] and B[] respectively
def mul(A, B, m, n):
#allocating total size for resultant array
C = [0]* (m+n-1)
for i in range(0, m, 1):
#multiplying by current term of first polynomial
#to each term of second polynomial
for j in range(n):
C[i+j] += A[i]*B[j]
return C
#A function to print a polynomial
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 = “”)
Polynomial Multiplication – Python Program
#Driver Code
if __name__ == ‘__main__’:

#The following array represents


#polynomial 1 + 1x +2x^2+ 3x^3
A = [1, 1, 2, 3]
#The following array represents
#polynomial 7x + 5x^3 Output:
B = [0, 7,0, 5] First polynomial is
m = len(A) 1 + 1x^ 1 + 2x^ 2 + 3x^ 3
n = len(B) Second polynomial is
print(“\nFirst polynomial is”) 0 + 7x^ 1 + 0x^ 2 + 5x^ 3
display(A, m) Multiplication of polynomial is...
print(“\nSecond polynomial is”) 0 + 7x^ 1 + 7x^ 2 + 19x^ 3 + 26x^ 4 +
display(B, n) 10x^ 5 + 15x^ 6

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.

10*10*2 = 200 bytes

(Here 2 bytes are required to store an integer value.)

 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.

 Definition: Sparse matrix is a matrix containing few non zero elements


Sparse Matrix
 For Example: For example - if the matrix is of size 100*100 and only 10
elements are non zero. Then for accessing these 10 elements one has
to make 10000 times scan. Also only 10 spaces will be with non-zero
elements remaining spaces of matrix will be filled with zeros only. i.e.
we have to allocate the memory of 100*100*2 = 20000.

 Hence sparse matrix representation is a kind of representation in


which only non zero elements along with their rows and columns is
stored.
Sparse Matrix Representation using Array
 The representation of sparse matrix will be a triplet only. That means it stores
rows, columns and values.
 The 0th row will store total rows of the matrix, total columns of the matrix, and
total non-zero values.
 For example – consider a matrix of size 5 X 6 containing 6 number of non-zero
values. This matrix can be represented as shown below
Sparse Matrix Representation using Array – Python Program

#function display a matrix


def display(matrix):
for row in matrix:
for element in row:
print(element, end =" “)
print()
#function to convert the matrix
#into a sparse matrix
def convert(matrix):
SP =[]
#searching values greater
#than zero
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
#creating a temporary sublist
temp = []
#appending row value, column
#value and element into the sublist
Sparse Matrix Representation using Array – Python Program

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

Input total number of rows for first matrix: 2


Input total number of non-zero values: 2
Input total number of columns for first matrix: 2
Enter row value: 2
Input total number of non-zero values: 3
Enter col value: 1
Enter row value: 1
Enter the element: 5
Enter col value: 1
Enter row value: 2
Enter the element: 10
Enter col value: 2
Enter row value: 1
Enter the element: 40
Enter col value: 2
Second sparse matrix is
Enter the element: 20
Row col Non_Zero_values
Enter row value: 2
2 2 2
Enter col value: 1
2 1 5
Enter the element: 30
2 2 40
First sparse matrix is
Addition of Sparse Matrix...
Row col Non_Zero_values
Row Col Non_Zero_values
2 2 3
2 2 4
1 1 10
1 1 10
1 2 20
1 2 20
2 1 30
2 1 35
Input total number of rows for second matrix: 2
2 2 40
Input total number of columns for second matrix: 2
Transpose of Sparse Matrix

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

Input number of rows: 3


Input number of columns: 3 Original sparse matrix is
Input total number of non-zero values: 4 Row col Non_Zero_values
Enter row value: 0 3 3 4
Enter col value: 0 0 0 10
Enter the element: 10 0 2 20
Enter row value: 0 1 1 30
Enter col value: 2 2 1 40
Enter the element: 20 Transposed sparse matrix is
Enter row value: 1 Row col Non_Zero_values
Enter col value: 1 3 3 4
Enter the element: 30 0 0 10
Enter row value: 2 1 1 30
Enter col value: 1 1 2 40
Enter the element: 40 2 0 20
Transpose of Sparse Matrix- Logic

 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

 Thus we get transposed matrix in the form of sparse matrix representation.


Fast Transpose of Sparse Matrix

 The fast transpose is a transpose method in which matrix transpose operation


is performed efficiently.
 In this method an auxiliary array are used to locate the position of the elements
to be transposed sequentially.
 Here is an implementation of fast transpose of sparse matrix in Python.

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)]


Fast Transpose of Sparse Matrix
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()
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
rterm = []
rpos = []
Fast Transpose of Sparse Matrix
if non_zero_values > 0:
for i in range(col_num):
rterm.insert(i,0)
for i in range(1,non_zero_values+1):
#rterm[s1[i][1]]++
index = s1[i][1]
val = rterm.pop(index)
rterm.insert(index,val+1)
rpos.insert(0,1)
for i in range(1,col_num+1):
#rpos[i]=rpos[i-1]+ rterm[(i - 1)]
rpos_val=rpos[i-1]
rterm_val=rterm[i-1]
rpos.insert(i,(rpos_val+rterm_val))
for i in range(1,non_zero_values+1):
j = rpos[s1[i][1]]
s2[j][0] = s1[i][1]
s2[j][1] = s1[i][0]
s2[j][2] = s1[i][2]
rpos[s1[i][1]] =j+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)
Fast Transpose of Sparse Matrix- Output

Input number of rows: 3


Original sparse matrix is
Input number of columns: 3
Row col Non_Zero_values
Input total number of non-zero values: 4
3 3 4
Enter row value: 0
0 1 10
Enter col value: 1
1 0 20
Enter the element: 10
2 0 30
Enter row value: 1
2 1 40
Enter col value: 0
Transposed sparse matrix is
Enter the element: 20
Row col Non_Zero_values
Enter row value: 2
3 3 4
Enter col value: 0
0 1 20
Enter the element: 30
0 2 30
Enter row value: 2
1 0 10
Enter col value: 1
1 2 40
Enter the element: 40
Fast Transpose of Sparse Matrix - Logic

 Consider the sparse matrix representative as

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]

i=1 i=2 i=3


rpos[1] = rpos[0]+rterm[0] rpos[2] = rpos[1]+rterm[1] rpos[3] = rpos[2]+rterm[2]
=1+2 =3+2 =5+0
rpos[1] = 3 rpos[2] = 5 rpos[3] = 5

rpos
0 1
1 3
2 5
3 5
Fast Transpose of Sparse Matrix - Logic

 Now we will read values of S1 array from 1 to 4


 We must find the triplet from S1 array which is at index 1.
 It is (0,1,10)
index row col value row col value
Just interchange
1 0 1 10
row and col 1 0 10
S1
Since, value is 1,
S2 Check rpos [1]
Non_Zero
Row Col
_Values
 rpos[1] points to value 3. That
0
means place the triplet (1,0,10) at
1 index 3 in S2 array
2
3 1 0 10
4
Fast Transpose of Sparse Matrix - Logic

 Now since rpos[1] is read just now, increment rpos[1] value by 1.


Hence rpos
0 1
1 34
2 5
3 5
 Read next element from S1 array

index row col value row col value


2 1 0 20 Interchange
0 1 20

rpos [0] = 1
Fast Transpose of Sparse Matrix - Logic

 That mean place triplet (0, 1, 20) at index 1 in S2 array


S2
Non_Zero
Row Col
_Values
0
1 0 1 20
2
3 1 0 10
4

rpos

 Since rpos[0] is just now, increment 0 12


rpos[0] by 1. 1 4
2 5
3 5
Fast Transpose of Sparse Matrix - Logic

 Read next element from S1 array

index row col value row col value


Interchange
3 2 0 30 0 2 30

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

 Read next element from S1 array 1 4


2 5
index row col value row col value
Interchange 3 5
4 2 1 40 1 2 40

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

 Thus we get transposed sparse matrix.


 Finally we fill up S2[0] by total number of rows, total number of columns and
total number of non-zero values.
 Thus we get… Non_Zero_Val
Row Col
ues
0 3 3 4
1 0 1 20
2 0 2 30
3 1 0 10
4 1 2 40

Time Complexity of Fast Transpose


For transposing the elements using simple transpose method we need
two nested for loops but in case of fast transpose we are determining the position
of the elements that get transposed using only one for loop. Hence the time
complexity of fast transpose is O(n)
Time and Space Tradeoff

 Concept:Time space trade-off is basically a situation where either a


space efficiency (memory utilization) can be achieved at the cost of
time or a time efficiency (performance efficiency) can be achieved at
the cost of memory.
 Example 1: Consider the programs like compilers in which symbol
table is used to handle the variables and constants. Now if entire
symbol table is stored in the program then the time required for
searching or storing the variable in the symbol table will be reduced
but memory requirement will be more. On the other hand, if we do not
store the symbol table in the program and simply compute the table
entries then memory will be reduced but the processing time will be
more.
 Example 2: Suppose, in a file, if we store the uncompressed data then
reading the data will be an efficient job but if the compressed data is
stored then to read such data more time will be required.
Time and Space Tradeoff

 Example 3: This is an example of reversing the order of the elements.


That is, the elements are stored in an ascending order and we want the
m in the descending order.
This can be done in two ways –
o We will use another array b[] in which the elements in descending or
der can be arranged by reading the array a[] in reverse direction.
This approach will actually increase the memory but time will be red
uced.
o We will apply some extra logic for the same array a[] to arrange the
elements in descending order. This approach will actually reduce the
memory but time of execution will get increased.
Time and Space Tradeoff - Program

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])

print("The elements in descending order (by method 2) are....")


mid=len(a)//2
for i in range(mid):
j=(len(a)-1)-i
temp=a[i]
a[i]=a[j]
a[j]=temp
for i in range(5):
print(a[i])
Time and Space Tradeoff - Output

The elements in descending order(By method 1) are....


50
40
30
20
10
The elements in descending order (by method 2) are....
50
40
30
20
10
Assignment No.2
1. Define & explain the term
i) Sequential Organization. ii) Ordered List
2. Explain polynomial representation using arrays with suitable example
3. Derive address calculation formula for one-dimensional array with one
example.
4. Explain two-dimensional arrays with row and column major
implementation. Explain address calculation in both cases with example.
5. What is sparse matrix ? Explain its representation with an example.
6. Explain fast Transpose of sparse matrix with suitable example,
Discuss time complexity of fast transpose.
7. Write Python code to perform simple transpose of sparse matrix.
Discuss its time complexity.
8. Write Python code to perform polynomial multiplication using array.
9. Explain List Comprehension along with its methods
10. Write Python code to perform Addition & Multiplication of Matrix.
Case Study – 2

1. Study use of Sparse matrix in Social Networks


and Maps.
2. Study how Economists use polynomials to model
economic growth patterns, how medical
researchers use them to describe the behavior of
Covid-19 virus.

You might also like