DV With Python - 3RD Sem
DV With Python - 3RD Sem
PROGRAM
print("Enter the three internals marks (> zero:")
m1 = int(input("Enter marks1:"))
m2 = int(input("Enter marks2:"))
m3 = int(input("Enter marks3:"))
print("Marks1:", m1)
print("Marks2:", m2)
print("Marks3:", m3)
small=m1
if small > m2:
small = m2
if small > m3:
small = m3
avg=(m1+m2+m3-small)/2;
print("Average of best two test out of three test is",avg)
OUTPUT
//Output 01
Enter the three internals marks:
Enter marks1:22
Enter marks2:24
Enter marks3:23
Marks1: 22
Marks2: 24
Marks3: 23
Average of best two test out of three test is 23.5
//Output 02
Enter the three internals marks:
Enter marks1:23
Enter marks2:19
Enter marks3:21
Marks1: 23
Marks2: 19
Marks3: 21
Average of best two test out of three test is 22.0
PROGRAM
rev = 0
num = int(input("Enter the number:"))
temp = num
n=str(temp)
while num > 0:
digit = num%10
rev = rev*10+digit
num //= 10
print("Given Number is", temp)
print("Reversed Number is", rev)
if temp == rev:
print(temp, "is a Palindrome")
else:
print(temp, "is not a Palindrome")
# Finding Number of Digits using built-in function
print("Number of Digits using Built-in Function: ", len(str(n)))
#Finding the occurrences of each digit
s={}
for i in n:
if i in s:
s[i]+=1
else:
s[i]=1
print("Number of occurrences of each digit in the input number are:")
print(s)
OUTPUT
//Output 01
Enter the number:1441
Given Number is 1441
Reversed Number is 1441
1441 is a Palindrome
Number of Digits using Built-in Function: 4
Number of occurrences of each digit in the input number are:
{'1': 2, '4': 2}
PROGRAM
def fibonacci(n):
if n <= 0:
print("Error: N must be greater than 0.")
return None
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
n = int(input("Enter a value for N: "))
result = fibonacci(n)
if result is not None:
print("The", n, "th term of the Fibonacci sequence is", result)
OUTPUT
//Output 01
Enter a value for N: 10
The 10 th term of the Fibonacci sequence is 34
//Output 02
Enter a value for N: 20
The 20 th term of the Fibonacci sequence is 4181
2 b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
PROGRAM
def binary_to_decimal(binary):
decimal = 0
power = 0
while binary > 0:
decimal += (binary % 10) * (2 ** power)
binary //= 10
power += 1
return decimal
def octal_to_hexadecimal(octal):
decimal = 0
power = 0
while octal > 0:
decimal += (octal % 10) * (8 ** power)
octal //= 10
power += 1
hexadecimal = ""
hex_digits = "0123456789ABCDEF"
while decimal > 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16
return hexadecimal
binary_number = int(input("Enter a binary number: "))
decimal_number = binary_to_decimal(binary_number)
print("Decimal:", decimal_number)
octal_number = int(input("Enter an octal number: "))
hexadecimal_number = octal_to_hexadecimal(octal_number)
print("Hexadecimal:", hexadecimal_number)
OUTPUT
//Output 01
Enter a binary number: 1111
Decimal: 15
Enter an octal number: 45
Hexadecimal: 25
//Output 02
Enter a binary number: 1001
Decimal: 9
Enter an octal number: 20
Hexadecimal: 10
3 a) Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters and lowercase letters.
PROGRAM
sentence = input("Enter a sentence: ")
word_count = len(sentence.split())
digit_count = 0
upper_count = 0
lower_count = 0
for char in sentence:
if char.isdigit():
digit_count += 1
elif char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
print("Number of words:", word_count)
print("Number of digits:", digit_count)
print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)
OUTPUT
//Output 01
Enter a sentence: Python Programming 21CSL46
Number of words: 3
Number of digits: 4
Number of uppercase letters: 5
Number of lowercase letters: 15
//Output 02
Enter a sentence: Python Programming Laboratory
Number of words: 3
Number of digits: 0
Number of uppercase letters: 3
Number of lowercase letters: 24
3 b) Write a Python program Sample Output:
to find the string similarity Original string:
between two given strings Python Exercises
Sample Output: Python Exercise
Original string: Similarity between two said
Python Exercises 0.967741935483871
Python Exercises
Similarity between two said
strings:
1.0
PROGRAM
import difflib
def string_similarity(str1, str2):
result = difflib.SequenceMatcher(a=str1.lower(), b=str2.lower())
return result.ratio()
str1 = 'Python Exercises' or str1 = input("Enter a sentence: ")
str2 = 'Python Exercises' or str2 = input("Enter a sentence: ")
print("Original string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))
str1 = 'Python Exercises' or str1 = input("Enter a sentence: ")
str2 = 'Python Exercise' or str2 = input("Enter a sentence: ")
print("\nOriginal string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))
OUTPUT
Original string:
Python Exercises
Python Exercises
Similarity between two said strings:
1.0
Original string:
Python Exercises
Python Exercise
Similarity between two said strings:
0.967741935483871
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
PROGRAM
import matplotlib.pyplot as plt
# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [10, 15, 7, 12]
# Create a bar plot
plt.bar(categories, values, color='green')
# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')
# Display the plot
plt.show()
\
4 b) Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.
PROGRAM
import matplotlib.pyplot as plt
# Sample data for the scatter plot
x = [1, 2, 3, 4, 5]
y = [10, 12, 5, 20, 7]
# Create a scatter plot
plt.scatter(x, y, label='Data Points', color='blue', marker='o')
# Add labels and a title
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('Scatter Plot Example')
# Add a legend
plt.legend()
# Show the plot
plt.show()
PROGRAM
import matplotlib.pyplot as plt
import numpy as np
# Generate random data for the histogram
data = np.random.randn(1000) # Sample 1000 data points from a normal distribution
# Create a histogram plot
plt.hist(data, bins=20, edgecolor='black', alpha=0.7)
# Add labels and a title
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram Plot Example')
# Show the plot
plt.show()
5 b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
PROGRAM
import matplotlib.pyplot as plt
# Sample data for the pie chart
labels = ['Category A', 'Category B', 'Category C', 'Category D']
sizes = [25, 40, 30, 35]
colors = ['gold', 'lightcoral', 'lightgreen', 'lightskyblue']
explode = (0.1, 0, 0, 0) # Explode the first slice (Category A)
# Create a pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
startangle=140)
# Add a title
plt.title('Pie Chart Example')
# Show the plot
plt.show()
PROGRAM
import matplotlib.pyplot as plt
# Sample data for the linear plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a linear plot
plt.plot(x, y, marker='o', linestyle='-')
# Add labels and a title
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('Linear Plot Example')
# Show the plot
plt.grid() # Add a grid for better readability
plt.show()
6 b) Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.
PROGRAM
import matplotlib.pyplot as plt
# Sample data for the linear plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a linear plot with line formatting
plt.plot(x, y, marker='o', color='blue', linestyle='--', linewidth=2, markersize=8, label='Data
Points')
# Add labels and a title
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('Linear Plot with Line Formatting')
# Add a legend
plt.legend()
# Show the plot
plt.grid()
7 a) Write a Python program which explains uses of customizing seaborn plots with
Aesthetic functions.
PROGRAM
import seaborn as sns
import matplotlib.pyplot as plt
# Load a sample dataset
tips = sns.load_dataset("tips")
# Set the style of the plot
sns.set(style="whitegrid")
# Create a customized bar plot
plt.figure(figsize=(8, 6))
sns.barplot(x="day", y="total_bill", data=tips, palette="Blues_d")
# Customize labels and titles
plt.xlabel("Day of the week", fontsize=12)
plt.ylabel("Total Bill ($)", fontsize=12)
plt.title("Total Bill Amounts by Day", fontsize=14)
# Show the plot
plt.show()
8 a) Write a Python program to explain working with bokeh line graph using Annotations
and Legends.
p.add_layout(legend)
# Show the plot
show(p)
8 b) Write a Python program for plotting different types of plots using Bokeh.
PROGRAM
import numpy as np
from bokeh.io import output_file
from bokeh.io import show
from bokeh.layouts import row, column
from bokeh.plotting import figure
# Create a new plot object.
fig = figure(plot_width=500, plot_height=300, title='Different Types of Plots')
# Add data to the plot.
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Add a line glyph to the plot.
fig.line(x, y, line_width=2, legend_label='Line Plot')
# Add a bar chart to the plot.
fig.vbar(x=x, top=y, legend_label='Bar Chart', width=0.5, bottom=0)
# Add a scatter plot to the plot.
fig.circle(x, y, size=10, color='red', legend_label='Scatter Plot')
# Customize the plot appearance.
fig.xaxis.axis_label = 'X Axis'
fig.yaxis.axis_label = 'Y Axis'
fig.legend.location = 'top_left'
# Show the plot.
show(fig)
10.a) Write a Python program to draw Time Series using Plotly Libraries.
import plotly.graph_objects as go
data = [
{'x': [1, 2, 3, 4, 5], 'y': [6, 7, 2, 4, 5]},
{'x': [6, 7, 8, 9, 10], 'y': [1, 3, 5, 7, 9]}
]
fig = go.Figure()
for i in range(len(data)):
fig.add_trace(go.Scatter(x=data[i]['x'], y=data[i]['y'], mode='lines'))
fig.update_layout(title='Time Series', xaxis_title='Time', yaxis_title='Value')
fig.show()
10.b) Write a Python program for creating Maps using Plotly Libraries.
import plotly.express as px
df = px.data.election()
geojson = px.data.election_geojson()
fig = px.choropleth(df, geojson=geojson, color="Bergeron",
locations="district", featureidkey="properties.district",
projection="mercator"
)
fig.update_geos(fitbounds="locations", visible=True)
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()