Bcs358d DVP Lab
Bcs358d DVP Lab
also count the number of occurrences of each digit in the input number.
1a) Write a Python program to find the best of two test average marks out of three test 2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program that accepts a
marks accepted by the user. val = int(input("Enter a value : ")) value for N (where N >0) as input and pass this value to the function. Display a suitable
error message if the condition for input value is not followed.
str_val = str(val)
def fn(n):
m1 = int(input("Enter marks for test1 : ")) if str_val == str_val[::-1]: if n == 1:
m2 = int(input("Enter marks for test2 : ")) print("Palindrome") return 0
elif n == 2:
m3 = int(input("Enter marks for test3 : ")) else: return 1
else:
if m1 <= m2 and m1 <= m3: print("Not Palindrome")
return fn(n-1) + fn(n-2)
avgMarks = (m2+m3)/2 for i in range(10):
num = int(input("Enter a number : "))
elif m2 <= m1 and m2 <= m3: if str_val.count(str(i)) > 0:
avgMarks = (m1+m3)/2 print(str(i),"appears", str_val.count(str(i)), "times"); if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
elif m3 <= m1 and m2 <= m2: else:
print("Error in input")
avgMarks = (m1+m2)/2
print("Average of best two test marks out of three test’s marks is", avgMarks); OUTPUT: OUTPUT:
Enter a value: 1234234 Enter a number : 5
OUTPUT Not Palindrome fn(5) = 3
Enter marks for test1: 45 1 appears 1 times Enter a number : -5
Enter marks for test2: 39 2 appears 2 times Error in input
Enter marks for test3: 48 3 appears 2 times
Average of best two test marks out of three test’s marks is 46.5 4 appears 2 times
Enter a value: 12321
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 1 times
2b) Develop a python program to convert binary to decimal, octal to hexadecimal using PROGRAM -3
functions.
3a) Write a Python program that accepts a sentence and find the number of words, digits, 3b) Write a Python program to find the string similarity between two given strings.
uppercase letters, and lowercase letters.
def bin_to_dec(): str1 = input("Enter String 1 \n")
bin=int(input("Enter a binary number : ")) sentence = input("Enter a sentence: ") str2 = input("Enter String 2 \n")
dec=0 words = digits = upper = lower = 0
i=0 if len(str2) < len(str1):
while bin!=0: # Splitting the sentence using split() method , by default split is by spaces
# Return value - list of strings short = len(str2)
dec+=(bin%10)*(2**i)
i+=1 long = len(str1)
bin//=10 split_sentence = sentence.split()
print("The result of split() on input sentence is : \n"+str(split_sentence)+"\n") else:
print("Decimal Equivalent is : ",dec)
short = len(str1)
words = len(split_sentence )
long = len(str2)
def oct_to_hex():
oct=int(input("Enter an octal number : ")) for c in sentence: matchCnt = 0
dec=0 if c.isdigit():
digits = digits + 1 for i in range(short):
i=0
while oct!=0: elif c.isupper(): if str1[i] == str2[i]:
dec+=(oct%10)*(8**i) upper = upper + 1
elif c.islower(): matchCnt += 1
i+=1
oct//=10 lower = lower + 1 print("Similarity between two said strings:")
hex ="" print(matchCnt/long)
print ("No of Words: ", words)
while dec!=0:
rem=dec%16 print ("No of Digits: ", digits)
print ("No of Uppercase letters: ", upper)
if rem<10: OUTPUT:
hex+=str(rem) print ("No of Lowercase letters: ", lower)
else: Enter String 1
hex+= chr(ord('A')+rem-10)
OUTPUT: Python Exercises
dec//=16
hex=hex[::-1] Enter a sentence: Rama went to Devaraja market to pick 2 kgs of vegetable Enter String 2
print("Hexadecimal Equivalent is : ", hex)
Python Exercises
The result of split() on input sentence is :
Similarity between two said strings:
print("BINARY TO DECIMAL CONVERSION") ['Rama', 'went', 'to', 'Devaraja', 'market', 'to', 'pick', '2', 'kgs', 'of', 'vegetable']
1.0
bin_to_dec() No of Words: 11
print("\n\nOCTAL TO HEXADECIMAL CONVERSION") Enter String 1
oct_to_hex() No of Digits: 1
Python Exercises
No of Uppercase letters: 2 Enter String 2
No of Lowercase letters: 42 Python Exercise
Similarity between two said strings: 0.9375
Matplotlib generates HTML and JavaScript code that can be embedded into web pages. This allows you to 2. Cars_BarPlot
create interactive visualizations that can be easily shared on the web.
Matplotlib is a popular Python library for creating static, animated, and interactive visualizations Car Sales
in a variety of formats. It is widely used for producing high-quality plots and charts in scientific Plotly Audi 419
computing, data analysis, and machine learning. Matplotlib provides a range of functions for BMW 263
Plotly is a versatile Python library for creating interactive and publication-quality plots and
creating different types of plots, including line plots, scatter plots, bar plots, histograms, and Mercedes 330
dashboards. It supports a wide range of chart types. Plotly excels at creating interactive plots.
more. Different visualizations plots are as follows: Honda 760
Users can zoom, pan, hover over data points for additional information, and perform other
Scatter plots: Scatter plots are particularly useful when exploring the relationship between two interactive actions directly within the plot. Its ability to create web-based dashboards makes it a
continuous variables. They excel at revealing patterns, trends, and correlations between data powerful tool for building data-driven applications. 3. tips.csv
points. These visualizations are adept at identifying outliers, showcasing them as points deviating
from the main cluster. By providing a clear picture of the distribution of data points along two total_bill tip sex smoker day time size
axes, scatter plots aid in understanding the spread and density of values. Moreover, they are Dataset used 1 16.99 1.01 Female No Sun Dinner 2
valuable for comparing different datasets, recognizing similarities or differences. 2 10.34 1.66 Male No Sun Dinner 3
1. Cars.csv 3 21.01 3.5 Male No Sun Dinner 3
Histogram: A histogram is a graphical representation of the distribution of a dataset, typically
Model Price Age Mfg_Month Mfg_Year KM Fuel_Type HP Met_Color Automatic cc Doors 4 23.68 3.31 Male No Sun Dinner 2
used for continuous or discrete data. It provides a way to visualize the frequency or count of data Id
5 24.59 3.61 Female No Sun Dinner 4
points within specific intervals or bins. In a histogram, the data is divided into contiguous, non- TOYOTA
overlapping intervals, and the height of each bar in the chart represents the frequency or count of Corolla 2.0 D4D
data points falling within that interval. 1 HATCHB 13500 23 10 2002 46986 Diesel 90 1 0 2000 3 4. Rainfall_data
To create a histogram, you divide the range of the data into bins or intervals and then TERRA 2/3-
Doors Specific Relative
count the number of data points that fall into each bin. The resulting bar chart, with the bars Year Month Day Humidity Humidity Temperature Precipitation
representing these counts, provides a visual summary of the data's distribution. TOYOTA
2000 1 1 8.06 48.25 23.93 0
Corolla 2.0 D4D
2 HATCHB 13750 23 10 2002 72937 Diesel 90 1 0 2000 3 2000 2 1 8.73 50.81 25.83 0.11
Bar chart: A bar chart is a graphical representation of data in which rectangular bars are used to
TERRA 2/3- 2000 3 1 8.48 42.88 26.68 0.01
represent the values of different categories. Each bar's length is proportional to the value it Doors 2000 4 1 13.79 55.69 22.49 0.02
represents. Bar charts are effective for comparing discrete categories or groups and are
?TOYOTA 2000 5 1 17.4 70.88 19.07 271.14
particularly useful for showing the distribution of categorical data.
Corolla 2.0 D4D
3 HATCHB 13950 24 9 2002 41711 Diesel 90 1 0 2000 3
Pie chart: Pie charts are a type of data visualization that is commonly used to represent the TERRA 2/3-
proportions of different parts of a whole. The primary purpose of a pie chart is to show the Doors
relationship of parts to a whole and to illustrate how each part contributes to the total. TOYOTA
Corolla 2.0 D4D
4 HATCHB 14950 26 7 2002 48000 Diesel 90 0 0 2000 3
Seaborn TERRA 2/3-
Doors
Seaborn is a statistical data visualization library built on top of Matplotlib in Python. It provides
an interface for creating informative and attractive statistical graphics. Seaborn comes with TOYOTA
Corolla 2.0 D4D
several built-in themes and color palettes to make it easy to create aesthetically pleasing 5 13750 30 3 2002 38500 Diesel 90 0 0 2000 3
HATCHB SOL
visualizations. It is particularly useful for exploring complex datasets and understanding 2/3-Doors
relationships between variables.
Bokeh
Bokeh is a Python interactive visualization library that targets modern web browsers for
presentation. It allows you to create interactive, web-ready visualizations in Python. Bokeh
4a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib 4. b) Write a Python program to Demonstrate how to draw a Scatter Plot using Matplotlib 5. a) Write a Python program to Demonstrate how to draw a Histogram using Matplotlib
# import the necessary libraries # import the necessary libraries
# Import the necessary modules import pandas as pd # Pandas library for data
import matplotlib.pyplot as plt import numpy as np frames import pandas as pd
import pandas as pd import matplotlib.pyplot as plt
# Initialize the lists for X and Y # numpy library to do numerical operations
data = pd.read_csv("Car_Barplot.csv") # Importing data.
df = pd.DataFrame(data) cars_data = pd.read_csv("Toyota.csv") import numpy as np
X = list(df.iloc[:, 0]) import matplotlib.pyplot as plt
# Create scatter plot using two variables, Age and Price.
Y = list(df.iloc[:, 1]) plt.scatter(cars_data['Age'],cars_data['Price'],c='blue')
# To set the title cars_data = pd.read_csv("cars.csv")
# Plot the data using bar() method plt.title('Scatter plot of Price vs Age of the plt.title('Histogram for distance travelled in KiloMeter')
plt.bar(X, Y, color='g') Cars') # To set the x and y axis labels.
plt.title("Used Car Sales") plt.xlabel('Age (months)') plt.hist(cars_data ['KM'], color='green', edgecolor='white', bins=5)
plt.xlabel("Car") plt.ylabel('Price (Euros)') plt.xlabel('Kilometer')
plt.ylabel("Number Sold") # To show the scatter plot plt.ylabel('Frequency')
# Show the plot plt.show() plt.show()
plt.show()
5. b) Write a Python program to Demonstrate how to draw a Piechart using Matplotlib 6a. Write a Python program to illustrate Linear Plotting using Matplotlib 6b) Write a Python program to illustrate liner plotting with line formatting using
Matplotlib
import matplotlib.pyplot as plt
# Import libraries import matplotlib.pyplot as plt
def formatted_linear_plot():
import matplotlib.pyplot as plt def linear_plot():
# Sample data
import pandas as pd # Sample data
x = [1, 2, 3, 4, 5, 6]
x = [1, 2, 3, 4, 5]
y = [3, 7, 9, 11, 14, 18]
# Creating dataset y = [3, 7, 9, 11, 14]
plt.plot(x, y, marker='o', linestyle='-', color='b', label='Linear Function: y = 2x')
cars_data = pd.read_csv("Car_BarPlot.csv") # Plotting the data
cars = cars_data["Car"] plt.plot(x, y, label='Linear Function: y = 2x')
# Adding labels and title
data = cars_data["Sales"]
plt.xlabel('X-axis')
# Adding labels and title plt.ylabel('Y-axis')
# Creating plot plt.xlabel('X-axis') plt.title('Formatted Linear Plot Example')
fig = plt.figure(figsize =(10, 7)) plt.ylabel('Y-axis')
plt.pie(data, labels = cars) plt.title('Linear Plot Example') plt.legend()
plt.show()
# Call the function to generate the plot # Call the function to generate the formatted linear plot
linear_plot() formatted_linear_plot()
Output
7a) Write a Python program which explains uses of customizing seaborn plots with Output 8 a) Write a Python program to explain working with bokeh line graph using Annotations
Aesthetic functions. and Legends.
from bokeh.plotting import figure, output_file, show
import seaborn as sns from bokeh.models import Label
import matplotlib.pyplot as plt
# Sample data
# Load a sample dataset
x = [1, 2, 3, 4, 5]
tips = sns.load_dataset("tips")
y = [2, 4, 6, 8, 10]
plt.show()
# Add legend
p.legend.location = "top_left"
p.legend.click_policy = "hide"
Output 8 b) Write a Python program for plotting different types of plots using Bokeh # Combine plots into a grid
import pandas as pd plots = gridplot([[hist_plot, bar_plot], [scatter_plot]])
import numpy as np
from bokeh.plotting import figure, output_file, show # Show the combined plot
from bokeh.layouts import gridplot show(plots)
# Histogram
hist, edges = np.histogram(tips['total_bill'], bins=8)
hist_plot = figure(title="Histogram of Total Bill", x_axis_label='Total Bill',
y_axis_label='Frequency')
hist_plot.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="purple",
line_color="white")
# Bar Plot
day_categories = tips['day'].unique()
average_total_bill = tips.groupby('day')['total_bill'].mean()
bar_plot = figure(title="Average Total Bill per Day", x_axis_label='Day', y_axis_label='Average
Total Bill', x_range=day_categories)
bar_plot.vbar(x=day_categories, top=average_total_bill, width=0.5, color="orange")
# Scatter Plot
scatter_plot = figure(title="Scatter Plot of Total Bill vs Tip", x_axis_label='Total Bill',
y_axis_label='Tip')
scatter_plot.scatter(x='total_bill', y='tip', size=8, color="green", alpha=0.6, source=tips)
9a) Write a Python program to draw 3D Plots using Plotly Libraries. Output 10a). Write a Python program to draw Time Series using Plotly Libraries
# Load the tips dataset # Load the dataset (replace 'your_dataset.csv' with the actual file path)
tips = pd.read_csv("tips.csv") data = pd.read_csv("Rainfall_data.csv")
# Create a 3D scatter plot # Combine Year, Month, and Day columns to create a datetime column
fig = go.Figure() data['Date'] = pd.to_datetime(data[['Year', 'Month', 'Day']])
import plotly.express as px
# Sample data for demonstration
data = {
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Houston'],
'Lat': [40.7128, 37.7749, 34.0522, 41.8781, 29.7604],
'Lon': [-74.0060, -122.4194, -118.2437, -87.6298, -95.3698],
'Population': [8175133, 870887, 3971883, 2716000, 2328000]
}
# Create a map
fig = px.scatter_geo(data, lat='Lat', lon='Lon', text='City', size='Population',
projection='natural earth', title='Population of Cities')
fig.update_traces(textposition='top center')
fig.show()
Output