0% found this document useful (0 votes)
51 views32 pages

Lab Report (SP-21447)

Uploaded by

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

Lab Report (SP-21447)

Uploaded by

Ammar Nadeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

National University of Modern Languages

LAB Report

Subject: AI LAB
Submitted to: Ma`am Ayesha Zafar
Submitted by: Syed Muhammad Abdullah Gilani (SP-21447)
Class: BSSE-V (Afternoon)
Section: B
Lab # 2
Math in python
Example # 1
Code:
#simple arithmetic
x=1/2
print(x)
#exponent operator
y=2**3
print(y)
#classic division returns float
z=17/3
print(z)
#floor division
a=17//3
print(a)
#modulus operator
m=23%3
print(m)

Output:

Variables
Example # 1
Code:
print ("This program is a demo of variables")
v = 1
print ("The value of v is now", v)
v = v + 1
print ("V now equals itself plus one, making it worth", v)
print ("To make V five times bigger, you would have to type v = v * 5")
v = v * 5
print ("There you go, now V equals", v, "and not", v / 5 )

Output:

Strings
Example # 1
Code:
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
print (word1, word2)
sentence = word1 + " " + word2 + " " +word3
print (sentence)

Output:
Conditional Statements
Example # 1
Code:
y=1
if y==1:
print("Y is still equals to 1, just checked it.")

a=1
if a>5:
print("This shouldn`t happen.")
else:
print("This should happen.")

z=4
if z>70:
print("Something is very wrong.")
elif z<7:
print("This is normal.")

Output:

Input from user


Example # 1
Code:
a=input("Enter value for variable A:")
print(a)

Output:
Task # 1

Write a python code of the given scenario.


Scenario:
Write a simple python program that first displays a simple cafe menu (see example below), asks
the user to enter the number of a choice, and either prints the appropriate action OR prints an
error message that their choice was not valid. Example output: 1. Soup and salad 2. Pasta with
meat sauce 3. Chef's special Which number would you like to order? 2 One Pasta with meat
sauce coming right up! Another example output: 1. Soup and salad 2. Pasta with meat sauce 3.
Chef's special Which number would you like to order? 5 Sorry, that is not a valid choice.

Code:
def display_menu():
print("1. Soup and salad")
print("2. Pasta with meat sauce")
print("3. Chef's special")
def main():
display_menu()
choice = input("Which number would you like to order? ")
if choice == '1':
print("One Soup and salad coming right up!")
elif choice == '2':
print("One Pasta with meat sauce coming right up!")
elif choice == '3':
print("One Chef's special coming right up!")
else:
print("Sorry, that is not a valid choice.")
if __name__ == "__main__":
main()
Output:

Task # 2

Write a python code of the given scenario.


Scenario:
Once upon a time in Apple land, John had three apples, Mary had five apples, and Adam had six
apples. They were all very happy and lived for a long time. End of story.
Your task is to: • create the variables: john, mary, and adam; • assign values to the variables. The
values must be equal to the numbers of fruit possessed by John, Mary, and Adam respectively; •
having stored the numbers in the variables, print the variables on one line, and separate each of
them with a comma; • now 00pp00pcreate a new variable named totalApples equal to addition of
the three former variables. • print the value stored in totalApples to the console • Check if the
totalApples is greater, smaller or equal to 10

Code:
john=3
mary=5
adam=6

print(john,mary,adam)
total_apples=john+mary+adam
print("Total apples are ",total_apples)

if total_apples>10:
print("Total apples are greater than 10.")
elif total_apples<10:
print("Total apples are less than 10.")
else:
print("Total apples are equal to 10.")
Output:
Lab # 3
Loops in python
Example # 1
Code (while loop):
a=0
while a<10:
a=a+1
print(a)

Output:

Code (for loop):


for i in range(1,5):
print(i)
for i in range(1,5):
print(i)
else:
print("The loop is over.")

Output:
Function
Example # 1
Code:
def greet():
print("Hello")
print("Good Morning")

greet()

def add_sub(x,y):
a=x+y
b=x-y
return a,b
result1, result2 = add_sub(5,10)
print(result1, result2)

def multiplybytwo(x):
return x*2
a = multiplybytwo(70)
print(a)

Output:
Classes and Inheritance
Example # 1
Code:
class MyClass:
i=12345
def f(self):
return 'Hello World'
x=MyClass()
print(x.i)

Output:

Example # 2
Code:
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print (x.r," ",x.i )

Output:
Example # 3
Code:
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
description = "This shape has not been described yet."
author = "Nobody has claimed to make this shape yet."

