Python
Python
REGULATIONS- 2021
NAME:
REGNO:
DEPT:
YEAR/SEM:
INDEX
14 K-Means Clustering
Aim
To create a function that takes two numbers as input and returns their sum, difference, product,
and quotient.
Algorithm
o Compute sum = a + b
o Compute difference = a - b
o Compute product = a × b
o If b ≠ 0:
Compute quotient = a ÷ b
o Else:
if b != 0:
quotient = a / b
else:
quotient = "Undefined (division by zero)"
# Input
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
# Function call
sum_result, difference, product, quotient = calculate_operations(a, b)
# Output
print("Sum:", sum_result)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
Sample Input :
Enter first number: 10
Enter second number: 5
Sample Output :
Sum: 15.0
Difference: 5.0
Product: 50.0
Quotient: 2.0
Result :
To write a program that counts the number of vowels and consonants in a given string.
Algorithm
Program (Python)
defcount_vowels_consonants(text):
vowels = "aeiouAEIOU"
v_count = 0
c_count = 0
for ch in text:
if [Link](): # check if character is alphabet
if ch in vowels:
v_count += 1
else:
c_count += 1
# Input
text = input("Enter a string: ")
# Function call
vowels, consonants = count_vowels_consonants(text)
# Output
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
Input
Enter a string: Hello World
Output
Number of vowels: 3
Number of consonants: 7
Result
Thus, the program to count the number of vowels and consonants in a given string was successfully
implemented and executed.
Ex No.03 PRINT EVEN NUMBERS FROM A LIST
Date:
Aim
To write a program that prints all even numbers from a given list using a loop.
Algorithm
Program (Python)
# Function to print even numbers
defprint_even_numbers(lst):
print("Even numbers in the list are:")
for num in lst:
if num % 2 == 0:
print(num, end=" ")
# Input
lst = list(map(int, input("Enter list elements separated by space:
").split()))
# Function call
print_even_numbers(lst)
Input
Enter list elements separated by space: 1 2 3 4 5 6 7 8
Output
Even numbers in the list are:
2 4 6 8
Result
Thus, the program to print all even numbers from a list using a loop was successfully implemented
and executed.
Ex No.04 COUNT OCCURANCES OF AN ELEMENT IN A TUPLE
Date:
Aim
To write a program that counts the number of occurrences of a specific element in a given tuple.
Algorithm
Program (Python)
# Function to count occurrences
defcount_occurrences(tup, element):
count = 0
for item in tup:
if item == element:
count += 1
return count
# Input
tup = tuple(map(int, input("Enter tuple elements separated by space:
").split()))
element = int(input("Enter element to count: "))
# Function call
result = count_occurrences(tup, element)
# Output
print("Number of occurrences:", result)
Input
Enter tuple elements separated by space: 1 2 3 2 4 2 5
Enter element to count: 2
Output
Number of occurrences: 3
Result
Thus, the program to count the number of occurrences of a specific element in a tuple was
successfully implemented and executed.
To write a program that iterates through a dictionary and prints its keys and values separately.
Algorithm
Program (Python)
# Function to print keys and values
defprint_keys_values(d):
print("Keys:")
for key in [Link]():
print(key)
print("Values:")
for value in [Link]():
print(value)
# Input
n = int(input("Enter number of elements: "))
d = {}
for i in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
d[key] = value
# Function call
print_keys_values(d)
Input
Enter number of elements: 3
Enter key: a
Enter value: 10
Enter key: b
Enter value: 20
Enter key: c
Enter value: 30
Output
Keys:
a
b
c
Values:
10
20
30
Result
Thus, the program to iterate through a dictionary and print keys and values separately was
successfully implemented and executed.
To create a DataFrame from a dictionary and handle missing values in the DataFrame.
Algorithm
Program (Python)
import pandas as pd
# Creating DataFrame
df = [Link](data)
# Display DataFrame
print("Original DataFrame:")
print(df)
Output
Original DataFrame:
Name Age Marks
0 Alice 25.0 85.0
1 Bob NaN 90.0
2 Charlie 30.0 NaN
3 David 22.0 88.0
Missing Values:
Name Age Marks
0 False FalseFalse
1 False True False
2 False False True
3 False FalseFalse
Result
Thus, the DataFrame was successfully created from a dictionary and missing values were identified
and handled using appropriate methods.
To calculate basic statistics of a DataFrame column and add a new column based on existing
columns.
Algorithm
Program (Python)
import pandas as pd
# Create DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Marks1": [80, 75, 90],
"Marks2": [85, 70, 95]
}
df = [Link](data)
# Basic statistics
print("Mean Marks1:", df["Marks1"].mean())
print("Sum Marks1:", df["Marks1"].sum())
print("Max Marks1:", df["Marks1"].max())
print("Min Marks1:", df["Marks1"].min())
print("\nUpdatedDataFrame:")
print(df)
Input
(No user input required)
Output
Mean Marks1: 81.67
Sum Marks1: 245
Max Marks1: 90
Min Marks1: 75
Updated DataFrame:
Name Marks1 Marks2 Total
0 Alice 80 85 165
1 Bob 75 70 145
2 Charlie 90 95 185
Result
Thus, basic statistics were calculated and a new column was successfully added.
Aim
To create a 2D array and perform basic operations, and calculate mean and standard deviation.
Algorithm
Program (Python)
import numpy as np
# Create 2D array
arr = [Link]([[1, 2, 3],
[4, 5, 6]])
print("Array:\n", arr)
# Operations
print("Sum:", [Link]())
print("Transpose:\n", arr.T)
# Statistics
print("Mean:", [Link]())
print("Standard Deviation:", [Link]())
Input
Output
Array:
[[1 2 3]
[4 5 6]]
Sum: 21
Transpose:
[[1 4]
[2 5]
[3 6]]
Mean: 3.5
Standard Deviation: 1.7078
Result
Thus, the 2D array operations and statistical measures were successfully performed.
Aim
To load a CSV file, display first few records, and find total number of entries.
Algorithm
Program (Python)
import pandas as pd
# Total entries
print("\nTotal number of entries:", len(df))
Input
Name,Age,Marks
Alice,20,85
Bob,21,78
Charlie,19,90
David,22,88
Eva,20,76
Output
First 5 rows:
Name Age Marks
0 Alice 20 85
1 Bob 21 78
2 Charlie 19 90
3 David 22 88
4 Eva 20 76
Result
Thus, the CSV file was successfully loaded, explored, and total entries were identified.
Aim
Algorithm
Program (Python)
from [Link] import factorial
import numpy as np
print("Factorial:", factorial(num))
print("Square Root:", [Link](num))
print("Exponential:", [Link](num))
Input
Enter a number: 5
Output
Factorial: 120.0
Square Root: 2.236
Exponential: 148.41
Result
Algorithm
Program (Python)
from [Link] import minimize
# Function
deffunc(x):
return x**2 + 3*x + 2
Input
Output
Minimum value: -0.25
At x = [-1.5]
Result
Algorithm
Program (Python)
import numpy as np
from sklearn.linear_model import LinearRegression
model = LinearRegression()
[Link](X, Y)
print("Slope:", model.coef_[0])
print("Intercept:", model.intercept_)
Input
Output
Slope: 2.0
Intercept: 0.0
Result
Thus, linear regression was successfully performed.
Aim
Algorithm
Program (Python)
from [Link] import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=3)
[Link](X, Y)
prediction = [Link]([[2.5]])
print("Predicted class:", prediction)
Input
Output
Predicted class: [0]
Result
Thus, classification using KNN was successfully performed.
Aim
Algorithm
Program (Python)
import numpy as np
from [Link] import KMeans
kmeans = KMeans(n_clusters=2)
[Link](X)
Input
Output
Cluster labels: [0 0 1 1]
Result
Algorithm
Program (Python)
import pandas as pd
moving_avg = [Link](window=3).mean()
Input
Output
Moving Average:
0 NaN
1 NaN
2 20.0
3 30.0
4 40.0
dtype: float64
Result
Algorithm
1. Start the program.
2. Import required libraries (Pandas, NumPy, Matplotlib, Scikit-learn).
3. Load the dataset using Pandas.
4. Explore the dataset using head(), info(), and describe().
5. Clean the data:
o Handle missing values using fillna() or dropna().
6. Apply Linear Regression:
o Select independent and dependent variables.
o Train the model and predict values.
7. Perform Clustering:
o Select relevant features.
o Apply K-Means clustering.
8. Visualize data:
o Use line plots, bar charts, and histograms.
9. Display results.
10. Stop the program.
Program (Python)
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from [Link] import KMeans
model = LinearRegression()
[Link](X, y)
predictions = [Link](X)
# Step 5: Clustering
features = df[["Population", "Services_Used"]]
kmeans = KMeans(n_clusters=3)
df["Cluster"] = kmeans.fit_predict(features)
# Step 6: Visualization
# Line Plot
[Link](df["Population"], df["Services_Used"])
[Link]("Population vs Services Used")
[Link]("Population")
[Link]("Services Used")
[Link]()
# Bar Chart
[Link]("Region")["Services_Used"].mean().plot(kind='bar')
[Link]("Average Services Used by Region")
[Link]()
# Histogram
[Link](df["Services_Used"])
[Link]("Distribution of Services Used")
[Link]()
Sample Output
First 5 rows:
Region Population Services_Used
0 Urban 10000 50
1 Rural 8000 30
2 Semi-Urban 9000 40
3 Urban 12000 60
4 Rural 7000 25
Result
Thus, the E-Governance dataset was successfully loaded, cleaned, analyzed using linear regression
and clustering, and visualized using graphs.
Algorithm
1. Start the program.
2. Import required libraries (Matplotlib, Seaborn).
3. Prepare sample data.
4. Plot a line chart using Matplotlib.
5. Plot a bar chart using Seaborn.
6. Display the plots.
7. Stop the program.
Program (Python)
import [Link] as plt
import seaborn as sns
# Sample Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
# Line Chart (Matplotlib)
[Link](x, y)
[Link]("Line Chart")
[Link]("X values")
[Link]("Y values")
[Link]()
Sample Input
(No input required)
Sample Output
Line chart showing trend of values
Bar chart showing comparison of values
Result
Thus, line and bar charts were successfully created.
Algorithm
1. Install Django and Django REST Framework.
2. Create a Django project and app.
3. Configure database (SQLite/MySQL).
4. Create models and migrate database.
5. Implement user registration and login.
6. Perform CRUD operations using models.
7. Create API endpoint using REST framework.
8. Run server and test application.
class Service([Link]):
name = [Link](max_length=100)
description = [Link]()
defcreate_service(request):
[Link](name="Test", description="Demo")
Step 5: Authentication
from [Link] import User
[Link].create_user(username="admin", password="1234")
@api_view(['GET'])
defget_services(request):
services = list([Link]())
return Response(services)
Sample Input
Username: admin
Password: 1234
Sample Output
User successfully registered and logged in
API returns JSON data:
[
{"name": "Test", "description": "Demo"}
]
Result
Thus, a Django application with authentication, database, CRUD operations, and API was successfully
implemented.
Algorithm
1. Install Flask.
2. Create a Flask application.
3. Define routes.
4. Run server.
5. Display output in browser.
Program (Python)
from flask import Flask
app = Flask(__name__)
@[Link]('/')
def home():
return "Welcome to Flask Web App"
@[Link]('/about')
def about():
return "About Page"
if __name__ == '__main__':
[Link](debug=True)
Sample Input
(Open browser and visit URL)
[Link]
Sample Output
Welcome to Flask Web App
Result
Thus, a basic web application using Flask framework was successfully created and executed.
Algorithm
1. Start the project.
2. Design front-end using HTML/CSS forms for citizen registration and service requests.
3. Set up back-end using Flask/Django.
4. Implement user authentication (login/register).
5. Create database models for citizens and services.
6. Perform CRUD operations (Create, Read, Update, Delete).
7. Generate data visualizations using Matplotlib/Seaborn.
8. Create REST API endpoints for data access.
9. Run the application locally.
10. Test all functionalities.
11. Stop the program.
app = Flask(__name__)
# Database connection
defconnect_db():
return [Link]("[Link]")
@[Link]('/')
def home():
return render_template("[Link]")
@[Link]('/register', methods=['POST'])
def register():
name = [Link]['name']
email = [Link]['email']
region = [Link]['region']
service = [Link]['service']
conn = connect_db()
cursor = [Link]()
[Link]("INSERT INTO citizens (name, email, region, service) VALUES
(?, ?, ?, ?)",
(name, email, region, service))
[Link]()
[Link]()
if __name__ == '__main__':
[Link](debug=True)
conn = [Link]("[Link]")
data = [Link]("SELECT region, COUNT(*) FROM citizens GROUP BY
region").fetchall()
[Link](regions, counts)
[Link]("Services Used per Region")
[Link]("Region")
[Link]("Count")
[Link]()
@[Link]('/api/citizens', methods=['GET'])
defget_citizens():
conn = connect_db()
cursor = [Link]()
[Link]("SELECT * FROM citizens")
data = [Link]()
[Link]()
return jsonify(data)
Open browser:
[Link]
Sample Input
Name: John
Email: john@[Link]
Region: Urban
Service: Water Supply
Sample Output
Registration Successful
API Output:
[
[1, "John", "john@[Link]", "Urban", "Water Supply"]
]
Graph Output:
Result
Thus, the E-Governance application was successfully developed with front-end forms, back-end
processing, database integration, visualization, API creation, and deployment.
Algorithm
1. Start the program.
2. Load dataset using Pandas.
3. Check missing values using isnull().
4. Check duplicates using duplicated().
5. Validate data types and ranges.
6. Display inconsistencies.
7. Stop the program.
Program (Python)
import pandas as pd
data = {
"Name": ["Alice", "Bob", None, "David"],
"Age": [25, 30, 30, -5]
}
df = [Link](data)
Sample Input
(No input required)
Sample Output
Missing Values:
Name Age
0 False False
1 False False
2 True False
3 False False
Duplicates:
0 False
1 False
2 False
3 False
Invalid Ages:
Name Age
3 David -5
Result
Thus, dataset completeness and consistency were analyzed successfully.
Algorithm
1. Identify system components (login, forms, database).
2. Simulate uptime logs.
3. Calculate uptime percentage.
4. Analyze logs for errors.
5. Display metrics.
Program (Python)
logs = ["UP", "UP", "DOWN", "UP", "UP"]
Sample Input
Logs: UP, UP, DOWN, UP, UP
Sample Output
Uptime %: 80.0
Downtime Count: 1
Result
Thus, uptime and logging metrics were successfully analyzed.
Algorithm
1. Import required libraries.
2. Define actual and predicted values.
3. Calculate accuracy score.
4. Display result.
Program (Python)
from [Link] import accuracy_score
y_true = [1, 0, 1, 1]
y_pred = [1, 0, 0, 1]
Sample Input
(No input required)
Sample Output
Accuracy: 0.75
Result
Thus, the model accuracy was successfully evaluated.
Algorithm
1. Define tasks and durations.
2. Use Matplotlib to plot bar chart.
3. Display Gantt chart.
Program (Python)
import [Link] as plt
[Link](tasks, duration)
[Link]("Project Gantt Chart")
[Link]("Days")
[Link]("Tasks")
[Link]()
Sample Input
(No input required)
Sample Output
Horizontal bar chart representing project timeline
Result
Thus, the Gantt chart was successfully created.
Algorithm
1. Load dataset.
2. Define risk conditions (e.g., low usage).
3. Filter risky records.
4. Display results.
Program (Python)
import pandas as pd
data = {
"Region": ["Urban", "Rural", "Urban", "Rural"],
"Usage": [50, 10, 60, 5]
}
df = [Link](data)
Sample Input
(No input required)
Sample Output
High Risk Areas:
Region Usage
1 Rural 10
3 Rural 5
Result
Thus, risks in the dataset were successfully identified.