0% found this document useful (0 votes)
10 views52 pages

Ds Rec Program

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

Ds Rec Program

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PROGRAM:

import numpy as np
empty_array = [Link]((3, 3))
print("Empty Array:")
print(empty_array)
full_array = [Link]((3, 3), 7)
print("\nFull Array:")
print(full_array)
zeros_array = [Link]((3, 3))
print("\nArray of Zeros:")
print(zeros_array)
ones_array = [Link]((3, 3))
print("\nArray of Ones:")
print(ones_array)

OUTPUT:
Empty Array:
[[2.4568938e-316 0.0000000e+000 6.9101386e-310]
[6.9101386e-310 6.9101386e-310 6.9101386e-310]
[6.9101386e-310 6.9101386e-310 6.9101386e-310]]
Full Array:
[[7 7 7]
[7 7 7]
[7 7 7]]
Array of Zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Array of Ones:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
data = [Link]([
[1, 2, 3],
[4, 'a', 6],
[7, 8, 9],
[10, 11, 'b']
], dtype=object)
print("Original Array:")
print(data)
def remove_non_numeric_rows(array):
numeric_rows = []
for row in array:
try:
numeric_row = [float(element) for element in row]
numeric_rows.append(numeric_row)
except ValueError:
continue
return [Link](numeric_rows)
cleaned_data = remove_non_numeric_rows(data)
print("\nArray After Removing Rows with Non-Numeric Values:")
print(cleaned_data)

OUTPUT:
Original Array:
[[1 2 3]
[4 'a' 6]
[7 8 9]
[10 11 'b']]
Array After Removing Rows with Non-Numeric Values:
[[1. 2. 3.]
[7. 8. 9.]]

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
array1 = [Link]([1, 2, 3, 4, 5])
array2 = [Link]([5, 4, 3, 2, 1])
print("Array 1:", array1)
print("Array 2:", array2)
addition = array1 + array2
print("\nElement-wise Addition:", addition)
subtraction = array1 - array2
print("Element-wise Subtraction:", subtraction)
multiplication = array1 * array2
print("Element-wise Multiplication:", multiplication)
division = array1 / array2
print("Element-wise Division:", division)
dot_product = [Link](array1, array2)
print("Dot Product:", dot_product)
array_2d = [Link]([[1, 2], [3, 4]])
transpose = array_2d.T
print("\nOriginal 2D Array:\n", array_2d)
print("Transpose of 2D Array:\n", transpose)
sum_array = [Link](array1)
print("\nSum of elements in Array 1:", sum_array)
max_value = [Link](array1)
min_value = [Link](array1)
print("Maximum value in Array 1:", max_value)
print("Minimum value in Array 1:", min_value)
mean_value = [Link](array1)
std_deviation = [Link](array1)
print("Mean of Array 1:", mean_value)
print("Standard Deviation of Array 1:", std_deviation)
concatenated = [Link]((array1, array2))
print("\nConcatenated Array:", concatenated)

[Link]:XXX NAME:XXX
first_three_rows = [Link](3)
print("\nFirst Three Rows:")
print(first_three_rows)

OUTPUT:
Array 1: [1 2 3 4 5]
Array 2: [5 4 3 2 1]
Element-wise Addition: [6 6 6 6 6]
Element-wise Subtraction: [-4 -2 0 2 4]
Element-wise Multiplication: [5 8 9 8 5]
Element-wise Division: [0.2 0.5 1. 2. 5. ]
Dot Product: 35
Original 2D Array:
[[1 2]
[3 4]]
Transpose of 2D Array:
[[1 3]
[2 4]]
Sum of elements in Array 1: 15
Maximum value in Array 1: 5
Minimum value in Array 1: 1
Mean of Array 1: 3.0
Standard Deviation of Array 1: 1.4142135623730951
Concatenated Array: [1 2 3 4 5 5 4 3 2 1]

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
original_array = [Link]([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print("Original Array:")
print(original_array)
bordered_array = [Link](original_array, pad_width=1, mode='constant', constant_values=0)
print("\nArray with Border:")
print(bordered_array)

OUTPUT:
Original array:
[[2. 3.]
[3. 4.] ]
Border array
[[0. 0. 0. 0.
0. 2. 3. 0.
0. 3. 4. 0.
0. 0. 0. 0.

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
matrix1 = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
addition = matrix1 + matrix2
print("\nMatrix Addition:")
print(addition)
subtraction = matrix1 - matrix2
print("\nMatrix Subtraction:")
print(subtraction)
elementwise_multiplication = matrix1 * matrix2
print("\nElement-wise Multiplication:")
print(elementwise_multiplication)
dot_product = [Link](matrix1, matrix2)
print("\nMatrix Multiplication (Dot Product):")
print(dot_product)
transpose = matrix1.T
print("\nTranspose of Matrix 1:")
print(transpose)
determinant = [Link](matrix1)
print("\nDeterminant of Matrix 1:")
print(determinant)
try:
inverse = [Link](matrix1)
print("\nInverse of Matrix 1:")
print(inverse)
except [Link]:
print("\nMatrix 1 is not invertible.")

[Link]:XXX NAME:XXX
eigenvalues, eigenvectors = [Link](matrix1)
print("\nEigenvalues of Matrix 1:")
print(eigenvalues)
print("Eigenvectors of Matrix 1:")
print(eigenvectors)
trace = [Link](matrix1)
print("\nTrace of Matrix 1:")
print(trace)

OUTPUT:
Matrix 1:
[[1 2 3]
[4 5 6]
[7 8 9]]
Matrix 2:
[[9 8 7]
[6 5 4]
[3 2 1]]
Matrix Addition:
[[10 10 10]
[10 10 10]
[10 10 10]]
Matrix Subtraction:
[[-8 -6 -4]
[-2 0 2]
[ 4 6 8]]
Element-wise Multiplication:
[[ 9 16 21]
[24 25 24]
[21 16 9]]
Matrix Multiplication (Dot Product):

[Link]:XXX NAME:XXX
[[ 30 24 18]
[ 84 69 54]
[138 114 90]]
Transpose of Matrix 1:
[[1 4 7]
[2 5 8]
[3 6 9]]
Determinant of Matrix 1:
0.0
Matrix 1 is not invertible.
Eigenvalues of Matrix 1:
[ 1.6116844e+01 -1.1168439e+00 -1.3036777e-15]
Eigenvectors of Matrix 1:
[[-0.23197069 -0.78583024 0.40824829]
[-0.52532209 -0.08675134 -0.81649658]
[-0.8186735 0.61232756 0.40824829]]
Trace of Matrix 1:
15

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
scores = [Link]([
[85, 78, 92],
[88, 74, 81],
[90, 88, 84],
[72, 65, 70],
[95, 91, 89]])
print("Student Scores:")
print(scores)
student_averages = [Link](scores, axis=1)
print("\nAverage Score of Each Student:")
print(student_averages)
subject_averages = [Link](scores, axis=0)
print("\nAverage Score for Each Subject:")
print(subject_averages)
highest_scores = [Link](scores, axis=0)
print("\nHighest Score in Each Subject:")
print(highest_scores)
highest_avg_student = [Link](student_averages) + 1 # Adding 1 for student index
print("\nStudent with the Highest Average Score: Student", highest_avg_student)
lowest_scores = [Link](scores, axis=0)
print("\nLowest Score in Each Subject:")
print(lowest_scores)
overall_average = [Link](scores)
overall_max = [Link](scores)
overall_min = [Link](scores)
print("\nOverall Performance Metrics:")
print("Overall Average Score:", overall_average)
print("Overall Highest Score:", overall_max)
print("Overall Lowest Score:", overall_min)
passing_threshold = 50

[Link]:XXX NAME:XXX
pass_status = scores >= passing_threshold
print("\nPass/Fail Status (Pass=True, Fail=False):")
print(pass_status)

OUTPUT:
Student Performance Matrix:
[[85 90 88]
[78 85 80]
[92 91 94]
[70 75 72]]
Comparison of Student 1 and Student 2:
Student 1 + Student 2 scores: [163 175 168]
Student 1 - Student 2 scores: [ 7 5 8]
Total and Average Scores for Each Student:
Student 1 - Total Score: 263, Average Score: 87.66666666666667
Student 2 - Total Score: 243, Average Score: 81.0
Student 3 - Total Score: 277, Average Score: 92.33333333333333
Student 4 - Total Score: 217, Average Score: 72.33333333333333
Highest score in the matrix: 94
Lowest score in the matrix: 70
Average Scores for Each Subject:
Math - Average Score: 81.25
Science - Average Score: 85.25
English - Average Score: 83.5
Transposed Performance Matrix (Subjects as rows, Students as columns):
[[85 78 92 70]
[90 85 91 75]
[88 80 94 72]]
Total Scores for Each Subject:
Math - Total Score: 325
Science - Total Score: 330
English - Total Score: 334

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
print("\nEnter the column names:")
column_names = [input(f"Column {i+1}: ") for i in range(columns)]
data = []
print("\nEnter the data for each row:")
for i in range(rows):
row_data = []
print(f"Row {i+1}:")
for j in range(columns):
value = input(f" Enter value for {column_names[j]}: ")
row_data.append(value)
[Link](row_data)
print("\nEnter custom index labels for the rows:")
index_labels = [input(f"Index label for row {i+1}: ") for i in range(rows)]
df = [Link](data, columns=column_names, index=index_labels)
print("\nCreated DataFrame:")
print(df)

OUTPUT:
Enter the number of rows: 2
Enter the number of columns: 2
Enter the column names:
Column 1: NAME
Column 2: AGE
Enter the data for each row:
Row 1:
Enter value for NAME: VISHNU
Enter value for AGE: 20
Row 2:

[Link]:XXX NAME:XXX
Enter value for NAME: KANISHKA
Enter value for AGE: 19
Enter custom index labels for the rows:
Index label for row 1: A
Index label for row 2: B

Created DataFrame:
NAME AGE
A VISHNU 20
B KANISHKA 19

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["New York", "Los Angeles", "Chicago"]
}
index_labels = ["Person1", "Person2", "Person3"]
df = [Link](data, index=index_labels)
print(df)

OUTPUT:
Created DataFrame:
Name Age City
Person1 Alice 25 New York
Person2 Bob 30 Los Angeles
Person3 Charlie 35 Chicago

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
data = {
"Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
"Age": [25, 30, 35, 40, 45],
"City": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
}
df = [Link](data)
print("Full DataFrame:")
print(df)
first_three_rows = [Link](3)
print("\nFirst Three Rows:")
print(first_three_rows)

OUTPUT:
Full DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
4 Eve 45 Phoenix
First Three Rows:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
data = {
"Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
"Age": [25, 30, 35, 40, 45],
"City": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
}
df = [Link](data)
print(df)
average_age = df["Age"].mean()
print("Average Age:", average_age)

OUTPUT:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
4 Eve 45 Phoenix

Average Age: 35.0

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
import [Link] as plt
data={"Date":["2024-01-01","2024-01-02","2024-01-03","2024-01-04","2024-01-
05"],"Sales":[200,220,250,270,300]}
df=[Link](data)
df['Date']=pd.to_datetime(df['Date'])
df.set_index('Date',inplace=True)
print("DataFrame with Date as index:")
print(df)
[Link](figsize=(10,6))
[Link]([Link],df['Sales'],marker='o',linestyle='-',color='b',label='Sales')
[Link]("Sales Over Time")
[Link]("Date")
[Link]("Sales")
[Link](rotation=45)
[Link](True)
[Link]()
plt.tight_layout()
[Link]()

[Link]:XXX NAME:XXX
OUTPUT:
DataFrame with Date as index:
Sales
Date
2024-01-01 200
2024-01-02 220
2024-01-03 250
2024-01-04 270
2024-01-05 300

[Link]:XXX NAME:XXX
PROGRAM:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]("Simple Plot Example")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import [Link] as plt
import pandas as pd
data = {
"Date": ["2016-10-03", "2016-10-04", "2016-10-05", "2016-10-06", "2016-10-07"],
"Stock Price": [112.34, 113.45, 111.89, 114.23, 115.67]
}
df = [Link](data)
df['Date'] = pd.to_datetime(df['Date'])
[Link](figsize=(10, 6))
[Link](df['Date'], df['Stock Price'], marker='o', linestyle='-', color='b', label='Stock Price')
[Link]("Stock Prices from Oct 3, 2016 to Oct 7, 2016")
[Link]("Date")
[Link]("Stock Price (USD)")
[Link](True)
[Link]()
plt.tight_layout()
[Link]()

[Link]:XXX NAME:XXX
OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
import [Link] as plt
data = {
"Month": [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
"Sales": [
1500, 1800, 2000, 2500, 2200, 2400,
2100, 2300, 2800, 3000, 3100, 3200
]
}
df = [Link](data)
print("Monthly Sales Data for 2023:")
print(df)
total_sales = df['Sales'].sum()
print(f"\nTotal Sales for the Year 2023: ${total_sales}")
average_sales = df['Sales'].mean()
print(f"Average Monthly Sales for 2023: ${average_sales:.2f}")
highest_sales_month = df[df['Sales'] == df['Sales'].max()]["Month"].values[0]
highest_sales = df['Sales'].max()
print(f"Highest Sales in {highest_sales_month}: ${highest_sales}")
lowest_sales_month = df[df['Sales'] == df['Sales'].min()]["Month"].values[0]
lowest_sales = df['Sales'].min()
print(f"Lowest Sales in {lowest_sales_month}: ${lowest_sales}")
[Link](figsize=(10, 6))
[Link](df['Month'], df['Sales'], marker='o', color='b', linestyle='-', label='Monthly Sales')
[Link]("Monthly Sales Analysis for the Year 2023")
[Link]("Month")
[Link]("Sales (USD)")
[Link](rotation=45

[Link]:XXX NAME:XXX
[Link](True)
[Link]()
plt.tight_layout()
[Link]()

OUTPUT:
Monthly Sales Data for 2023:
Month Sales
0 January 1500
1 February 1800
2 March 2000
3 April 2500
4 May 2200
5 June 2400
6 July 2100
7 August 2300
8 September 2800
9 October 3000
10 November 3100
11 December 3200

Total Sales for the Year 2023: $28900


Average Monthly Sales for 2023: $2408.33
Highest Sales in December: $3200
Lowest Sales in January: $1500

[Link]:XXX NAME:XXX
[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
import [Link] as plt
data = [3, 7, 3, 5, 6, 2, 7, 8, 9, 10, 6, 7, 8, 6, 9]
df = [Link](data, columns=['Values'])
frequency = df['Values'].value_counts().sort_index()
cumulative_frequency = [Link]()
print("Value Frequency Distribution:")
print(frequency)
print("\nCumulative Frequency:")
print(cumulative_frequency)
[Link](cumulative_frequency.index, cumulative_frequency.values, marker='o', linestyle='-',
color='b', label='Cumulative Frequency')
[Link]("Cumulative Frequency Distribution")
[Link]("Value")
[Link]("Cumulative Frequency")
[Link](True)
[Link]()
plt.tight_layout()
[Link](

[Link]:XXX NAME:XXX
OUTPUT:
Value Frequency Distribution:
Values
2 1
3 2
5 1
6 3
7 3
8 2
9 2
10 1
Cumulative Frequency:
Values
2 1
3 3
5 4
6 7
7 10
8 12
9 14
10 15

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
import [Link] as plt
data = [45, 34, 50, 75, 22, 56, 63, 70, 49, 33,8, 14, 39, 86, 52, 92, 88, 70, 56, 50,57, 45,
42,12,39]
df = [Link](data)
bins = [0, 20, 40, 60, 80, 100]
frequency = [Link](df, bins=bins, right=False).value_counts().sort_index()
cumulative_frequency = [Link]()
print("Class Intervals and Frequency Distribution:")
print(frequency)
print("\nLess Than Cumulative Frequency:")
print(cumulative_frequency)
[Link](figsize=(10, 6))
[Link](bins[1:], cumulative_frequency, marker='o', linestyle='-', color='b', label='Less Than
Cumulative Frequency')
[Link]("Less Than Cumulative Frequency Distribution of Runs Scored")
[Link]("Runs Scored (Less Than)")
[Link]("Cumulative Frequency")
[Link](True)
[Link]()
plt.tight_layout()
[Link]()

[Link]:XXX NAME:XXX
OUTPUT:
Class Intervals and Frequency Distribution:
[0, 20) 3
[20, 40) 5
[40, 60) 10
[60, 80) 4
[80, 100) 3
Name: count, dtype: int64

Less Than Cumulative Frequency:


[0, 20) 3
[20, 40) 8
[40, 60) 18
[60, 80) 22
[80, 100) 25
Name: count, dtype: int64

[Link]:XXX NAME:XXX
PROGRAM:
def calculate_sum_and_average():
n = int(input("Enter the number of integers: "))
numbers = [int(input(f"Enter integer {i+1}: ")) for i in range(n)]
total_sum = sum(numbers)
average = total_sum / n if n > 0 else 0 # Handle division by zero
print(f"The sum of the {n} integers is: {total_sum}")
print(f"The average of the {n} integers is: {average}")
calculate_sum_and_average()

OUTPUT:
Enter the number of integers: 3
Enter integer 1: 5
Enter integer 2: 10
Enter integer 3: 15
The sum of the entered numbers is: 30
The average of the entered numbers is: 10.00

[Link]:XXX NAME:XXX
PROGRAM:
def calculate_sum_and_average():
n=int(input("Enter the number of integers: "))
total_sum=0
for i in range(n):
num=int(input(f"Enter integer {i+1}: "))
total_sum+=num
average=total_sum/n
print(f"The sum of the {n} integers is: {total_sum}")
print(f"The average of the {n} integers is: {average}")
calculate_sum_and_average()

OUTPUT:
Enter the number of integers: 3
Enter integer 1: 5
Enter integer 2: 10
Enter integer 3: 15
The sum of the entered numbers is: 30
The average of the entered numbers is: 10.00

[Link]:XXX NAME:XXX
PROGRAM:
def calculate_expenses():
n=int(input("Enter the number of days: "))
total_expense=0
for i in range(n):
expense=float(input(f"Enter expense for day {i+1}: "))
total_expense+=expense
average_expense=total_expense/n
print(f"\nTotal expenses for {n} days: {total_expense}")
print(f"Average daily expense: {average_expense}")
calculate_expenses()

OUTPUT:
Enter the number of days: 5
Enter expense for day 1: 80
Enter expense for day 2: 120
Enter expense for day 3: 90
Enter expense for day 4: 110
Enter expense for day 5: 70

Total expenses for 5 days: 470.0


Average daily expense: 94.0

[Link]:XXX NAME:XXX
PROGRAM:
import math
def calculate_variance_and_std():
n=int(input("Enter the number of elements: "))
numbers=[]
for i in range(n):
num=float(input(f"Enter number {i+1}: "))
[Link](num)
mean=sum(numbers)/n
variance=sum((x-mean)**2 for x in numbers)/n
std_deviation=[Link](variance)
print(f"\nVariance: {variance}")
print(f"Standard Deviation: {std_deviation}")
calculate_variance_and_std()

OUTPUT:
Enter the number of elements: 5
Enter number 1: 10
Enter number 2: 12
Enter number 3: 23
Enter number 4: 23
Enter number 5: 16

Variance: 29.360000000000003
Standard Deviation: 5.418486873657627

[Link]:XXX NAME:XXX
PROGRAM:
import math
def calculate_sample_variance(numbers):
n=len(numbers)
mean=sum(numbers)/n
variance=sum((x-mean)**2 for x in numbers)/(n-1)
return variance
def variance_for_samples():
num_samples=int(input("Enter the number of samples: "))
for i in range(num_samples):
n=int(input(f"Enter the number of elements for sample {i+1}: "))
sample=[]
for j in range(n):
num=float(input(f"Enter element {j+1}: "))
[Link](num)
variance=calculate_sample_variance(sample)
print(f"Variance for sample {i+1}: {variance}")
variance_for_samples()

OUTPUT:
Enter the number of samples: 2
Enter the number of elements for sample 1: 5
Enter element 1: 12
Enter element 2: 15
Enter element 3: 14
Enter element 4: 17
Enter element 5: 13
Variance for sample 1: 3.7

[Link]:XXX NAME:XXX
Enter the number of elements for sample 2: 4
Enter element 1: 30
Enter element 2: 35
Enter element 3: 40
Enter element 4: 45
Variance for sample 2: 41.666666666666664

[Link]:XXX NAME:XXX
PROGRAM:
import math
def calculate_population_variance(numbers):
n=len(numbers)
mean=sum(numbers)/n
variance=sum((x-mean)**2 for x in numbers)/n
return variance
def variance_statistics():
n=int(input("Enter the number of elements: "))
numbers=[]
for i in range(n):
num=float(input(f"Enter element {i+1}: "))
[Link](num)
variance=calculate_population_variance(numbers)
print(f"\nPopulation Variance: {variance}")
variance_statistics()

OUTPUT:
Enter the number of elements: 5
Enter element 1: 10
Enter element 2: 15
Enter element 3: 20
Enter element 4: 25
Enter element 5: 30

Population Variance: 50.0

[Link]:XXX NAME:XXX
PROGRAM:
import math
def calculate_mean(temperatures):
return sum(temperatures)/len(temperatures)
def calculate_variance(temperatures,mean):
return sum((temp-mean)**2 for temp in temperatures)/len(temperatures)
def calculate_standard_deviation(variance):
return [Link](variance)
def analyze_temperature_variation():
days=int(input("Enter the number of days for temperature data: "))
temperatures=[]
for i in range(days):
temp=float(input(f"Enter temperature for day {i+1}: "))
[Link](temp)
mean_temp=calculate_mean(temperatures)
variance_temp=calculate_variance(temperatures,mean_temp)
std_deviation=calculate_standard_deviation(variance_temp)
print(f"\nMean Temperature: {mean_temp:.2f}")
print(f"Temperature Variance: {variance_temp:.2f}")
print(f"Standard Deviation of Temperature: {std_deviation:.2f}")
analyze_temperature_variation()

[Link]:XXX NAME:XXX
OUTPUT:
Enter the number of days for temperature data: 7
Enter temperature for day 1: 20
Enter temperature for day 2: 22
Enter temperature for day 3: 19
Enter temperature for day 4: 21
Enter temperature for day 5: 23
Enter temperature for day 6: 20
Enter temperature for day 7: 18

Mean Temperature: 20.43


Temperature Variance: 2.53
Standard Deviation of Temperature: 1.59

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
import [Link] as plt
def create_normal_curve():
mean=0
std_dev=1
num_samples=1000
data=[Link](mean,std_dev,num_samples)
[Link](data,bins=30,density=True,alpha=0.6,color='b')
xmin,xmax=[Link]()
x=[Link](xmin,xmax,100)
p=(1/(std_dev*[Link](2*[Link])))*[Link](-0.5*((x-mean)/std_dev)**2)
[Link](x,p,'k',linewidth=2)
[Link]('Normal Distribution Curve')
[Link]('Data')
[Link]('Density')
[Link]()
create_normal_curve()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
import [Link] as plt
def simulate_exam_scores():
mean_score=75
std_dev=10
num_students=200
scores=[Link](mean_score,std_dev,num_students)
scores=[Link](scores,0,100)
[Link](figsize=(10,6))
[Link](scores,bins=15,density=True,alpha=0.7,color='skyblue',edgecolor='black')
xmin,xmax=[Link]()
x=[Link](xmin,xmax,100)
p=(1/(std_dev*[Link](2*[Link])))*[Link](-0.5*((x-mean_score)/std_dev)**2)
[Link](x,p,'r',linewidth=2)
[Link]('Distribution of Exam Scores')
[Link]('Exam Scores')
[Link]('Density')
[Link](True)
[Link]()
simulate_exam_scores()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import [Link] as plt
import numpy as np
def create_scatter_plot():
x = [Link](1,10,50)
y = 2*x + [Link](5,10,50)
[Link](figsize=(8,6))
[Link](x,y,color='b',marker='o',label='Data points')
[Link]('Scatter Plot: Hours Studied vs Marks Obtained')
[Link]('Hours Studied')
[Link]('Marks Obtained')
[Link](True)
[Link]()
[Link]()
create_scatter_plot()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import [Link] as plt
import numpy as np
def create_scatter_plot():
x = [Link](1,10,50)
y = 2*x + [Link](5,10,50)
[Link](x,y,color='green',marker='x',label='Data points')
[Link]('Scatter Plot: Hours Studied vs Marks Obtained')
[Link]('Hours Studied')
[Link]('Marks Obtained')
[Link](True)
[Link]()
[Link]()
create_scatter_plot()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import [Link] as plt
import numpy as np
def create_colored_scatter_plot():
x = [Link](1,20,50)
y = 2*x + [Link](5,10,50)
colors = y
[Link](x,y,c=colors,cmap='viridis',marker='o')
[Link](label='Marks Obtained')
[Link]('Scatter Plot: Hours Studied vs Marks Obtained (Colored by Marks)')
[Link]('Hours Studied')
[Link]('Marks Obtained')
[Link](True)
[Link]()
create_colored_scatter_plot()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import [Link] as plt
import numpy as np
def visualize_correlation():
[Link](42)
study_hours = [Link](1,11,50)
exam_scores = 5*study_hours + [Link](5,15,50)
[Link](figsize=(8,6))
[Link](study_hours,exam_scores,color='blue',marker='o',label='Data points')
[Link]('Correlation Between Study Hours and Exam Scores')
[Link]('Study Hours')
[Link]('Exam Scores')
[Link](True)
[Link]()
[Link]()
visualize_correlation()

OUTPUT:

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
def calculate_correlation():
study_hours = [Link]([1,2,3,4,5,6,7,8,9,10])
exam_scores = [Link]([35,42,47,50,53,57,60,65,70,75])
correlation_matrix = [Link](study_hours,exam_scores)
correlation_coefficient = correlation_matrix[0,1]
print(f"The correlation coefficient between Study Hours and Exam Scores
{correlation_coefficient:.2f}")
calculate_correlation()

OUTPUT:

The correlation coefficient between Study Hours and Exam Scores is : 1.00

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
def pearson_correlation(x,y):
if len(x) != len(y):
raise ValueError("Both variables must have the same number of data points.")
mean_x = [Link](x)
mean_y = [Link](y)
numerator = [Link]((x - mean_x) * (y - mean_y))
denominator = [Link]([Link]((x - mean_x)**2) * [Link]((y - mean_y)**2))
r = numerator / denominator
return r
study_hours = [Link]([1,2,3,4,5,6,7,8,9,10])
exam_scores = [Link]([35,42,47,50,53,57,60,65,70,75])
correlation_coefficient = pearson_correlation(study_hours,exam_scores)
print(f"The Pearson correlation coefficient between Study Hours and Exam Scores is:
{correlation_coefficient:.2f}")

OUTPUT:

The Pearson correlation coefficient between Study Hours and Exam Scores is : 1.00

[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from [Link] import mean_squared_error, r2_score
study_hours = [Link]([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)
exam_scores = [Link]([35,42,47,50,53,57,60,65,70,75])
X_train,X_test,y_train,y_test =
train_test_split(study_hours,exam_scores,test_size=0.2,random_state=42)
model = LinearRegression()
[Link](X_train,y_train)
y_pred = [Link](X_test)
print(f"Intercept: {model.intercept_}")
print(f"Slope: {model.coef_[0]}")
mse = mean_squared_error(y_test,y_pred)
r2 = r2_score(y_test,y_pred)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R-squared: {r2:.2f}")
[Link](figsize=(8,6))
[Link](study_hours,exam_scores,color='blue',label='Actual Data')
[Link](study_hours,[Link](study_hours),color='red',label='Regression Line')
[Link]('Simple Linear Regression: Study Hours vs Exam Scores')
[Link]('Study Hours')
[Link]('Exam Scores')
[Link]()
[Link](True)
[Link]()

[Link]:XXX NAME:XXX
OUTPUT
Intercept: 32.30172413793103
Slope: 4.172413793103448
Mean Squared Error: 0.93
R-squared: 1.00

[Link]:XXX NAME:XXX
PROGRAM:
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score
data = [Link]({
"Pregnancies": [6,1,8,1,0,5,3,10,2,8],
"Glucose": [148,85,183,89,137,116,78,115,197,125],
"BloodPressure": [72,66,64,66,40,74,50,0,70,96],
"SkinThickness": [35,29,0,23,35,0,32,0,45,0],
"Insulin": [0,0,0,94,168,0,88,0,543,0],
"BMI": [33.6,26.6,23.3,28.1,43.1,25.6,31.0,35.3,30.5,32.0],
"DiabetesPedigreeFunction":
[0.627,0.351,0.672,0.167,2.288,0.201,0.248,0.134,0.158,0.232],
"Age": [50,31,32,21,33,30,26,29,53,54],
"Outcome": [1,0,1,0,1,0,0,0,1,1]
})
X = [Link](columns=['Glucose'])
y = data['Glucose']
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=42)
model = LinearRegression()
[Link](X_train,y_train)
y_pred = [Link](X_test)
mse = mean_squared_error(y_test,y_pred)
r2 = r2_score(y_test,y_pred)
accuracy = r2 * 100
print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"R-squared (R²): {r2:.2f}")
print(f"Model Accuracy: {accuracy:.2f}%")

[Link]:XXX NAME:XXX
comparison = [Link]({"Actual": y_test.values,"Predicted": y_pred})
print("\nComparison of Actual vs Predicted Values:")
print(comparison)
[Link](figsize=(10,5))
[Link](range(len(y_test)),y_test,alpha=0.6,color='blue',label='Actual')
[Link](range(len(y_pred)),y_pred,alpha=0.6,color='red',label='Predicted')
[Link]('Actual vs Predicted Glucose Levels')
[Link]('Sample Index')
[Link]('Glucose Level')
[Link]()
[Link](True)
[Link]()
[Link](figsize=(8,6))
[Link](y_test,y_pred,color='purple',label='Predicted vs Actual')
[Link](y_test,y_test,'r--',label='Perfect Prediction')
[Link]('Scatter Plot of Actual vs Predicted Glucose Levels')
[Link]('Actual Glucose Levels')
[Link]('Predicted Glucose Levels')
[Link]()
[Link](True)
[Link]()

OUTPUT:
Mean Squared Error (MSE): 14126.01
R-squared (R²): -5.34
Model Accuracy: -533.58%
Comparison of Actual vs Predicted Values:
Actual Predicted
0 197 35.563060
1 85 209.754803
2 116 143.429792

[Link]:XXX NAME:XXX
[Link]:XXX NAME:XXX
PROGRAM:
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import classification_report, confusion_matrix,
ConfusionMatrixDisplay

X,y =
make_classification(n_samples=1000,n_features=10,n_informative=5,n_redundant=2,rando
m_state=42)
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=42)
model = LogisticRegression()
[Link](X_train,y_train)
y_pred = [Link](X_test)
report = classification_report(y_test,y_pred,output_dict=True)
print("Classification Report:")
print(classification_report(y_test,y_pred))

classes = list([Link]())[:-3]
metrics = ["precision","recall","f1-score"]
heatmap_data = [Link]([[report[cls][metric] for metric in metrics] for cls in classes])

[Link](figsize=(8,6))
[Link](heatmap_data,interpolation="nearest",cmap="Blues")
[Link]()
[Link](range(len(metrics)),metrics)
[Link](range(len(classes)),classes)
[Link]("Classification Report Heatmap")
[Link]("Metrics")
[Link]("Classes")

[Link]:XXX NAME:XXX
for i in range(len(classes)):
for j in range(len(metrics)):
[Link](j,i,f"{heatmap_data[i,j]:.2f}",ha="center",va="center",color="black")
[Link]()

conf_matrix = confusion_matrix(y_test,y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=conf_matrix,display_labels=[Link](y))
[Link](cmap="Blues",values_format="d")
[Link]("Confusion Matrix")
[Link]()

OUTPUT:
Classification Report:
precision recall f1-score support

0 0.82 0.85 0.84 158


1 0.83 0.79 0.81 142
accuracy 0.82 300
macro avg 0.82 0.82 0.82 300
weighted avg 0.82 0.82 0.82 300

[Link]:XXX NAME:XXX
[Link]:XXX NAME:XXX

You might also like