def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
a=Shape(3,4)
print (a.area())

Output:
Tasks # 1
Write a program to find the largest of two numbers using function.
Code:
numbers=[]
for i in range(10):
num=int(input("Enter number {}: ".format(i+1)))
numbers.append(num)
max=numbers[0]
for i in range(10):
if numbers[i]>max:
max=numbers[i]
print("Max number is ",max)

Output:

Task # 2

Create a class name basic_calc with following attributes and methods;


Two integers (values are passed with instance creation)
Different methods such as addition, subtraction, division, multiplication

Code:
class basic_calc:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def addition(self):
return self.num1 + self.num2

def subtraction(self):
return self.num1 - self.num2

def division(self):
if self.num2 != 0:
return self.num1 / self.num2
else:
return "Error: Division by zero is not allowed"

def multiplication(self):
return self.num1 * self.num2

calc=basic_calc(25,5)
print("Addition:",calc.addition())
print("Multiplication:",calc.multiplication())
print("Subtraction:",calc.subtraction())
print("Division:",calc.division())

Output:
Lab # 4
Input (reads a string of text from input)
Example # 1
Code:
name=input("What is your name?\n")
print(name," nice name...")

Output:

Example # 2
Code:
name="Linkin Park"
length=len(name)
big_name=str.upper(name)
print(big_name," has ",length," characters.")

Output:
Lists
Example # 1
Code:
num = [1,2,3]
names = ['Talal', 'Husnain', 'Saeed', 'Aezid']
hybrid = [5,5.6,'text']
combined = [num,names,hybrid]
print(combined)

Output:

Example # 2
Code:
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
print (cats[2])
cats.append("Oscar")
print (len(cats))
del cats[1]

Output:
Example # 3
Code:
a= ['spam', 'eggs', 100, 1234]
a[2] = a[2] + 23
print(a)

Output:

Sets
Example # 1
Code:
basket=['Apple','Banana','Orange','Mango','Apple','Guava']
fruit=set(basket)
print(fruit)

print('Orange' in fruit)

Output:
Example # 2
Code:
a=set('abracadabra')
b=set('alacazam')
print('Unique letters in set a: ',a)
print('Unique letters in set b: ',b)
print('Letters in set a but not in b: ',a-b)
print('Letters in set a or b: ',a|b)
print('Letters in both a and b: ', a&b)
print('Letters in a or b but not both: ', a^b)

Output:

Task # 1

Write a program to calculate the length of a string.


Code:
name='Abdullah'
def string_length(name):
count=0
for char in name:
count +=1
return count
print('Length of the string is: ',string_length(name))
Output:

Write a program to calculate the length of a string without using built-in len()
function.
Code:
name='NUML'
counter=0
for i in name:
counter +=1
print('Length of string is: ',counter)

Output:

Task # 2

Write a program that creates a list of 10 random integers. Then create two
lists by name odd_list and even_list that have all odd and even values of the
list respectively.
Code:
import random
randlist=[random.randint(0,50) for _ in range(10)]
even_list=[num for num in randlist if num%2==0]
odd_list=[num for num in randlist if num%2!=0]

print('Original list: ',randlist)


print('Even numbers: ', even_list)
print('Odd numbers: ', odd_list)

Output:
Lab # 5
Intelligent Agents
Example # 1
Room temperature sensor.
Code:
sensor=[10,20,30,40]
def temp_check(sensor):
for sens in sensor:
if sens < 30:
print('Fan OFF.')
elif sens > 30:
print('Fan ON.')
print(temp_check(sensor))

Output:

Example # 2
Vacuum Based Agent.
Code:
class ModelBasedVacuumAgent():
def __init__(self,init_a,init_b):
self.model = {"Loc_a" : init_a, "Loc_b" : init_b}
def DoAction(self,location, status):
self.model[location] = status
print(self.model)
if self.model["Loc_a"] == self.model["Loc_b"] == 'clean':
return 'NoOp'
elif status == 'dirty':
return 'suck'
elif location == "Loc_a":
return 'right'
else:
return 'left'
a=ModelBasedVacuumAgent('dirty','dirty')
print(a.DoAction("Loc_a",'dirty'))

Output:

Task # 1

1. Can you name few model-based reflex agents.


