Lab Report (SP-21447)
Lab Report (SP-21447)
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:
Output:
Task # 1
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
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:
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
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 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]
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
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:
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
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
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
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
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
Output: