Data Visualization with Python BCS358D
Course Code: BCS358D
Credits: 01
CIE Marks: 50
SEE Marks: 50
Total Marks: 100
Exam Hours: 03
Teaching Hours/Weeks: [L:T:P:S] 0:0:2:0
1.a) Write a python program to find the best of two test average marks out of three test’s marks accepted
from the user.
m1 = int(input("Enter marks for test1 : "))
m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))
if m1 <= m2 and m1 <= m3:
avgMarks = (m2 + m3) / 2
elif m2 <= m1 and m2 <= m3:
avgMarks = (m1 + m3) / 2
elif m3 <= m1 and m2 <= m2:
avgMarks = (m1 + m2) / 2
print("Average of best two test marks out of three test’s marks is", avgMarks)
Enter marks for test1 : 54
Enter marks for test2 : 76
Enter marks for test3 : 34
Average of best two test marks out of three test’s marks is 65.0
1.b) Develop a Python program to check whether a given number is palindrome or not and also count the
number of occurrences of each digit in the input number.
val = int(input("Enter a value : "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i), "appears", str_val.count(str(i)), "times")
OUTPUT:
Enter a value : 121
Palindrome
1 appears 2 times
2 appears 1 times
Enter a value : 123
Not Palindrome
1 appears 1 times
2 appears 1 times
3 appears 1 times
2.a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value for N
(where N >0) as input and pass this value to the function. Display suitable error message if the condition
for input value is not followed.
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n - 1) + fn(n - 2)
num = int(input("Enter a number : "))
if num > 0:
print("fn(", num, ") = ", fn(num), sep="")
else:
print("Error in input")
OUTPUT:
Enter a number : 5
fn(5) = 3
Enter a number : -1
Error in input
2.b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
def bin2Dec(val):
rev = val[::-1]
dec = 0
i = 0
for dig in rev:
dec += int(dig) * 2 ** i
i += 1
return dec
def oct2Hex(val):
rev = val[::-1]
dec = 0
i = 0
for dig in rev:
dec += int(dig) * 8 ** i
i += 1
list = []
while dec != 0:
list.append(dec % 16)
dec = dec // 16
nl = []
for elem in list[::-1]:
if elem <= 9:
nl.append(str(elem))
else:
nl.append(chr(ord('A') + (elem - 10)))
hex = "".join(nl)
return hex
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
OUTPUT:
Enter a binary number : 10111001
185
Enter a octal number : 675
1BD
3.a) Write a Python program that accepts a sentence and find the number of words, digits, uppercase letters and lowercase letters.
sentence = input("Enter a sentence : ")
wordList = sentence.split(" ")
print("This sentence has", len(wordList), "words")
digCnt = upCnt = loCnt = 0
for ch in sentence:
if '0' <= ch <= '9':
digCnt += 1
elif 'A' <= ch <= 'Z':
upCnt += 1
elif 'a' <= ch <= 'z':
loCnt += 1
print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt, "lower case letters")
OUTPUT:
Enter a sentence : Welcome 2 VtuCode
This sentence has 3 words
This sentence has 0 digits 1 upper case letters 0 lower case letters
This sentence has 0 digits 1 upper case letters 1 lower case letters
This sentence has 0 digits 1 upper case letters 2 lower case letters
This sentence has 0 digits 1 upper case letters 3 lower case letters
This sentence has 0 digits 1 upper case letters 4 lower case letters
This sentence has 0 digits 1 upper case letters 5 lower case letters
This sentence has 0 digits 1 upper case letters 6 lower case letters
This sentence has 0 digits 1 upper case letters 6 lower case letters
This sentence has 1 digits 1 upper case letters 6 lower case letters
This sentence has 1 digits 1 upper case letters 6 lower case letters
This sentence has 1 digits 2 upper case letters 6 lower case letters
This sentence has 1 digits 2 upper case letters 7 lower case letters
This sentence has 1 digits 2 upper case letters 8 lower case letters
This sentence has 1 digits 3 upper case letters 8 lower case letters
This sentence has 1 digits 3 upper case letters 9 lower case letters
This sentence has 1 digits 3 upper case letters 10 lower case letters
This sentence has 1 digits 3 upper case letters 11 lower case letters
3.b) Write a Python program to find the string similarity between two given strings.
str1 = input("Enter String 1:\n")
str2 = input("Enter String 2:\n")
if len(str2) < len(str1):
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt / long)
OUTPUT:
Enter String 1:
Welcome to vtucode
Enter String 2:
Welcome to vtucode
Similarity between two said strings:
1.0
Enter String 1:
Welcome to vtucode
Enter String 2:
author vtucode
Similarity between two said strings:
0.1111111111111111
4.a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
#before exuting this program you have to install matpilotlib package...
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 2, 1]
plt.bar(x, y, color='green')
plt.title('Bar Plot Example')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
OUTPUT:
4.b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x, y)
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
OUTPUT:
5.a) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(100, 10, 1000)
plt.hist(data, bins=20, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram of Data')
plt.grid(True)
plt.show()
OUTPUT:
5.b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels, autopct="%1.1f%%")
plt.title("Pie Chart")
plt.show()
OUTPUT:
6.a) Write a Python program to illustrate Linear Plotting using Matplotlib.
# Import the necessary libraries
import matplotlib.pyplot as plt
import numpy as np
X = np.array([2, 4, 6, 8, 10])
Y = X * 2
plt.plot(X, Y)
plt.xlabel("X-axis Label")
plt.ylabel("Y-axis Label")
plt.title("This is the title of of the plot")
plt.show()
OUTPUT:
6.b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, color='blue', linestyle='-', linewidth=2)
plt.title('Line Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
OUTPUT:
7. Write a Python program which explains uses of customizing seaborn plots with Aesthetic functions.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.scatterplot(x="total_bill", y="tip", data=tips)
sns.set_style("whitegrid")
sns.set_palette("Set2")
sns.despine()
plt.show()
OUTPUT:
8. Write a Python program to explain working with bokeh line graph using Annotations and Legends.
a) Write a Python program for plotting different types of plots using Bokeh.
from bokeh.plotting import figure, show
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
p = figure(title="Interactive line graph", x_axis_label='x', y_axis_label='y')
p.line(x, y, legend_label="Line", line_width=2)
p.annular_wedge(x=5, y=5, inner_radius=0.2, outer_radius=0.4, start_angle=45, end_angle=135, line_color="red", fill_color="red")
show(p)
OUTPUT:
9. Write a Python program to draw 3D Plots using Plotly Libraries.
# Import necessary libraries
import plotly.graph_objects as go
import numpy as np
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
z = np.random.randn(100, 100)
fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z, mode='markers')])
fig.update_layout(title='3D Scatter Plot', scene=dict(xaxis_title='X Axis', yaxis_title='Y Axis', zaxis_title='Z Axis'))
fig.show()
OUTPUT:
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()
OUTPUT:
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()
OUTPUT: