Screenshot 2023-11-08 at 6.22.02 PM
Screenshot 2023-11-08 at 6.22.02 PM
STUDENT NAME :
REGISTER
:
NUMBER
YEAR &
: 2022- I Semester
SEMESTER
SUBJECT
: Data Analysis Fundamentals
TITLE
i
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
CERTIFICATE
Certified to be the bonafide record of practical work done by
______________________________________Register No.__________________________ of
Degree course for PAD21102J - Data Analysis Fundamentals in the
Computer lab in SRM Institute of Science and Technology during the academic
year 2022-2023.
ii
Index
S.No: Program Title Page. Staff
No Signature
1 GCD of two numbers
2 Square Root of a Number (Newton’s method)
3 To find Maximum of a List of Numbers
4 Menu Program
5 Palindrome or Not
6 To Find Factorial of a given number using functions,
7 Comparison of lists
8 Sort (ascending and descending) a dictionary by value
9 Python script to check if a given key already exists in a
dictionary.
10 Merge two Python dictionaries
11 To find shortest list of values with the keys in a given
dictionary.
12 To Check a Number is Spy number or Not
13 To print all Twin Primes numbers
14 To Convert Decimal to hexadecimal using while loop.
15 To find sum of two numbers using class and methods.
16 To read 3 subject marks and display pass or failed using
class and object.
17 To find Area of Rectangle, Circle and Square using
Hierarchical Inheritance
18 To find All Arithmetic operation using multilevel and
multiple inheritance
19 Method Overloading –I
20 Method Overloading -II
21 Date Time formats –I
22 Date Time format –II
23 Date Time format –III
iii
Index
S.No: Program Title Page. Staff
No Signature
24 Date Time format –IV
25 Dataframe Concatenation
26 Loading Datasets
27 Data Analysis using Pandas
28 Numpy Array operations-I
29 Numpy Array operations-II
30 Multi-dimensional arrays and find its shape and dimension
31 To Create a matrix full of zeros and ones.
32 To Reshape and flatten data in the array
33 To Append data vertically and horizontally
34 To Apply indexing and slicing on array
35 To Use statistical functions on array - Min, Max, Mean, Median
and SD.
36 To compute the Dot and matrix product of two arrays
37 To Compute the Eigen values of a matrix
38 To Compute the multiplicative inverse of a matrix
39 To compute the rank of a matrix.
40 To Compute the determinant of an array
41 To Solve a linear matrix equation such as 3 * x0 + x1 = 9, x0 + 2
* x1 = 8
iv
DATE: 1
Ex. No: 1 GCD of two numbers.
AIM: To write a python program to compute the GCD of two numbers.
ALGORITHM:
Step 1: Create a function that uses loops to compute the GCD of two numbers that takes two
parameters.
Step 2: In the function assign the smallest of the two numbers to a variable small.
Step 3:Using the for loop check if the iteration i while iterating in range from 1 to small+1
perfectly divides the two numbers.
Step 4: The value of i that dividies the numbers perfectly is the GCD.
CODE:
def computeGCD(x, y):
if x > y:
small = y
else:
small = x
for i in range(1, small + 1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd
a=int(input("Enter 1st value to find GCD"))
b=int(input("Enter 2nd value to find GCD"))
print("value of gcd is:",computeGCD(a,b))
OUTPUT:
1
DATE:
Ex. No: 2 Square Root of a Number (Newton’s method)
AIM: To write a python program to find the square root of a number using
Newton’s method.
ALGORITHM:
Step 1: Create a function that uses the formula, root = 0.5 * (X + (N / X)) where X is any guess
which can be assumed to be N or 1.
Step 2: Keep the loop running for 500 iterations as the calculated root will get closer to the real
root with repetition.
Step 3: Print the value after the end of the iterations.
CODE:
def newton_method(n,n_iters=500):
a=float(n)
for i in range(n_iters):
n=0.5*(n+(a/n))
return n
a=int(input("Enter number to find square root of:"))
print("The square root is:",newton_method(a))
OUTPUT:
2
DATE:
Ex. No: 3 Maximum of a List of Numbers.
CODE:
lst=[]
n=int(input("Enter the number of elements in the
list:"))
for i in range(0,n):
k=n
k-=i
ele=int(input("Enter the {} number".format(k)))
lst.append(ele)
print("The Largest element is:",max(lst))
OUTPUT:
3
DATE:
Ex. No: 4 Menu Program
AIM: To write a menu program that take two values performs Addition,
Subtraction, Multiplication or Division based on the user's choice.
ALGORITHM:
Step 1: Define four functions that perform each of the given arithmetic operations and print the
output.
Step 2: Take user input of the two values then take the input of the user's menu choice.
Step 3: Use if condition to check for menu choice and call the respective function.
CODE:
def add(a,b):
print("The sum of the numbers is:",a+b)
def sub(a,b):
print("The differnce between the numbers
is:",abs(a-b))
def div(a,b):
print("The quotient is:",a/b,"\n")
print("The remainder is:",a%b,"\n")
def mult(a,b):
print("The product is:",a*b)
a=int(input("Enter 1st value:"))
b=int(input("Enter 2nd value:"))
4
add(a,b)
elif n==2:
sub(a,b)
elif n==3:
mult(a,b)
elif n==4:
div(a,b)
else:
print("Invalid entry")
OUTPUT:
5
DATE:
Ex. No: 5 Palindrome
AIM: To Write a python program to check whether the given string is
palindrome or not.
ALGORITHM:
Step 1: Create a function that checks the if the reversed string is the same as the original string
and returns a boolean vlaue.
Step 3: Take a string input from user.
Step 4: If TRUE is returned by the function the print it is a palindrome or else that it is not.
CODE:
def ispalindrome(s):
return s==s[::-1]
p=input("Enter the word:")
p=p.lower()
t=ispalindrome(p)
if t:
print("The word is a palindrome")
else:
print("The word is not a palindrome")
OUTPUT:
6
DATE:
Ex. No: 6 Factorial
AIM: To write a python program to find factorial of a given number using
functions,
ALGORITHM:
Step 1: Create function that finds the factorial by using a for loop and uses the if condition to
check the number.
Step 2: Print the output of the function.
CODE:
def findfactorial(n):
factorial=1
if n==0:
print("The factorial for 0 is 1")
elif n<0:
print("Negative numbers have no factorial")
else:
for i in range(1,n+1):
factorial=factorial*i
print(f"The factorial of {n} is",factorial)
n=int(input("Enter the number to find factorial for:"))
findfactorial(n)
OUTPUT:
7
DATE:
Ex. No: 7 Comparison of lists
AIM: To Write a Python function that takes two lists and returns true if they
are equal otherwise false
ALGORITHM:
Step 1: Take user inputs for two lists.
Step 2: Sort both lists.
Step 3: Use if condition to check the equality of both lists and print the respective output for
each of the two outputs.
CODE:
a=[]
b=[]
n=int(input("Enter the number of items for both
lists"))
print("Enter elements of first list:")
for i in range(n):
ele=float(input("Enter element:"))
a.append(ele)
print("Enter elements of second list:")
for i in range(n):
ele=float(input("Enter element:"))
b.append(ele)
a.sort()
b.sort()
if a==b:
print("The lists are equal")
8
else:
print("The lists are not equal")
OUTPUT:
9
DATE:
Ex. No: 8 Sort dictionary by value
AIM: To Write a Python script to sort (ascending and descending) a
dictionary by value using item function
ALGORITHM:
Step 1: Create two dictionaries to store the sorted dictionary.
Step 2: In each of the dictionary use the sorted function in a for loop to sort the dictionaries by
value.
Step 3: Print the two dicitonaries.
CODE:
student={'Ravi': 10,'Kumar': 20,'Raja': 9,'Babu': 43}
sortedbyval={k: v for k, v in
sorted(student.items(),key= lambda v: v[1])}
sortedbyvald={k: v for k, v in
sorted(student.items(),key= lambda v:
v[1],reverse=True)}
print(sortedbyval)
print(sortedbyvald)
OUTPUT:
10
DATE:
Ex. No: 9 Check For a key in a dictionary
AIM: To Write a Python script to check if a given key already exists in a
dictionary.
ALGORITHM:
Step 1: Create a function that take in a dictionary and key as its arguments.
Step 2: In the function use the .key() function on the dictionary to get its keys.
Step 3: Use the if function to check if the key is there in .keys() function.
Step 4: Print the output response.
CODE:
def checkkey(dic,key):
if key in dic.keys():
print("The key is present:",dic[key])
else:
print("The key is not present.")
dic={'a':250,'b':300,'c':150}
key=input("Enter the key to check ")
checkkey(dic,key)
OUTPUT:
11
DATE:
Ex. No: 10 Merge two Python dictionaries
AIM: To Write a Python script to merge two Python dictionaries
ALGORITHM:
Step 1: Crete a function that takes two dictionaries as the input and merges them using the merge
dictionary operator(|) and returns it.
Step 2: Store the returned merged dictionary in another variable and the print the variable.
CODE:
def merge(dict1,dict2):
result=dict1 | dict2
return result
dict1={}
dict2={}
n=int(input("Enter the number of items in dict1:"))
k=int(input("Enter the number of items in dict2:"))
print("Creating dictionary 1:")
for i in range(n):
key=input("Enter key:")
value=input("Enter value:")
dict1[key]=value
print("Creating dictionary 2:")
for j in range(k):
keys=input("Enter the key:")
values=input("Enter the value:")
dict2[keys]=values
print("original dictionary1:",dict1)
print("original dictionary2:",dict2)
12
dict3=merge(dict1,dict2)
print("The merged dictionary is:",dict3)
OUTPUT:
13
DATE:
Ex. No: 11 shortest key in Dictionary
AIM: To Write a Python program to find shortest list of values with the keys
in a given dictionary.
ALGORITHM:
Step 1: Create a function to check the key with the lowest values:
Step 2: Find the minimum length of a key's values using the min function and store it in variable.
Step 3: Run a for loop to check which key has the length equal to the minimum value found
above.
Step 4: Print the corresponding key and value that fulfill the condition.
CODE:
def checkl(dict):
minval=min([len(dict[ele]) for ele in dict])
res=[]
for ele in dict:
if len(dict[ele])==minval:
res.append(ele)
print("The list of keys with lowest values are:",res)
dict1={'k':[30,40],'b':[56,43,232],'c':[56,1],'f':[32,23,21
],'g':[43,23]}
checkl(dict1)
The list of keys with lowest values are: ['k', 'c', 'g']
OUTPUT:
14
DATE:
Ex. No: 12 SPY Number
AIM: To Write a python Program to Check a Number is Spy number or Not
ALGORITHM:
Step 1: Initialise two variables sum as 0 and product as 1.
Step 2: Take the user input for the number to be checked.
Step 3: Using while loop split the number to digits find the sum of digits and product of digits
and assign each to the Sum and product variable created above.
Step 4: If the sum and product are equal print that it is a spy number if not that it is not a spy
number.
CODE:
num=int(input("Enter your number "))
sum=0
product=1
num1 = num
while(num>0):
d=num%10
sum=sum+d
product=product*d
num=num//10
if(sum==product):
print("{} is a Spy number!".format(num1))
else:
print("{} is not a Spy number!".format(num1))
OUTPUT:
CODE:
def printTwinPrime(n):
prime = [True for i in range(n + 2)]
p = 2
while (p * p <= n + 1):
if (prime[p] == True):
for i in range(p * 2, n + 2, p):
prime[i] = False
p += 1
for p in range(2, n-1):
if prime[p] and prime[p + 2]:
print("(",p,",", (p + 2), ")" ,end='')
n=int(input("Enter number to find twin prime's for"))
printTwinPrime(n)
OUTPUT:
16
DATE:
Ex. No: 14 Decimal to Hexadecimal
AIM: To write a python program to Convert Decimal to hexadecimal using
while loop.
ALGORITHM:
Step 1: Create a dictionary that has the decimal values as its key and the the hexadecimal values
as its value.
Step 2: Create a function that takes in the decimal values as its input:
Step 3: Split the number into digits and replace it with the corresponding hexadecimal value in
the dictionary and Store it in a variable and then print it
Step 4: Print the variable that has the converted hexadecimal number.
CODE:
conversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4:
'4',5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A',
11: 'B', 12: 'C',13: 'D', 14: 'E', 15: 'F'}
def decimalToHexadecimal(decimal):
hexadecimal = ''
while(decimal > 0):
remainder = decimal % 16
hexadecimal = conversion_table[remainder] +
hexadecimal
decimal = decimal // 16
return hexadecimal
decimalnumber=int(input("Enter the decimal number :"))
print("The hexadecimal form of", decimalnumber,"is",
decimalToHexadecimal(decimalnumber))
17
OUTPUT:
18
DATE:
Ex. No: 15 Sum of two numbers using class.
AIM: To Write a program to find sum of two numbers using class and
methods.
ALGORITHM:
Step 1: Create a class named addition that has a method add that returns the sum of two
numbers.
Step 2: Take two numbers as input from the user and pass them into the class method
Step 3: Print the result returned by the method.
CODE:
class addition:
def add(a,b):
return a+b
a=int(input("Enter 1st number"))
b=int(input("Enter the 2nd number"))
print("The sum of the numbers are:",addition.add(a,b))
OUTPUT:
19
DATE:
Ex. No: 16 Marks result using class
AIM: To write a program to read 3 subject marks and display pass or failed
using class and object.
ALGORITHM:
Step 1: Create a class result that takes a mark as its input.
Step 2: After the init function create a method that returns pass if the mark is greater than 50 if
not fail.
Step 3: pass the input from the user directly into the fucntion parameter.
CODE:
class result:
def __init__(self,n):
self.n=n
if(n<50):
print("The student has failed")
elif(n>=50):
print("The student has passed")
result(int(input("Enter the marks for the student")))
result(int(input("Enter the marks for the student")))
result(int(input("Enter the marks for the student")))
OUTPUT:
20
DATE:
Ex. No: 17 Area's using Hierarchical Inheritance
AIM: To write a python Programming to find Area of Rectangle, Circle and
square using Hierarchical Inheritance
ALGORITHM:
Step 1: Create a class side that has s initialized in its init function.
Step 2: Create a class square that inherits from side and has a method area that returns the area
of square using s.
Step 3: Create a class rectangle that inherits from side and also has its own parameter b that is
initialized using the init Function and uses super to inherit s. Create a method in it that
returns the area of rectangle using b and s.
Step 4: Create a class circle that inherits from side and has a method area that returns the area of
circle using s.
Step 5: Create an instance of each class and pass a value into its parameter.
Step 6: Print the method area from each class instance.
CODE:
class side:
def __init__(self,s):
self.s=s
class square(side):
def area(self):
return self.s*self.s
class rectangle(side):
def __init__(self,s,b):
super().__init__(s)
self.b=b
def area(self):
return self.s*self.b
21
class circle(side):
def area(self):
return 3.14*self.s*self.s
sq=square(2)
print("Area of square:",sq.area())
rect=rectangle(7,6)
print("Area of rectangle is",rect.area())
circ=circle(5)
print("Area of circle is:",circ.area())
OUTPUT:
22
DATE:
25
DATE:
Ex. No: 19 Method Overloading -I
AIM: To write a python program to find sum of the two numbers and product
of the three numbers using method overloading.
ALGORITHM:
Step 1: Create a function that has its three arguments all initialized as none:
Step 2: Using if condition, if two of those arguments are not none because two values have been
passed into the function, find and print the sum of the two values.
Step 3: Else if all three argument are not none because three values have been passed into the
function, find and print the product of the three values.
CODE:
def func(a=None,b=None,c=None):
if a!=None and b!= None and c==None:
print("The sum is :",a+b)
elif a!=None and b!= None and c!=None:
print("The product of 3 numbers is:",a*b*c)
else:
print("Nothing to find")
func(8,9)
func(10,3,2)
OUTPUT:
26
DATE:
Ex. No: 20 Method Overloading -II
AIM: To write a python programming to find area of Square and area of
Triangle using method overloading
ALGORITHM:
Step 1: Create a function that has its two arguments all initialized as none:
Step 2: Using if condition, if one of those arguments are not none because one value has been
passed into the function, find and print the area of the square.
Step 3: Else if all two arguments are not none because tow values have been passed into the
function, find and print the area of triangle.
CODE:
def area(a=None,b=None):
if a!=None:
print("The area of the square is:",a*a)
elif a!=None and b!= None:
print("The area of the triangle is:",0.5*a*b)
area(7)
area(10,2)
OUTPUT:
27
DATE:
Ex. No: 21 Date Time formats -I
AIM: To Write a Python to print the various Date Time formats. a) Current
date and time b) Current year c) Month of year d) Week number of the
year e) Weekday of the week f) Day of year g) Day of the month h) Day
of week
ALGORITHM:
Step 1: Import time and date time libraries.
Step 2: Using the functions from the date and time libraries print the required formats of date
and time.
CODE:
import time
import datetime
print("Current date and time: " ,
datetime.datetime.now())
print("Current year: ",
datetime.date.today().strftime("%Y"))
print("Month of year: ",
datetime.date.today().strftime("%B"))
print("Week number of the year: ",
datetime.date.today().strftime("%W"))
print("Weekday of the week: ",
datetime.date.today().strftime("%w"))
print("Day of year: ",
datetime.date.today().strftime("%j"))
print("Day of the month : ",
datetime.date.today().strftime("%d"))
28
print("Day of week: ",
datetime.date.today().strftime("%A"))
OUTPUT:
29
DATE:
Ex. No: 22 Date Time format -II
AIM: To Write a Python program to add 5 seconds with the current time.
ALGORITHM:
Step 1: Import date time libraries.
Step 2: Save the current time in a variable.
Step 3: Using time delta () add 5 seconds to the current time variable and save it to another
variable.
Step 4: Print both variables.
CODE:
import datetime
x= datetime.datetime.now()
y = x + datetime.timedelta(0,5)
print(x.time())
print(y.time())
OUTPUT:
30
DATE:
Ex. No: 23 Date Time format -III
AIM: To Design a Python script to determine the difference in date for given
two dates in YYYY: MM: DD format (0 <=YYYY <= 9999, 1 <= MM
<= 12, 1 <= DD <= 31) following the leap year rules.
ALGORITHM:
Step 1: Take two user inputs of dates in the format of: yyyy: mm:dd
Step 2: Use strp time to change the two input dates into date time objects and store it each in a
variable.
Step 3: Subtract them from each other and store the difference.
Step 4: Print the difference.
CODE:
from datetime import datetime
d1=input("Enter date as yyyy:mm:dd:")
d2=input("Enter date as yyyy:mm:dd:")
d3=datetime.strptime(d1,"%Y:%m:%d").date()
d4=datetime.strptime(d2,"%Y:%m:%d").date()
diff=d4-d3
print("The differnce between the days is:",diff)
OUTPUT:
31
DATE:
Ex. No: 24 Date Time format -IV
AIM: To Design a Python Script to determine the time difference between two
given times in HH:MM:SS format.( 0 <= HH <= 23, 0 <= MM <= 59, 0
<= SS <= 59).
ALGORITHM:
Step 1: Take two user inputs in the format HH:MM:SS
Step 2: Use strptime to change the two input dates into date time objects and store it each in a
variable.
Step 3: Subtract them from each other and store the difference.
Step 4: Print the difference.
CODE:
from datetime import datetime
t1=input("Enter time in HH:MM:SS:")
t2=input("Enter time in HH:MM:SS:")
t3=datetime.strptime(t1,"%H:%M:%S")
t4=datetime.strptime(t2,"%H:%M:%S")
diff=t4-t3
print("The difference in time is:",diff)
OUTPUT:
32
DATE:
Ex. No: 25 Dataframe Concatenation
AIM: To write a python program to concatenate the dataframes with two
different objects.
ALGORITHM:
Step 1: Import pandas library.
Step 2: Create two dataframes.
Step 3: Use the concat function from pandas to concatenate the two dataframes.
Step 4: Print the result.
CODE:
import pandas as pd
df1=pd.DataFrame({"A":["A0","A1","A2","A3"],"B":["B0","B1",
"B2","B3"],"C":["C0","C1","C2","C3"]},index=[0,1,2,3])
df2=pd.DataFrame({"A":["A4","A5","A6","A7"],"B":["B4","B5",
"B6","B7"],"C":["C4","C5","C6","C7"]},index=[4,5,6,7])
print("The dataframe after concatenation
is:\n",pd.concat([df1,df2]))
OUTPUT:
33
DATE:
Ex. No: 26 Loading Datasets
AIM: To write a python code to read a csv file using pandas module and print
the first and last five lines of a file
ALGORITHM:
Step 1: Import pandas.
Step 2: Create a list that has the column names of the dataset.
Step 3: In read_csv function from pandas add the dataset path and column names to load the
dataset.
Step 4: Store the dataset in a variable.
Step 5: Print the first and last five rows in the dataset using the head and tail function.
CODE:
import pandas as pd
url="https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data"
new_names=['sepal_length','sepal_width','petal_length',
'petal_width','iris_class']
dataset=pd.read_csv(url, names=new_names, skiprows=0,
delimiter=',')
print("The first 5 top data is:")
print(dataset.head(5))
print("The last 5 data is:")
print(dataset.tail(5))
34
OUTPUT:
35
DATE:
Ex. No: 27 Data Analysis using Pandas
AIM: To write a python program to find Pandas Math Functions for Data
Analysis. Let us go through the following Pandas math functions: mean
( ), sum ( ), median ( ), min ( ), max ( ), value_counts( ) and describe()
function.
ALGORITHM:
Step 1: Import pandas.
Step 2: Create a dataframe using a dictionary.
Step 3: Use the functions to find mean, median, sum, maximum and minimum of the dataframe
and print the results.
CODE:
import pandas as pd
sample={"Temp":[20,24,45,30],"Wind":[1,2,0.5,3],"Humidity":
[10,5,35,20]}
s=pd.DataFrame(sample)
print("The mean for the above dataframe
is:\n",s.mean(),'\n')
print("The sum for the above dataframe is:\n",s.sum(),'\n')
print("The median for the above dataframe
is:\n",s.median(),'\n')
print("The maximum in the above dataframe
is:\n",s.max(),'\n')
print("The minimum in the above dataframe
is:\n",s.min(),'\n')
print("The value counts for temperature, wind and humidity
are:\n",s.Temp.value_counts(),s.Wind.value_counts(),
s.Humidity.value_counts(),'\n')
36
print("The description of the dataframe
is:\n",s.describe(),'\n')
OUTPUT:
37
RESULT: The program is executed and verified.
38
DATE:
Ex. No: 28 Numpy Array operations-I
AIM: To write a basic array of operations on single array to add x to each
element of array and subtract y from each element of array Using
Numpy,
ALGORITHM:
Step1: Import numpy.
Step 2: Take a list as user input and convert it into a numpy array.
Step 3: Use a menu program to and take user's choice.
Step 4: According to user choice add or subtract the number using for loop inside the array
square brackets.
Step 5: Print the respective result.
CODE:
import numpy as np
a=[]
n=int(input("Enter the number of elements in the
array:"))
for i in range(n):
ele=float(input("Enter the element value:"))
a.append(ele)
np.array(a)
c=int(input("If you want to add an element to each
element press 1\nIf you want to subtract from each
element press 2\n"))
print("The original array is:",a)
if c==1:
k=float(input("Enter the number you want to add:"))
39
new_a=[x+k for x in a]
print("The new array is:",new_a)
elif c==2:
m=float(input("Enter the number you want to
subtract:"))
new_a_1=[x-m for x in a]
print("The new array is:",new_a_1)
else:
print("Invalid entry")
OUTPUT:
40
DATE:
No: 29 Numpy Array operations-II
AIM: To Use Numpy, write a program to add, subtract and multiply two
matrices.
ALGORITHM:
Step1: Import numpy
Step2: Create two matrices and print them.
Step 3: Use dot product to multiply the two matrices and save the product in a variable.
Step 4: print the product.
Step 5: Create two more matrices and print.
Step 6: Use the add and subtract functions from pandas to get the Difference and sum of the
matrices.
Step 7: Store the difference and sum in two variables.
Step 8: Print the sum and difference.
CODE:
import numpy as np
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
result= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
print("The first matrice is:")
for i in A:
41
print(i)
print("The second matrice is:")
for j in B:
print(j)
print("multiplying the matrices:")
result = np.dot(A,B)
print("The product of the two matrices are:")
for r in result:
print(r)
C = np.array([[1, 2], [3, 4]])
D = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix:")
print(C)
print("Printing elements of second matrix:")
print(D)
print("Addition of two matrix:")
print(np.add(C, D))
print("Subtraction of two matrix:")
print(np.subtract(C, D))
42
OUTPUT:
43
DATE:
Ex. No: 30 Numpy-I
AIM: To Create multi-dimensional arrays and find its shape and dimension.
ALGORITHM:
Step 1: Import numpy.
Step 2: Take user input for number for rows and columns.
Step 3: Take the elements for the matrix as user input, each element separated by space.
Step 4: Use the split () method to take multiple inputs in a single line and save it in a variable as
a list
Step 5: Store this list by converting it into a numpy array and reshaping it into a ndarray using
reshape in a variable.
Step 6: Print the matrix.
CODE:
import numpy as np
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
print("Enter the entries in a single line (separated by
space): ")
entries = list(map(int, input().split()))
matrix = np.array(entries).reshape(R, C)
print(matrix)
matrix.shape
44
OUTPUT:
45
DATE:
Ex. No: 31 Numpy-II
AIM: To Create a matrix full of zeros and ones.
ALGORITHM:
Step 1: Import numpy.
Step 2: Use the Zeros and ones functions to create a matrix of zeros and ones
CODE:
import numpy as np
print(np.zeros((5,5)))
print(np.ones((3,3)))
OUTPUT:
46
DATE:
Ex. No: 32 Numpy-III
AIM: To Reshape and flatten data in the array
ALGORITHM:
Step 1: Create a matrix using user input and print the original matrix.
Step 2: Reshape the matrix using reshape function and switch the rows and column.
Step 3: Use the flatten function to flatten the matrix.
Step 4: Print the reshaped and flattened matrix.
CODE:
import numpy as np
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
print("Enter the entries in a single line (separated by
space): ")
entries = list(map(int, input().split()))
matrix = np.array(entries).reshape(R, C)
print(matrix)
print("Reshaped array is:")
print(matrix.reshape(C,R))
k=matrix.flatten()
print("The flattened array is :")
print(k)
47
OUTPUT:
48
DATE:
Ex. No: 33 Numpy-IV
AIM: To Append data vertically and horizontally
ALGORITHM:
Step 1: Create two numpy arrays.
Step 2: Use the hstack and vstack functions to stack the array horizontally and vertically.
Step 3: Print the results.
CODE:
import numpy as np
a=np.array([1,2,3])
b=np.array([4,5,6])
c=np.vstack([a,b])
print("Array1 is:",a)
print("Array2 is :",b)
print("Array after stacking vrtically is:",c)
d=np.hstack([a,b])
print("Array after stacking horizontally is:",d)
OUTPUT:
49
DATE:
Ex. No: 34 Numpy-V
AIM: To apply indexing and slicing on array
ALGORITHM:
Step 1: Import numpy
Step 2: Create a numpy array.
Step 3: Perform basic numpy slicing and indexing methods and print them.
CODE:
import numpy as np
arr = np.arange(0,11)
print("Array before indexing and slicing is:",arr)
print("8th element of the array is",arr[8])
print("Printing elements from 1 to 5:",arr[1:5])
print("Condtional selection:")
bool_arr= arr>4
print("Elements of array greater than:")
print(arr[bool_arr])
OUTPUT:
50
DATE:
Ex. No: 35 Numpy-VI
AIM: To Use statistical functions on array - Min, Max, Mean, Median and
Standard Deviation.
ALGORITHM:
Step 1: Import numpy and statistics libraries.
Step 2: Create a numpy array.
Step 3: Use the min(),max(),mean(),median() and stdev() functions from statistics on the array.
Step 4: Print the results individually.
CODE:
import numpy as np
import statistics as st
arr1=np.array([23,42,12,432,54,67,69])
print("The array is:",arr1)
print("The maximum value in this array is:",arr1.max())
print("The minimum vlaue in this array is:",arr1.min())
print("The mean is:",st.mean(arr1))
print("The median is:",st.median(arr1))
print("The Standard Deviation of the array
is:",st.stdev(arr1))
OUTPUT:
51
DATE:
Ex. No: 36 Numpy-VII
AIM: To compute the Dot and matrix product of two arrays.
ALGORITHM:
Step 1: Import numpy
Step 2: Create two matrices.
Step 3: Create two additional matrices initialized to zero with the same number of rows and
columns to store the result.
Step 4: Use the dot() and matmul() functions from numpy to get the dot and matrix
multiplication products for the two matrices.
Step 5: Store the results in each of the matrices that were initialized to zeros.
Step 6: Print the stored results.
CODE:
import numpy as np
A = [[12, 7, 3],
[8, 5, 6],
[7, 8, 9]]
B = [[10, 8, 1, 9],
[6, 7, 3, 0],
[4, 5, 9, 1]]
result= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
result1= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
print("The two matrix are:")
for i in A:
52
print(i)
print("\n")
for j in B:
print(j)
result=np.dot(A,B)
print("The dot product of the two matrices is:")
for r in result:
print(r)
result1=np.matmul(A,B)
print("The matrix multiplication product of the two
matrices is:")
for k in result1:
print(k)
OUTPUT:
53
DATE:
Ex. No: 37 Numpy-VII
ALGORITHM:
Step1 : Import numpy
Step 2: Create a square matrix.
Step 3: Print the orignial matrix.
Step 4: Use the linalg.eig() function to find the eigen values and eigen vectors of the matrix.
Step 5: Print only the eigen values.
CODE:
import numpy as np
m = np.array([[1, 2],
[2, 3]])
print("Printing the Original square matrix:\n",m)
w, v = np.linalg.eig(m)
print("Printing the Eigen values of the given square
array:\n",w)
OUTPUT:
54
DATE:
Ex. No: 38 Numpy-IX
AIM: To compute the multiplicative inverse of a matrix
ALGORITHM:
Step 1: Import numpy
Step 2: Create a numpy array.
Step 3: Print the array.
Step 4: Using the inv() function from the linalg() module from numpy, invert the matrix and
print it.
CODE:
import numpy as np
arr=np.array([[ 5, 10], [ 15, 20 ]])
print("The original array is:",arr2)
print("The multiplicative inverse of the Matrix
is:",np.linalg.inv(arr2))
OUTPUT:
55
DATE:
Ex. No: 39 Numpy-X
AIM: To Compute the rank of a matrix.
ALGORITHM:
Step 1: Import numpy
Step 2: Create a matrix.
Step 3: Pass the matrix into the matrix_rank() function from the linalg module from numpy to
get its rank.
Step 4: Print the rank.
CODE:
import numpy as np
Matrix = np.array([[10, 20, 10],
[-20, -30, 10],
[30, 50, 0]])
print("The Rank of the matrix
is:",np.linalg.matrix_rank(Matrix))
OUTPUT:
56
DATE:
Ex. No: 40 Numpy-XI
AIM: To compute the determinant of an array
ALGORITHM:
Step 1: Create a matrix.
Step 2: Print the original array.
Step 3: Using the det() function from the linalg module from python find the determinant and
store it in a variable.
Step 4: Print the determinant.
CODE:
import numpy as np
n_array = np.array([[50, 29], [30, 44]])
print("Matrix is:")
print(n_array)
det = np.linalg.det(n_array)
print("\nDeterminant of given matrix is:")
print(int(det))
OUTPUT:
57
DATE:
Ex. No: 41 Solving Linear Equations.
ALGORITHM:
Step 1: Import symbols, Eq and solve functions from sympy (symbolic mathematics python).
Step 2: Change x and y into symbols using the symbols function.
Step 3: Store the equations using the Eq function.
Step 4: Print the two equations.
Step 5: Pass the two equations into the solve function and pass the variables to solve for.
Step 6: Print the solutions to the variables.
CODE:
from sympy import symbols, Eq, solve
x, y = symbols('x,y')
eq1 =Eq((3*x+y),9)
eq2=Eq((x+2*y),8)
print("Equation 1:")
print(eq1)
print("Equation 2")
print(eq2)
print("Values of 2 unknown variable are as follows:")
print(solve((eq1, eq2), (x, y)))
58
OUTPUT:
59