DVP Manual
DVP Manual
The program assumes that the user will enter valid numerical test scores.
The program calculates the average using the provided test scores.
The best of two averages is calculated by considering two out of the three
test scores.
Input:
Output:
Program:
def calculate_average(test_scores):
return sum(test_scores) / len(test_scores)
# Input: Accept three test scores from the user
test_scores = []
for i in range(3):
score = float(input(f"Enter the score for Test {i + 1}: "))
test_scores.append(score)
# Calculate the average of all three test scores
average_all = calculate_average(test_scores)
# Calculate the best of two test averages
best_of_two = max(calculate_average(test_scores[:2]),
calculate_average(test_scores[1:]))
# Output the results
print(f"Average of all three tests: {average_all:.2f}")
print(f"Best of two test averages: {best_of_two:.2f}")
Output:
Enter the score for Test 1: 45
Enter the score for Test 2: 56
Enter the score for Test 3: 78
Average of all three tests: 59.67
Best of two test averages: 67.00
1b)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
Constraints:
Input:
Output:
12321 is a palindrome.
Digit 1 occurs 2 time(s) in the number.
Digit 2 occurs 2 time(s) in the number.
Digit 3 occurs 2 time(s) in the number.
Input:
Output:
Output:
Enter a number: 123321
123321 is a palindrome.
Digit 1 occurs 2 time(s) in the number.
Digit 2 occurs 2 time(s) in the number.
Digit 3 occurs 2 time(s) in the number.
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.
Constraints:
Input:
Output:
Input:
Output:
Input:
Output:
Output:
Enter a positive integer N: 10
The 10-th Fibonacci number is: 34
2b)Develop a python program to
convert binary to decimal, octal to
hexadecimal using functions.
Constraints:
The program handles invalid input and provides error messages for
incorrect binary or octal numbers.
Input:
Output:
Input:
Output:
Program:
def binary_to_decimal(binary_str):
try:
decimal_value = int(binary_str, 2)
return decimal_value
except ValueError:
return "Invalid binary input."
# Function to convert octal to hexadecimal
def octal_to_hexadecimal(octal_str):
try:
decimal_value = int(octal_str, 8)
hexadecimal_value = hex(decimal_value)
return hexadecimal_value
except ValueError:
return "Invalid octal input."
# Input: Accept user input for binary and octal numbers
binary_input = input("Enter a binary number: ")
octal_input = input("Enter an octal number: ")
# Convert binary to decimal
decimal_result = binary_to_decimal(binary_input)
print(f"Decimal value of {binary_input} is: {decimal_result}")
# Convert octal to hexadecimal
hexadecimal_result = octal_to_hexadecimal(octal_input)
print(f"Hexadecimal value of {octal_input} is: {hexadecimal_result}")
Output:
Enter a binary number: 0101
Enter an octal number: 567
Decimal value of 0101 is: 5
Hexadecimal value of 567 is: 0x177
3a)Write a Python program that accepts a sentence and
find the number of words, digits, uppercase letters and
lowercase letters.
def analyze_sentence(sentence):
# Initialize counters
word_count = len(sentence.split())
digit_count = 0
uppercase_count = 0
lowercase_count = 0
# Iterate through each character in the sentence
for char in sentence:
if char.isalpha():
if char.islower():
lowercase_count += 1
elif char.isupper():
uppercase_count += 1
elif char.isdigit():
digit_count += 1
# Display the results
print("Number of words:", word_count)
print("Number of digits:", digit_count)
print("Number of uppercase letters:", uppercase_count)
print("Number of lowercase letters:", lowercase_count)
Output:
Enter a sentence: Hello How are you doing? @123
Number of words: 6
Number of digits: 3
Number of uppercase letters: 2
Number of lowercase letters: 17
Program:
def get_cosine(vec1, vec2):
# Find the common words (intersection) between the two vectors
intersection = set(vec1.keys()) & set(vec2.keys())
Output:
The cosine similarity between 'This is a foo bar sentence.' and 'This sentence is
similar to a foo bar sentence.' is 0.86.
Bars:
Axis:
The axis provides a reference for the values associated with each bar. In a
horizontal bar plot, the bars extend along the y-axis, and in a vertical bar plot,
the bars extend along the x-axis.
Categories:
Each bar is associated with a specific category or group, and these categories
are usually labeled on the axis.
Bars are drawn vertically, extending along the x-axis. This type is suitable when
comparing categories along a common baseline.
Bars are drawn horizontally, extending along the y-axis. This type is effective
when labels for categories are long or when comparing data across different
groups.
Comparison of Data:
Bar plots are ideal for representing categorical data, where each bar represents a
distinct category or group. This makes them suitable for displaying counts,
frequencies, or percentages associated with each category. Clarity and
Simplicity:
Bar plots are simple to understand and visually intuitive. They communicate
information in a clear and straightforward manner, making them accessible to a
wide audience.
Effective Communication:
Trend Identification:
Trends and patterns in the data become apparent through the visual
representation of bars. For example, it's easy to identify which category has the
highest or lowest value.
Bar plots can be used to compare data across multiple groups or subcategories.
Grouped bar plots or stacked bar plots are common variations used for this
purpose.
Frequency Distribution:
Bar plots are frequently used to display the frequency distribution of categorical
data. This is particularly useful in fields such as statistics, market research, and
social sciences. In summary, bar plots serve as effective tools for visualizing
and communicating data in a way that is accessible and meaningful. Their
simplicity, clarity, and ability to convey comparative information make them
valuable in various fields, from scientific research to business analytics.
Program:
plt.bar(categories, data)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
Output:
Program:
import numpy as np
plt.ylabel("Humidity (%)")
plt.grid(True)
plt.tight_layout()
plt.show()
5a) Write a Python program to Demonstrate how to
Draw a Histogram Plot using Matplotlib
What is a Histogram:
Identifying Patterns: Histograms can reveal patterns and trends in the data, such
as modes, clusters, or outliers. Comparison: Useful for comparing different
datasets or understanding changes in a dataset over time.
Data Preparation: Collect the dataset that you want to analyze. Choose the
Number of Bins:
Decide on the number of bins (intervals) that the data range will be divided into.
This influences the granularity of the histogram.
Plotting:
Use a plotting library (e.g., Matplotlib in Python) to create a histogram. Plot the
data on the x-axis and the frequency (or density) on the y-axis.
Customize:
Adjust parameters like color, transparency, bin edges, and labels to enhance
visualization. Add axis labels and a title for clarity.
Interpretation:
Analyze the histogram to understand the data distribution. Look for patterns,
peaks, skewness, or any other characteristics that provide insights into the
dataset.
Key Components of a Histogram:
Bins: Intervals along the x-axis that represent ranges of data values.
Frequency: Number of data points falling into each bin.
Axis Labels: Descriptions for the x and y axes.
Title: A title that provides context for the histogram.
Bars: Rectangles whose heights represent the frequency of data within
each bin.
Program:
import numpy as np
data = np.random.randn(1000)
# Create histogram
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram Plot')
plt.show()
Output:
# Add legend
plt.legend()
A pie chart is a circular statistical graphic that is divided into slices to illustrate
numerical proportions. Each slice represents a proportion of the whole, and the
size of each slice corresponds to the quantity it represents. Why Use a Pie
Chart:
Visualizing Proportions:
Pie charts are effective for visually representing the distribution of parts
within a whole.
Comparisons: Easily compare the relative sizes of different categories or
components.
Simple Representation: Provide a clear and simple way to communicate
percentages or proportions.
Data Preparation:
Plotting:
Use a plotting library (e.g., Matplotlib in Python) to create a pie chart. Use the
plt.pie() function, providing values, labels, and additional parameters.
Customization:
Customize the pie chart with colors, labels, explosion, shadow, and other
aesthetic options. Add a title using plt.title() for clarity.
Program:
# Example data
categories = ['Category A', 'Category B', 'Category C']
values = [30, 40, 30]
# Add a title
plt.title('Simple Pie Chart')
Variation 1:
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y1 = 2 * x + 3
y2 = -0.5 * x + 5
# Adding annotations
plt.annotate('Intersection', xy=(5, 3),
xytext=(6, 8),
arrowprops=dict(facecolor='black',
shrink=0.05),
fontsize=10, color='purple')
-sns.set_style(): Sets the aesthetic style of the plots. -sns.set_context(): Sets the
context parameters for the plots. -sns.set_palette(): Sets the color palette for the
plots. -sns.color_palette(): Generates color palettes. -sns.set() : Sets the aesthetic
parameters in one step. -sns.despine(): Removes the top and right spines from
plots. -sns.set_theme(): Sets the visual theme for Seaborn.
These functions allow you to create plots with different visual styles, color
schemes, and overall appearances, making it easier to customize your
visualizations according to your preferences or the requirements of your
analysis.
Program:
# Summary statistics
print(iris.describe())
plt.figure(figsize=(10, 6))
sns.boxplot(x="species", y="sepal_width",
data=iris)
plt.title('Sepal Width Distribution by Species')
plt.show()
plt.figure(figsize=(10, 6))
sns.boxplot(x="species", y="petal_length", data=iris)
plt.title('Petal Length Distribution by Species')
plt.show()
plt.figure(figsize=(10, 6))
sns.boxplot(x="species", y="petal_width", data=iris)
plt.title('Petal Width Distribution by Species')
plt.show()
# Correlation heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(iris.corr(), annot=True,
cmap='coolwarm', linewidths=0.5)
plt.title('Correlation Heatmap of Iris Dataset')
plt.show()
Output:
# Create a figure
p = figure(title="Bokeh Line Graph with Annotations and Legends",
x_axis_label="X-axis",
y_axis_label="Y-axis")
p.add_layout(annotation1)
p.add_layout(annotation2)
Output:
Variation 2: 3D Line Plot
In [2]:
import matplotlib.pyplot as plt
import numpy as np
Output:
'Phoenix'],
df = pd.DataFrame(data)
projection='natural earth')
fig.show()
Output: