0% found this document useful (0 votes)
7 views

For Studnets Updated Labmanual after approval

The document outlines various Python exercises aimed at building foundational skills in AI modeling, data manipulation, and mathematical calculations. Each exercise includes an aim and a step-by-step algorithm for implementation, covering topics such as BFS for maze solving, concrete mix calculations, GPA computation, and operations on lists and arrays. Additionally, it includes instructions for installing Anaconda for data analytics and working with NumPy arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

For Studnets Updated Labmanual after approval

The document outlines various Python exercises aimed at building foundational skills in AI modeling, data manipulation, and mathematical calculations. Each exercise includes an aim and a step-by-step algorithm for implementation, covering topics such as BFS for maze solving, concrete mix calculations, GPA computation, and operations on lists and arrays. Additionally, it includes instructions for installing Anaconda for data analytics and working with NumPy arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Ex.

No: 1 BUILD A SIMPLE AI MODEL USING PYTHON


Date:

Aim:
To build a simple AI model using python for Maze problem

Algorithm:
Step1: Initialize BFS

 Create a queue (queue) to store positions that need to be explored.


 Store the current position and the path taken in the queue as (position, path).
 Create a visited matrix (visited[][]) to track explored positions.
 Define four possible movement directions (Up, Down, Left, Right).

Step 2: BFS Traversal Process

1. Dequeue the front element (current_position, path_taken).


2. Check if we reached the goal:
o If (current_position == goal), return path_taken as the solution.

Step 3: Explore all possible moves:

 Try moving in all four directions.


 If the new position is within bounds, not visited, and is a valid path (0), then:
o Mark it as visited.
o Add it to the queue with the updated path.

Step 4: Repeat until either:

 The goal is reached, returning the path.


 The queue becomes empty, meaning no path exists.

Ex. No: 2 CONCRETE MIX CALCULATOR (CEMENT, SAND, AGGREGATE)


Date:

Aim:
To calculate the required cement, sand, and aggregate for a concrete mix (1:2:4).

Algorithm:
1. Input cement quantity
2. Compute sand and aggregate using the ratio 1:2:4
3. Display the required quantities
Ex.No: 3 LED RESISTOR CALCULATOR
Date:

Aim:
To calculate the required resistor value for an LED circuit using: R = (Vs - Vled) / Iled

Algorithm:
1. Input supply voltage (Vs)
2. Input LED voltage (Vled)
3. Input LED current (Iled)
4. Compute resistor value using R = (Vs - Vled) / Iled
5. Display the resistor value (R) in ohms

Ex No: 4 VOLTAGE-CURRENT TO POWER CONVERSION


Date:

Aim:
To convert Voltage-Current to Power Conversion

Algorithm:

1. Input voltage (V) from the user


2. Input current (I) from the user
3. Compute power using the formula: P=V×IP = V \times IP=V×I
4. Display the calculated power (P) in watts

Ex No: 5 CALCULATING STRESS, STRAIN, AND YOUNG’S MODULUS


Date:

Aim:
To calculate stress, strain, and Young’s modulus using Hooke’s law.

Algorithm:
1. Get the applied force (F), original area (A), original length (L), and elongation (ΔL).

2. Calculate stress using the formula:

3. Calculate strain using the formula:

4. Compute Young’s modulus:

5. Display the results.


Ex No: 6 FIND THE GRADE BASED ON MARKS
Date:

Aim:
To determine the grade of a student based on their marks using if-else statements.

Algorithm:
1. Input the marks M.
2. Use an if-elif-else ladder to check the grade range.
3. Print the grade based on the marks.

Ex No: 7 CHECK ALPHABET OR DIGIT


Date:

Aim:
To check if the entered character is an alphabet or a digit using an if-else statement.
Algorithm:
1. Input the character C.
2. Use an if statement to check if the character is alphabetic.
3. Use an elif statement to check if the character is a digit.
4. Print the appropriate message based on the check.

Ex No: 8 SUM OF NUMBERS FROM 1 TO N


Date:

Aim:
To calculate the sum of digits in a number.

Algorithm:

Take an integer input from the user

1. Initialize sum_digits to 0
2. While the number is greater than 0:
o Extract the last digit using number % 10
o Add the extracted digit to sum_digits
o Remove the last digit using number //= 10
3. Print the sum of digits

Ex No: 9 FACTORIAL OF A NUMBER


Date:
Aim:
To calculate the factorial of a number using a 'for' loop.

Algorithm:
1. Input the number N.
2. Initialize a variable 'factorial' to 1.
3. Use a 'for' loop to multiply the factorial with each number from 1 to N.
4. Print the factorial.

