Programs for Artificial Intelligence Lab File
Programs for Artificial Intelligence Lab File
Python
Write a program to display the highest number among three numbers.
a=int(input("Enter the first number:-"))
b=int(input("Enter the second number:-"))
c=int(input("Enter the third number:-"))
if a>b and a>c:
print(a,"is the greater number.")
if b>a and b>c:
print(b,"is the greater number.")
if c>a and c>b:
print(c,"is the greater number.")
Write a program that read the customer number & power consumed and prints the
amount to be paid by the customer. Note that output should be well formatted.
Solution:
units = elecUnit
bill=0
if(elecUnit>500):
over5Hund = elecUnit-500
bill = bill+over5Hund*15
#Detail Bill
Page 1 of 18
print("\nUnits Above 500 : ",over5Hund," charges : ",over5Hund*15)
elecUnit = elecUnit-over5Hund
if(elecUnit>300):
over3Hund = elecUnit-300
bill = bill+over3Hund*1.7+250
elecUnit = elecUnit-over3Hund
if(elecUnit>100):
over1Hund = elecUnit-100
bill = bill+over1Hund*1.45+160
elecUnit = elecUnit-over1Hund
if(elecUnit>=0):
print("--------------------------------------------------------")
Write a program to print the output of the following series using loop:
-5, 10, -15, 20, -25
Solution:
Page 2 of 18
Write a program to display the Multiplication Table of any user given number.
Solution:
n=int(input("Enter the number whose Multiplication Table to display:-"))
print("The Multiplication Table is :-")
for i in range (1,11):
print(n,"*",i,"=",n*i)
Write a program to display the even numbers from a user defined List.
Solution:
n=int(input("Enter the length of the list:-"))
L=[]
print("Enter the number of the List:-")
for i in range(0,n):
e=int(input())
L.append(e)
print("The List is:-",L)
print("The even numbers are:-")
for i in range(0,n):
if L[i]%2==0:
print(L[i],end=" ")
Page 5 of 18
Computer Vision
Input Image:
Write the Python Code to Read, Display, and Save an Image Using OpenCV
Solution:
import cv2
if img is None:
else:
# Wait for a key press indefinitely or for a specified amount of time (in ms)
Page 6 of 18
cv2.waitKey(0) # Press any key to close the window
cv2.imwrite('output_image.png', img)
cv2.destroyAllWindows()
Explanation:
Write the Python Code to display an image in Gray Scale and also display the edges of
the image using OpenCV.
Solution:
import cv2
# Load the image in grayscale
image = cv2.imread(r'C:\Users\DELL\Downloads\sample_image.jpg',
cv2.IMREAD_GRAYSCALE)
# Check if image was loaded successfully
if image is None:
print("Error: Could not load image.")
else:
# Display the grayscale image
cv2.imshow('Grayscale Image', image)
# Wait for a key press and close the window
cv2.waitKey(0)
cv2.destroyAllWindows()
# Apply Canny edge detection
edges = cv2.Canny(image, threshold1=100, threshold2=200)
Page 7 of 18
# Display the edges
cv2.imshow('Edges', edges)
# Wait for a key press and close the window
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation
1. Import OpenCV: We import the OpenCV library with import cv2.
2. Load the Image:
a. cv2.imread(r'C:\Users\DELL\Downloads\sample_image.jpg',
cv2.IMREAD_GRAYSCALE) reads the image in grayscale mode.
b. Replace 'path_to_image.jpg' with the path to your image file.
3. Error Check:
a. If image is None, an error message is displayed. This check ensures the image
path is correct.
4. Apply Canny Edge Detection:
a. cv2.Canny(image, threshold1=100, threshold2=200) performs edge detection on
the grayscale image.
b. threshold1 and threshold2 control the sensitivity of edge detection. You can
adjust these values based on your image.
5. Display the Edges:
a. cv2.imshow('Edges', edges) opens a window displaying only the detected edges.
b. 'Edges' is the title of the window.
6. Wait and Close:
a. cv2.waitKey(0) waits indefinitely for a key press to close the window.
b. cv2.destroyAllWindows() ensures all OpenCV windows are closed.
image = cv2.imread(r'C:\Users\DELL\Downloads\sample_image.jpg')
Page 8 of 18
# Check if image was loaded successfully
if image is None:
else:
new_width = 300
new_height = 200
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation
Resize the Image:
Write the Python Code to convert an image in round shape using OpenCV.
Solution:
import cv2 # Import OpenCV
if image is None:
else:
# Create a square black mask with the same size as the image
cv2.waitKey(0)
cv2.destroyAllWindows()
Page 10 of 18
Explanation
1. Get Image Dimensions:
a. height, width = image.shape[:2] stores the height and width of the image.
2. Create a Black Mask:
a. np.zeros((height, width), dtype=np.uint8) creates a black mask with the same
dimensions as the image.
3. Define Circle Properties:
a. center is set to the center of the image.
b. radius is the smaller of the two distances to ensure the circle fits inside the
image.
4. Draw the Circle on the Mask:
a. cv2.circle(mask, center, radius, 255, -1) draws a white circle at the center of the
mask.
b. 255 is the color for white, and -1 fills the circle.
5. Apply the Mask to the Image:
a. cv2.bitwise_and(image, image, mask=mask) uses the circular mask to retain
only the circular area of the image.
6. Add Transparency:
a. Convert the image to include an alpha channel using
cv2.COLOR_BGR2BGRA.
b. Set the alpha channel to match the circular mask, making the background
transparent.
Write the Python Code to display maximum and minimum pixel of an image using
OpenCV.
Solution:
import cv2 # Import OpenCV
image = cv2.imread(r'C:\Users\DELL\Downloads\sample_image.jpg',
cv2.IMREAD_GRAYSCALE)
Page 11 of 18
# Check if the image was loaded successfully
if image is None:
else:
min_pixel_value = np.min(image)
max_pixel_value = np.max(image)
Explanation
Find Minimum and Maximum Pixel Values:
Page 12 of 18
Data Science
Write a Python Code to Calculate BMI Using NumPy
Solution:
import numpy as np
# Sample data: weights (kg) and heights (m)
weights = np.array([70, 80, 55, 68, 90]) # in kilograms
heights = np.array([1.75, 1.80, 1.60, 1.70, 1.85]) # in meters
# Formula for BMI: BMI = weight / (height ** 2)
bmi = weights / (heights ** 2)
# Display the BMI values
print("BMI values:")
print(np.round(bmi, 2)) # Rounds BMI values to 2 decimal places
# Categorize the BMI results
categories = np.where(bmi < 18.5, 'Underweight', np.where(bmi < 25, 'Normal weight',
np.where(bmi < 30, 'Overweight', 'Obesity')))
print("\nBMI Categories:")
for i in range(len(weights)):
print(f"Person {i+1}: BMI = {bmi[i]:.2f}, Category = {categories[i]}")
Explanation:
Data setup: We store weights and heights in NumPy arrays.
np.round(): Rounds the BMI values to two decimal places.
np.where(): Categorizes the BMI values:
o Underweight: BMI < 18.5
o Normal weight: 18.5 ≤ BMI < 25
o Overweight: 25 ≤ BMI < 30
o Obesity: BMI ≥ 30
Output
BMI values:
Page 13 of 18
BMI Categories:
Write a program to create a dataframe named player and store their data in the
columns like team, no. of matches, runs and average. Assign player name as row index
and display only those player details whose score more than 1000.
Solution:
import pandas as pd
d={‘Team’:[‘India’, ‘Pakistan’, ‘England’, ‘Australia’], ‘Matches’: [25, 23, 19, 17], ‘runs’:
[1120, 1087, 954, 830], ‘Average’: [44.80, 47.26, 50.21, 48.82]}
#Creating Dataframe
print(player)
print(player[player[‘Runs’]>1000])
Output:
Page 14 of 18
Write a program to display the mean, median, variance and standard deviation of a
given array.
Solution:
import numpy as np
ary1=np.array([10,15,20,25,30,35,40])
print(ary1)
print('Mean:-',np.mean(ary1))
print('Median:-',np.median(ary1))
print('Variance:-',np.var(ary1))
print('Standard Deviation:-',np.std(ary1))
Output:
[10 15 20 25 30 35 40]
Mean:- 25.0
Median:- 25.0
Variance:- 100.0
Page 15 of 18
Write a Python Create a Bar Graph using mathplotlib
Solution:
import matplotlib.pyplot as plt
# Data for the bar graph
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 13]
# Creating the bar graph
plt.bar(categories, values, color='skyblue', edgecolor='black')
# Adding title and labels
plt.title('Sample Bar Graph')
plt.xlabel('Categories')
plt.ylabel('Values')
# Display the graph
plt.show()
Explanation
plt.bar(): This function creates a bar graph.
categories: These are the labels on the x-axis.
values: These are the heights of the bars.
color: Sets the color of the bars (can accept names or hex codes).
edgecolor: Sets the color of the bar edges.
plt.title(), plt.xlabel(), plt.ylabel(): Adds the title and axis labels.
Page 16 of 18
Write a Python Create a Pie Chart using mathplotlib
Solution
import matplotlib.pyplot as plt
# Data for the pie chart
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [15, 30, 45, 10] # Percentage distribution
colors = ['#FF9999', '#66B3FF', '#99FF99', '#FFD700'] # Custom colors
explode = (0, 0.1, 0, 0) # Explode the 2nd slice (Bananas)
# Creating the pie chart
plt.pie(sizes, labels=labels, colors=colors, explode=explode, autopct='%1.1f%%',
startangle=140, shadow=True)
# Adding title
plt.title('Fruit Distribution')
# Display the pie chart
plt.show()
Explanation
plt.pie(): Creates a pie chart.
sizes: Represents the percentage (or value) of each category.
Page 17 of 18
labels: Names of the categories.
colors: Custom colors for the slices (you can use names or hex codes).
explode: Moves a slice outward (highlighting a specific part).
Example: (0, 0.1, 0, 0) moves the 2nd slice outward.
autopct: Displays the percentage value inside the slices.
startangle: Rotates the chart to start at a specific angle.
shadow=True: Adds a shadow effect.
Page 18 of 18