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

Programs for Artificial Intelligence Lab File

Uploaded by

saluiamanda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Programs for Artificial Intelligence Lab File

Uploaded by

saluiamanda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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.")

An electric power distribution company charges its domestic consumers as follows :

Consumption Units Rate of Charge


0-100 Rs. 1.25 per unit
101-300 Rs. 160 plus Rs. 1.45 per unit in excess of 100 units
301-500 Rs. 250 plus Rs. 1.70 per unit in excess of 300
500 and above Rs. 350 plus Rs. 1.95 per unit in excess of 500

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:

elecUnit = int(input("Enter the number of Electrical Units(KwH) Consumed : "))

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

print("Units Above 300 : ",over3Hund," charges : ",over3Hund*1.7+250)

elecUnit = elecUnit-over3Hund

if(elecUnit>100):

over1Hund = elecUnit-100

bill = bill+over1Hund*1.45+160

print("Units Above 100 : ",over1Hund," charges : ",over1Hund*1.45+160)

elecUnit = elecUnit-over1Hund

if(elecUnit>=0):

bill = bill + elecUnit*1.25

print("Units Above 0 : ",elecUnit," charges : ",elecUnit*1.25)

print("--------------------------------------------------------")

print(" For Total units consumed : ",units,"The total bill : ",bill)

Write a program to print the output of the following series using loop:
-5, 10, -15, 20, -25
Solution:

n=int(input("Enter the length of the series:-"))


p=1
k=5
print("The series is :-")
for i in range (1,n+1):
p=p*-1
print(k*i*p,end=" ")

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 print the sum of natural numbers with in a range.


Solution:
start=int(input("Enter the start value of the range-:"))
stop=int(input("Enter the stop value of the range-:"))
s=0
for i in range(start,stop+1):
s=s+i
print("The sum of natural numbers is-:",s)

Write a program to reverse a number.


Solution:
n=int(input("Enter the number:-"))
s=0
while n>0:
r=n%10
s=s*10+r
n=n//10
print("The reverse of the number is:-",s)

Write a program to check the number is prime or not.


n=int(input("Enter the number:-"))
f=0
for i in range(2,n):
Page 3 of 18
if n%i==0:
f=1
break
if f==0:
print("The number is Prime number.")
else:
print("The number is not Prime number.")

Write a program to check a number is perfect number or not.


#Sum of the factor (except the number) equal to the number (eg. 6)
n=int(input("Enter the number:-"))
s=0
for i in range(1,n):
if n%i==0:
s=s+i
if s==n:
print("The number is Perfect number.")
else:
print("The number is not Perfect number.")

Write a program to search an element form a user defined List.


Solution:
n=int(input("Enter the length of the list:-"))
L=[]
print("Enter the element of the List:-")
for i in range(0,n):
e=int(input())
L.append(e)
print("The List is:-",L)
s=int(input("Enter the element to search:-"))
Page 4 of 18
flag=0
for i in range(0,n):
if s==L[i]:
flag=1
if flag==0:
print("The searched element not present in the list.")
else:
print("The searched element present in the list.")

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

# Read the image

img = cv2.imread(r'C:\Users\DELL\Downloads\sample_image.jpg') # Replace with your


image path

# Check if the image was loaded successfully

if img is None:

print("Error: Could not read the image.")

else:

# Display the image in a window

cv2.imshow('Image Window', img)

# 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

# Save the image in another format (e.g., PNG)

cv2.imwrite('output_image.png', img)

# Destroy all the windows created

cv2.destroyAllWindows()

Explanation:

 cv2.imread(): Reads an image from the specified path.


 cv2.imshow(): Displays the image in a window.
 cv2.waitKey(): Waits for a key press (use 0 to wait indefinitely).
 cv2.imwrite(): Saves the displayed image to a file.
 cv2.destroyAllWindows(): Closes all the OpenCV windows.

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.

Write the Python Code to resize an image using OpenCV.


Solution:
import cv2 # Import the OpenCV library

# Load the original image

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:

print("Error: Could not load image.")

else:

# Define the new width and height

new_width = 300

new_height = 200

# Resize the image

resized_image = cv2.resize(image, (new_width, new_height))

# Display the original and resized images

cv2.imshow('Original Image', image)

cv2.imshow('Resized Image', resized_image)

# Wait for a key press and close the windows

cv2.waitKey(0)

cv2.destroyAllWindows()

Explanation
Resize the Image:

 cv2.resize(image, (new_width, new_height)) resizes the image to the specified


dimensions.
 The new dimensions are provided as a tuple (width, height).

Write the Python Code to convert an image in round shape using OpenCV.
Solution:
import cv2 # Import OpenCV

import numpy as np # Import NumPy for array operations

# Load the original image


Page 9 of 18
image = cv2.imread(r'C:\Users\DELL\Downloads\sample_image.jpg')

# Check if image was loaded successfully

if image is None:

print("Error: Could not load image.")

else:

# Get the dimensions of the image

height, width = image.shape[:2]

# Create a square black mask with the same size as the image

mask = np.zeros((height, width), dtype=np.uint8)

# Calculate the center and radius of the circular mask

center = (width // 2, height // 2)

radius = min(center[0], center[1])

# Draw a white filled circle on the black mask

cv2.circle(mask, center, radius, 255, -1)

# Apply the circular mask to the image

circular_image = cv2.bitwise_and(image, image, mask=mask)

# Create a transparent background by setting areas outside the circle to zero

circular_image = cv2.cvtColor(circular_image, cv2.COLOR_BGR2BGRA)

circular_image[:, :, 3] = mask # Set the mask as the alpha channel

# Display the circular image

cv2.imshow('Round Image', circular_image)

# Wait for a key press and close the window

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

import numpy as np # Import NumPy for array operations

# Load the image in grayscale mode

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:

print("Error: Could not load image.")

else:

# Find the maximum and minimum pixel values

min_pixel_value = np.min(image)

max_pixel_value = np.max(image)

# Display the results

print(f"Minimum pixel value: {min_pixel_value}")

print(f"Maximum pixel value: {max_pixel_value}")

Explanation
Find Minimum and Maximum Pixel Values:

 np.min(image) finds the minimum pixel value in the image.


 np.max(image) finds the maximum pixel value in the image.

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:

[22.86 24.69 21.48 23.53 26.3 ]

Page 13 of 18
BMI Categories:

Person 1: BMI = 22.86, Category = Normal weight

Person 2: BMI = 24.69, Category = Normal weight

Person 3: BMI = 21.48, Category = Normal weight

Person 4: BMI = 23.53, Category = Normal weight

Person 5: BMI = 26.30, Category = Overweight

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 package

import pandas as pd

#Creating Dictionary to store data

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

player=pd.DataFrame(d,index=[‘Virat Kohli’, ‘Babar Azam’, ‘ ‘Ben Stokes’, ‘Steve Smith’])

print(player)

#Display data whose runs >1000

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

Standard Deviation:- 10.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

You might also like