Ex No : 10 FUNCTION TO CALCULATE GPA

Date:

Aim:

To create a function that calculates the GPA for the first semester results based on the grades
and credit hours of the courses.

Algorithm:

1. Input Grades and Credits:


Collect the number of courses.
For each course, input the grade obtained and the course's credit hours.
2. Convert Grades to Points:
Use a grade-point mapping (e.g., A=4.0, B=3.0, etc.).
3. Calculate Total Points and Credits:
Multiply grade points by credit hours for each course to get total points.
Sum up all the credit hours and total points.
4. Calculate GPA:
Divide the total points by the total credit hours.
5. Output the GPA.

Ex No: 11 GCD OF TWO NUMBERS USING RECURSIVE FUNCTIONS


Date:

Aim
To use recursive function to calculate GCD of two numbers using python

Algorithm

1. Take two numbers from the user.


2. Pass the two numbers as arguments to a recursive function.
3. When the second number becomes 0, return the first number.
Else recursively call the function with the arguments as the second number
and the
a. remainder when the first number is divided by the second number.

4. Return the first number which is the GCD of the two numbers.
5. Print the GCD.

Ex No: 12 VARIABLE-LENGTH ARGUMENTS OF FUNCTION


Date:

Aim:

To write Python program to illustrate variable-length arguments of python function.

Algorithm:

1. use *args. It enables to accept more arguments than the number of formal arguments
previously defined.
2. use **kwargs to pass a keyworded, variable-length argument list.kwargs is called
with a double star. The reason for this is that the double star permits to pass over
keyword arguments (in any order). Arguments are collected into a dictionary within
the function that allow us to access them by their keys.

3. Define function args_and_kwargs with *args and **kwargs as arguments


3.1 print positional arguments using for loop
3.2 Print Keyword arguments using another for loop.
4. Call the function args_and_kwargs with variable-length arguments

Ex No: 13 CHECK FOR POSITIVE NEGATIVE OR ZERO NUMBER


Date:
USING LAMBDA FUNCTIONS
Aim:

To write a Python code to check if a number is positive, negative, or zero using lamda
functions.
Algorithm:

1. Define function with keyword lambda.


Step1a: Use decision statements (nested if ) to check for positive/negative/zero
Step 1b: Appropriate value is returned and stored in another variable.
2. Call the lambda function with x as argument.
3. Print the value returned by lambda function.

Ex No: 14 SUM OF NATURAL NUMBERS - RECURSIVE FUNCTION


Date:

Aim:

To write a Python program to find the sum of natural numbers using recursive function.

Algorithm:

1. Define a function named recur_sum with parameter n


2. The function returns 1 if the n value is 1.
3. Else recur_sum function is called with the parameter n-1 and the value is returned
4. Using input function get the limit of natural number as num
5. Call the function recur_sum and print the returned value.

Ex No: 15 FIBONACCI SEQUENCE USING RECURSIVE FUNCTION


Date:

Aim:

To write a Python program to display the Fibonacci sequence using recursive function.

Alogrithm:

1. Prompt the user to enter the number of terms, n.


2. If n <= 0, print a message to enter a positive integer and stop.
3. Create a function Fibonacci (x) to calculate the Fibonacci number for term x:
If x == 1, return 0 (base case).
If x == 2, return 1 (base case).
Otherwise, return Fibonacci (x - 1) + Fibonacci (x - 2) (recursive call).
4. Iterate from 1 to n using a loop.
5. For each iteration, call the Fibonacci function and print the result.
6. Display the Fibonacci sequence for n terms.

Ex No:16 OPERATIONS IN THE LIST


Date:

Aim:

To perform various operations in the list

Algorithm:

1. Define a list with numeric values.


2. Use the built-in max() function to find the largest value.
3. Print the maximum value
4. Reverse the lis by list[::-1]
5. Use the remove() method to delete the specified element.
6. Use the sorted() function to sort the list.

Ex No: 17 SLICING OPERATIONS ON A TUPLE

Date:

Aim:

To demonstrate slicing operations on a tuple.

Algorithm:

1. Define a tuple with multiple elements.


2. Use slicing syntax to extract a subset of the tuple.
3. Print the sliced tuple.

Ex No: 18 REPLACING LAST VALUE IN A TUPLE & FINDING DUPLICATES

Date:

Aim:

To replace the last value of a tuple with a new value and find the duplicates in a tuple.

Algorithm:

1. Define a tuple with multiple elements.


2. Extract all elements except the last using slicing.
3. Define the new value to replace the last value.
4. Create a new tuple by combining the sliced elements and the new value.
5. Print the updated tuple.
6. Use a dictionary or collections.Counter to count the occurrences of each element.
7. Identify elements with a count greater than 1.
8. Print the repeated elements

Ex No: 19 DOWNLOAD, INSTALL, AND EXPLORE PYTHON/R FOR


Date:
DATA ANALYTICS

1. Installing Anaconda (Recommended for Python & R)

Anaconda is a distribution that includes Python, R, Jupyter Notebook, and data science
libraries.

Step 1: Download Anaconda

 Visit Anaconda Official Website


 Click on Download and choose the version for your operating system (Windows,
macOS, or Linux).
 Select the latest Python 3.x version (R is included in Anaconda as well).

Step 2: Install Anaconda

 Run the downloaded installer.


 Follow the installation wizard and select the following options:
o Add Anaconda to System PATH (optional but recommended for command-
line access).
o Register Anaconda as the default Python 3.
 Click Install and wait for completion.

Step 3: Verify Installation

 Open Anaconda Navigator from the Start Menu or Applications folder.


 Check for installed applications like Jupyter Notebook, Spyder, and RStudio.

2. Basic Operations in Jupyter Notebook

Jupyter Notebook is a web-based interactive environment for writing Python and R code.

Step 1: Launch Jupyter Notebook

 Open Anaconda Navigator → Click Launch under Jupyter Notebook.


 Alternatively, open the Anaconda Prompt and type:
jupyter notebook

 The Jupyter interface will open in your web browser.

Step 2: Create a New Notebook

 Click New → Python 3 (or R if installed).


 A new notebook with an empty cell appears.

Step 3: Run Basic Operations

1. Print a Message

print("Hello, Data Analytics!")

2. Perform Basic Arithmetic

a = 10
b=5
sum = a + b
sum

3. Data handling

Import Libraries

import pandas as pd
import numpy as np

import pandas as pd

# Create a simple DataFrame

data = {'Name': ['Alice', 'Bob', 'Charlie'],

'Age': [25, 30, 35],

'Salary': [50000, 60000, 70000]}

df = pd.DataFrame(data) # Convert dictionary to DataFrame

# Display the DataFrame

print("DataFrame:\n", df)
# Access a column

print("\nAge Column:\n", df['Age'])

# Filter rows where Salary > 55000

filtered_df = df[df['Salary'] > 55000]

print("\n Employees with Salary > 55000:\n", filtered_df)

# Add a new column

df['Experience'] = [2, 5, 7]

print("\n DataFrame after adding Experience column:\n", df)

# Save to CSV

df.to_csv('data.csv', index=False)

print("\n Data saved to 'data.csv'")

To use R, install RStudio from RStudio Website.

Step 1: Load a Dataset


df <- read.csv("sample_data.csv")
head(df)
Step 2: Inspect Data
summary(df) # Get statistics
str(df) # Check structure
Step 3: Data Cleaning
df <- na.omit(df) # Remove missing values
df$column_name <- as.integer(df$column_name) # Change data type

Result:

Thus the Anaconda was downloaded, Installed, and Explored using R/Python for Data
Analytics
Ex No: 20 CREATION OF NUMPY ARRAY

Date:

Aim:

To create a NumPy array using a tuple and determine its size, shape, and dimension.

Algorithm:

1. Import the NumPy library.


2. Create a tuple containing numerical data.
3. Convert the tuple into a NumPy array.
4. Print the NumPy array.
5. Determine and print the following properties of the array:
o Size: Total number of elements.
o Shape: Tuple representing the dimensions of the array.
o Dimension: Number of dimensions in the array.

Ex No: 21 MANIPULATE NUMPY ARRAY ATTRIBUTES


Date:

Aim:
To manipulate array attributes such as shape, size, dimension, dtype, itemsize, and perform
reshaping, transposition, flattening, and data type conversion using NumPy.

Algorithm:

1. Import the NumPy library.


2. Create a NumPy array from a tuple.
3. Print the original array.
4. Perform the following manipulations:
o Size: Get the total number of elements.
o Shape: Get and modify the shape of the array.
o Dimension: Get the number of dimensions.
o Data Type (dtype): Get the data type of elements.
o Item Size: Get the size of each element in bytes.
o Reshape: Modify the shape of the array.
o Transpose (T): Convert rows to columns and vice versa.
o Flatten: Convert the array into a 1D array.
o Data Type Conversion: Convert elements to a different data type.

Ex No: 22 CREATION OF SUBARRAYS


Date:

Aim:
To create subarrays using NumPy
Algorithm:

1. Initialize an empty list subarrays to store the subarrays.


2. Determine the length of the input array arr and store it in n.
3. Iterate over all possible starting indices i from 0 to n-1:
o For each starting index i, iterate over all possible ending indices j from i+1 to
n.
 Extract the subarray from index i to j-1 using slicing (arr[i:j]).
 Append the extracted subarray to the subarrays list.
4. Return the list subarrays containing all the subarrays.

Ex No: 23 RESHAPING THE ARRAY


Date:

Aim:
To perform the reshaping of the array along the row vector and column vector
Algorithm:

1. Input a 1D NumPy array arr of length n.

2. Steps to Reshape into a Row Vector:

1. Take the input 1D array arr.


2. Use the NumPy reshape() function to reshape the array into a row vector. This means
converting it to a 2D array with 1 row and n columns (i.e., shape (1, n)).
oSyntax: arr.reshape(1, -1) where -1 means NumPy will automatically infer the
number of columns based on the length of the original array.
3. Store the reshaped array as row_vector.

3. Steps to Reshape into a Column Vector:

1. Take the input 1D array arr.

2. Use the NumPy reshape() function to reshape the array into a column vector. This
means converting it to a 2D array with n rows and 1 column (i.e., shape (n, 1)).

o Syntax: arr.reshape(-1, 1) where -1 means NumPy will automatically infer the


number of rows based on the length of the original array.

3. Store the reshaped array as column_vector.

4. Output:

 Return or print both row_vector and column_vector.


Ex No: 24 CONCATENATION OF TWO ARRAYS
Date:

Aim:
To concatenate two arrays using NumPy
Algorithm:

1. Input two NumPy arrays arr1 and arr2 of size n and m respectively.

2. Steps for Concatenation:

1. Initialization:
o Define two arrays arr1 and arr2 with their respective values.

2. Check Compatibility (if needed):


o Ensure that the arrays are compatible for concatenation. For example:
 For 1D arrays, they should simply have the same dimension.
 For 2D arrays:
 If concatenating along rows (axis=0), both arrays must have the
same number of columns.
 If concatenating along columns (axis=1), both arrays must have
the same number of rows.

3. Concatenate Arrays:
o Use NumPy's concatenate() function to combine the arrays along a specified
axis.
 For 1D arrays, concatenate along the horizontal axis (axis=0).
 For 2D arrays, concatenate along either:
 Rows (axis=0): concatenated_array = np.concatenate((arr1,
arr2), axis=0)
 Columns (axis=1): concatenated_array = np.concatenate((arr1,
arr2), axis=1)

4. Step 4: Return or Display Result:


o After the concatenation, return or display the concatenated array.

5. Output:

 A new array, concatenated_array, which is the result of joining arr1 and arr2.
Ex No: 25 STATISTICAL OPERATIONS ON DATA
Date:

Aim:
To perform statistical operations on data using NumPy and Pandas
Algorithm:

1. Import the necessary libraries (Pandas and NumPy).


2. Create a list of numerical data.
3. Convert the list into a Pandas Series.
4. Perform statistical operations like:
o Sum
o Product
o Median
o Minimum
o Maximum
o Quantiles (25%, 50%, 75%)
o Arg min (index of the minimum value)
o Arg max (index of the maximum value)
5. Display the results.

Ex No: 26 CREATION OF SERIES AND DATA FRAMES USING PANDAS


Date:

Aim:
To write python code to illustrate creation of series and data frames in Pandas.
Algorithm:

Step 1: Import Required Libraries

1. Import the pandas and numpy libraries.

Step 2: Create a Pandas Series

1. Define a list data_series containing numerical values.


2. Convert the list into a Pandas Series using pd.Series(data_series).
3. Print the Series.

Step 3: Create a Pandas DataFrame

1. Define a dictionary data with:


o A list of names.
o A list of ages.
o A list of salaries.
2. Convert the dictionary into a Pandas DataFrame using pd.DataFrame(data).
3. Print the DataFrame.

Step 4: Set Index in the DataFrame

1. Use set_index('Name') to set the "Name" column as the index.


2. Store the modified DataFrame in df_indexed.
3. Print the updated DataFrame.

Step 5: Access a Specific Column

1. Select the "Age" column using df['Age'] and store it in age_series.


2. Print the selected column.

Step 6: Access a Specific Row using loc

1. Use df_indexed.loc['Bob'] to fetch details of the row where "Name" is "Bob".


2. Print the selected row.

Step 7: Perform an Operation on the DataFrame

1. Calculate a 10% salary increase using df['Salary'] * 1.1.


2. Store the new values in a new column called "Salary Increase".
3. Print the modified DataFrame.

Ex No: 27 IMPLEMENT DATA SELECTION AND DATA INDEXING


Date:
OPERATIONS
Aim
To implement the Data Selection Operations, Data indexing operations using Pandas
Algorithm:

Step 1: Create a DataFrame

1. Import the pandas library.


2. Define a dictionary containing data with column names (Name, Age, Salary).
3. Convert the dictionary into a Pandas DataFrame.

Step 2: Display the Original DataFrame

4. Print the DataFrame to check the initial data.

Step 3: Data Selection using loc[] (Label-Based Selection)

5. Select a row using loc[]:


o Use df.loc[row_label] to select a row by index label.
6. Select a specific column using loc[]:
o Use df.loc[:, 'Column_Name'] to select a column for all rows.
7. Select multiple rows and columns using loc[]:
o Use df.loc[start_row:end_row, ['Column1', 'Column2']] to extract specific
rows and columns.

Step 4: Data Selection using iloc[] (Integer-Based Selection)

8. Select a row using iloc[]:


o Use df.iloc[row_index] to select a row by integer position.
9. Select a specific column using iloc[]:
o Use df.iloc[:, column_index] to select a column by integer position.
10. Select multiple rows and columns using iloc[]:

 Use df.iloc[start_row:end_row, start_col:end_col] to extract specific rows and


columns.

Step 5: Display Selected Data

11. Print all selected data to verify the output.

Ex No: 28 HANDLING MISSING DATA


Date:
Aim:
To write a python code to demonstrate handling of missing data in Pandas DataFrame.
Algorithm:

1. Initialize DataFrame:
o Create a DataFrame from a dataset that may contain missing values (NaN or
None).
2. Check for Missing Data (isnull()):
o For each cell in the DataFrame, check if the value is missing (NaN or None).
o Return a DataFrame of the same shape with boolean values (True for missing
values and False for non-missing values).

3. Check for Non-Missing Data (notnull()):


o For each cell in the DataFrame, check if the value is not missing.
o Return a DataFrame of the same shape with boolean values (True for non-
missing values and False for missing values).

4. Drop Rows with Missing Data (dropna()):


o Identify rows in the DataFrame that contain any missing values.
o Drop these rows and return a new DataFrame without the missing data.

5. Drop Columns with Missing Data (dropna(axis=1)):


o Identify columns that contain any missing values.
o Drop these columns and return a new DataFrame without the missing data.

6. Fill Missing Data with a Specific Value (fillna()):


o Replace all missing values (NaN or None) with a specific value (e.g., 0, mean,
median).
o Return a new DataFrame with missing values replaced.

7. Fill Missing Data with Statistical Values (fillna() with mean, median, etc.):
o Compute the mean or median of the column.
o Replace missing values in the column with the computed mean or median.
o Return a new DataFrame with imputed values.

Ex No: 29
Date: STORE SALES PREDICTION USING MACHINE LEARNING
ALGORITHM
Aim:
To write a python code to apply machine learning model (Linear regression) to
predict the sales of a store.

Algorithm:
Step 1: Import Required Libraries

 Load necessary libraries such as Pandas, NumPy, Matplotlib, and Scikit-Learn.


Step 2: Load the Dataset

 Create a dataset containing advertising spend (independent variable) and sales


(dependent variable).

Step 3: Split Data into Training and Testing Sets

 Divide the dataset into 80% training and 20% testing.

Step 4: Train the Linear Regression Model

 Fit the training data into the Simple Linear Regression Model.

Step 5: Get Model Parameters

 Extract the slope (m) and intercept (b) of the regression line.

Step 6: Make Predictions

 Use the trained model to predict sales on the test dataset.

Step 7: Evaluate Model Performance

 Calculate Mean Squared Error (MSE) and R² Score to check accuracy.

Step 8: Visualize the Regression Line

 Plot the actual vs. predicted sales to visualize the relationship.

Ex No: 30 DECISION TREE FOR CREDIT CARD APPROVAL PREDICTIONS


Date:

Aim:
To write a python code to perform credit card predictions using decision tree.

Algorithm:

Step 1: Import Required Libraries

 Load necessary libraries such as Pandas, NumPy, and Scikit-learn.


Step 2: Load or Create the Dataset

 The dataset includes financial details like income, credit score, debt, and approval
status.

Step 3: Data Preprocessing

 Convert categorical data (e.g., "Yes"/"No") into numerical form.

Step 4: Split Data into Training and Testing Sets

 Divide the dataset into 80% training and 20% testing.

Step 5: Train the Decision Tree Model

 Fit the training data into the Decision Tree Classifier.

Step 6: Make Predictions

 Use the trained model to predict approval for test data.

Step 7: Evaluate Model Performance

 Measure accuracy using a confusion matrix and classification report.

You might also like