Model-based reflex agents are a type of intelligent agent in artificial intelligence that use
internal models of the world to make decisions. These agents typically consist of four main
components: a model of the world, a set of rules, a state evaluator, and an action function.
Here are a few examples of model-based reflex agents:
➢ Vacuum Cleaner Agent: A simple example where the agent maintains a model of its
environment (thelayout of the room), applies rules based on its current perception (dirt
detection, location), evaluates the state (whether there is dirt in the current location), and
performs actions (suck or move) accordingly.
➢ Traffic Light Controller: An agent responsible for controlling traffic lights at an
intersection. It maintains a model of the traffic flow (number of vehicles approaching
from different directions), applies rules based on traffic regulations and current conditions,
evaluates the state (e.g., traffic congestion), and selects actions (changing signal phases)
accordingly.
➢ Navigation Agent: Used in robotics or autonomous vehicles, a navigation agent
maintains a model ofits environment (map, obstacles), applies rules based on sensor data
(e.g., lidar, cameras), evaluates the state (position relative to the goal, obstacles in the
path), and selects actions (turn, accelerate, brake) to navigate to the destination safely.
2. Write a program for model-based reflex agent of your own choice.

Code:
sensor=[10,20,30,40]
def temp_check(sensor):
for sens in sensor:
if sens < 30:
print('Fan OFF.')
elif sens > 30:
print('Fan ON.')
print(temp_check(sensor))

Output:

3. Consider the vacuum world shown in the figure below:

This particular world has just two locations: squares A and B. The vacuum agent
perceives which square it is in and whether there is dirt in the square. It can choose to
move left, move right, suck up the dirt, or do nothing. One very simple agent function is
the following: if the current square is dirty, then suck, otherwise move to the other
square. Write a simple reflex agent for the vacuum cleaner. (Hint: Agent has no initial
states knowledge) If the current square is dirty, then suck; otherwise, move to the other
square. Pseudocode to the task is as follows; function Reflex-Vacuum- Agent(
[location,status]) returns an action if status = Dirty then return Suck else if location = A
then return Right else if location = B then return Left.
Code:
class ModelBasedVacuumAgent():
def __init__(self,init_a,init_b):
self.model = {"Loc_a" : init_a, "Loc_b" : init_b}
def DoAction(self,location, status):
self.model[location] = status
print(self.model)
if self.model["Loc_a"] == self.model["Loc_b"] == 'clean':
return 'NoOp'
elif status == 'dirty':
return 'suck'
elif location == "Loc_a":
return 'right'
else:
return 'left'
a=ModelBasedVacuumAgent('dirty','dirty')
print(a.DoAction("Loc_a",'dirty'))

Output:
Lab # 6
Task # 1

Consider the given graph:

Use BFS to find the shortest path between A and F. (Hint: the distance between any
consecutive vertices is 1, i.e. distance between A and D is 2 ((A to B=1) + (B to
D=1) = 2)
Task # 2

Consider the given graph:

Using DFS, check if there is any path exists between any two nodes? Also the return
the path. e.g. if user two vertices i.e. 2 and 1; the program should return: Yes the
paths exist, which are [2,1], [2,0,1].
Lab # 7
Different Python packages
Examples

1. NUMPY
2. PANDAS
Task # 1

1. Write a NUMPY program to create a random array of 10x4 and extract


the first five rows of the array and store them into a variable.
Code:
import numpy as np
#creating a random array
array=np.random.rand(10,4)
five_rows=array[:5,:]
print("Array:",array)
print("First five rows:",five_rows)

Output:
2. Write a Pandas program to select the rows where the number of attempts
in the examination is greater than 2.
Sample Python dictionary data and list labels: exam_data = {'name': ['Anastasia',
'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 'attempts': [1, 3, 2, 3, 2, 3, 1, 1,
2, 1], 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] Expected Output: Number of attempts in the examination
is greater than 2: name score attempts qualify b Dima 9.0 3 no d James NaN 3 no f
Michael 20.0 3 yes

Code:
import pandas as pd
import numpy as np

# Create a DataFrame from the given dictionary and list


exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily',
'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data, index=labels)

# Select the rows where the number of attempts is greater than 2


selected_rows = df[df['attempts'] > 2]

# Print the selected rows


print("Total data of exams \n")
print(df)
print("\n")
print("Number of attempts in the examination is greater than 2:\n")
print(selected_rows[['name', 'score', 'attempts', 'qualify']])

Output:

3. From the data given in task # 2, write a program that calculates the
average score. The program should be able to ignore NaN values.

Code:
import pandas as pd
import numpy as np

# Create a DataFrame from the given dictionary and list


exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily',
'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data, index=labels)

# Calculating average scores


average = df['score'].mean()

# Print average score

print("The average score is: ", round(average,2))

Output:

You might also like