0% found this document useful (0 votes)
14 views11 pages

PDA Lab Prog (Short)

Uploaded by

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

PDA Lab Prog (Short)

Uploaded by

Unknown Person
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

PDA Lab prog(short)

LAB PROGRAM 1 Write a python program to find sum of n natural numbers using recursive function

def naturalSum(n):

if n == 1:

return 1

else:

return n+naturalSum(n-1)

n = int(input("Enter a number: "))

res = naturalSum(n)

print(f"Sum of first {n} natural number is: {res}")

LAB PROGRAM 2 Write a Python Program to Create a Dictionary with Key as First Character and Value
as Words Starting with that Character.

words = ["apple","banana","coconut","durian","apricot","corn","berry","dalgona"]

d = {}

for word in words:

fchar = word[0]

if fchar in d:

d[fchar].append(word)

else:

d[fchar] = [word]

print(d)
LAB PROGRAM 3 Implement a Python program to count the numbers of characters in the string and
store them in a dictionary data structure

string = str(input("Enter the string: "))

length = 0

d = {}

for ch in string:

if(ch == ' '):

continue

length += 1

for ch in string:

if(ch == ' '):

continue

if ch not in d:

d[ch] = 1

else:

d[ch] += 1

print("Length of string is ", length)

print("The required dictionary is ",d)

LAB PROGRAM 4 Design and Develop a Python Program to Append, Delete and Display Elements of a
List Using Classes and Objects.

class ListOperation:

def __init__(self):

self.List = []

def Append(self, x):


self.List.append(x)

def Delete(self, x):

if x in self.List:

self.List.remove(x)

else:

print(f"{x} is not found")

def Display(self):

if not self.List:

print("Empty List")

else:

for x in self.List:

print(x, "\t")

def main():

Operation = ListOperation()

isRunning = True

while isRunning:

print("1. Append 2. Delete 3. Display 4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

x = input("Enter value to append: ")

Operation.Append(x)

elif choice == 2:

x = input("Enter value to delete: ")

Operation.Delete(x)

elif choice == 3:

Operation.Display()

elif choice == 4:

isRunning = False
else:

print("Invalid choice")

if __name__ == "__main__":

main()

LAB PROGRAM 5 Demonstrate the concept of Method Resolution order in multiple inheritance in
Python Program.

class A:

def show(self):

print("Method of class A\n")

class B(A):

def show(self):

print("Method of class B\n")

class C(A):

def show(self):

print("Method of class C\n")

class D(B,C):

pass

d = D()

d.show()

print("Method of resolution order (MRO)\n")

print(D.mro())

LAB PROGRAM 6 Design and Implement a Python Program to perform addition, subtraction,
multiplication of two complex numbers using binary operators overloading.
class complexnumber:

def __init__(self,real,imag):

self.real = real

self.imag = imag

def __add__(self,other):

return complexnumber(self.real + other.real, self.imag + other.imag)

def __sub__(self,other):

return complexnumber(self.real - other.real, self.imag - other.imag)

def __mul__(self,other):

real_part = self.real * other.real - self.imag * other.imag

imag_part = self.real * other.imag + self.imag * other.real

return complexnumber(real_part, imag_part)

def __str__(self):

return f"{self.real}+{self.imag}i" if self.imag>=0 else f"{self.real}-{-self.imag}i"

c1 = complexnumber(3,7)

c2 = complexnumber(1,10)

print("Addition: ",c1 + c2)

print("Subtraction: ",c1 - c2)

print("Multiplication: ",c1 * c2)

LAB PROGRAM 7 Demonstrate with a python program to show the speed of execution is more when
using numpy array

import numpy as np

import time

size = 1000000

list1 = range(size)
list2 = range(size)

array1 = np.arange(size)

array2 = np.arange(size)

initialtime = time.time()

resultantlist = [(a*b) for a, b in zip(list1, list2)]

print("Time taken by lists: ", (time.time()-initialtime),"seconds")

initialtime = time.time()

resultantArr = array1*array2

print("The time taken by numpy Arrays: ", (time.time()-initialtime),"seconds")

LAB PROGRAM 8 Write a program to read the data and perform correlation, Two way conditional
probability, joint probability and marginal probability.

import pandas as pd

import numpy as np

data = {

'A' : [1,1,0,1],

'B' : [0,1,1,0]

df = pd.DataFrame(data)

print("Reading CSV: \n",df)

correlation = df.corr()

print("\nCorrelation:\n",correlation)

jointFreq = pd.crosstab(df['A'], df['B'])


jointProb = jointFreq / jointFreq.values.sum()

print("\nJoint probability:\n",jointProb)

margProbA = jointProb.sum(axis = 1)

print("\nmarginal Probability of A\n",margProbA)

margProbB = jointProb.sum(axis = 0)

print("\nmarginal Probability of B\n",margProbB)

condProbAgivenB = jointProb.div(margProbB, axis = 1)

print("\n Condition Probability of A given B\n",condProbAgivenB)

condProbBgivenA = jointProb.div(margProbA, axis = 0)

print("\n Condition Probability of B given A\n",condProbBgivenA)

lab program 9. Write a program to analyse the given data and perform the operation to find the
missing data.

import pandas as pd

data = {

'Name':['Aditya','Akash',None,'Ayush'],

'age':[None, 19,21, 20],

'city':['Bihar','Blr','Delhi', None]

df = pd.DataFrame(data)

print(df)

print("\n")
a = df.isnull().any(axis=0)

b = df.isnull().sum(axis=0)

print(a)

print("\n")

print(b)

c = df.isnull().any(axis = 1)

d = df.isnull().sum(axis = 1)

print("\n")

print(c)

print("\n")

print(d)

LAB PROGRAM 10 :Read the data set and perform scatter plot, Histogram and Bar plot using
Matplotlib in libraries

import pandas as pd

import matplotlib.pyplot as plt

data =
pd.read_csv('https://raw.githubusercontent.com/Adityarish/pythonlabExternal/refs/heads/main/datase
t.csv')

print(data.head())

plt.figure(figsize = (8,6))

plt.scatter(data['column1'], data['column2'], color="blue", alpha = 0.7, marker = "x")

plt.title("Scatter plot")

plt.xlabel("Column 1")

plt.ylabel("Column 2")

plt.grid(True)
plt.show()

plt.figure(figsize = (8,6))

plt.hist(data['column1'],bins = 20, color='green',edgecolor = "black")

plt.title("Histogram")

plt.xlabel('Column 3')

plt.ylabel('frequency')

plt.show()

plt.figure(figsize = (8,6))

data['column4'].value_counts().plot(kind = 'bar', color= 'orange',edgecolor="black")

plt.title("Bar Plot")

plt.xlabel("Category")

plt.ylabel("frequency")

plt.xticks(rotation = 45)

plt.show()

LAB PRO 11 Read the data set and perform scatter plot, Histogram and Bar plots using seaborn library

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

df =
pd.read_csv('https://raw.githubusercontent.com/Adityarish/pythonlabExternal/refs/heads/main/data.c
sv')

plt.figure(figsize = (8,6))

sns.scatterplot(data = df, x = "bill_length_mm", y = "bill_depth_mm" , hue = "species", marker="x")


plt.title("Scatter plot of Bill length vs Bill depth")

plt.grid(True)

plt.show()

plt.figure(figsize = (8,6))

sns.histplot(data =df, x="bill_length_mm", kde=True,bins = 20, color= "blue")

plt.title("Histogram of Bill length")

plt.show()

plt.figure(figsize = (8,6))

sns.barplot(data =df, x= "species", y = "body_mass_g",hue ="species", palette = "viridis")

plt.title("Bar Plot of Body mass of Species")

plt.show()

LAB PROGRAM 12 Read the data set and perform Box and whiskers plot using seaborn library

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

data =
pd.read_csv('https://raw.githubusercontent.com/Adityarish/pythonlabExternal/refs/heads/main/tips.cs
v')

plt.figure(figsize = (8,6))

sns.boxplot(x='day', y = 'total_bill', data = data, hue = 'day', palette='pastel')


plt.title("Box and whisker plot of total bill by day", fontsize = 14)

plt.xlabel('Day', fontsize =12)

plt.ylabel('Total Bill', fontsize = 12)

plt.show()

You might also like