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

Artificial Intelligence Lab Final b-25439

The document contains solutions to 4 questions about Python programming concepts. Question 1 defines a Student class and includes methods to sort a list of students by name, age, department, or grade. Question 2 defines Node and Tree classes to represent a binary tree, with methods to construct a tree from a list, find the lowest common ancestor of two nodes, and find the greatest value in the tree. Question 3 provides an implementation of topological sorting on a graph. Question 4 defines a CustomList class that implements common list operations like append, insert, remove, get, set, sort, and reverse.

Uploaded by

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

Artificial Intelligence Lab Final b-25439

The document contains solutions to 4 questions about Python programming concepts. Question 1 defines a Student class and includes methods to sort a list of students by name, age, department, or grade. Question 2 defines Node and Tree classes to represent a binary tree, with methods to construct a tree from a list, find the lowest common ancestor of two nodes, and find the greatest value in the tree. Question 3 provides an implementation of topological sorting on a graph. Question 4 defines a CustomList class that implements common list operations like append, insert, remove, get, set, sort, and reverse.

Uploaded by

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

Artificial Intelligence - Lab

Lab Final Term


Roll number: B-25439
Name: Nauman shahid

Question 1 solution:
Ans: class Student:
def __init__(self, name, age, department, grade):

self.name = name

self.age = age

self.department = department

self.grade = grade

def __repr__(self):

return f"Student('{self.name}', {self.age}, '{self.department}', '{self.grade}')"

def sort_students(students, criteria):

if criteria == 1:

students.sort(key=lambda student: student.name)

elif criteria == 2:

students.sort(key=lambda student: student.age)

elif criteria == 3:

students.sort(key=lambda student: student.department)

elif criteria == 4:

students.sort(key=lambda student: student.grade)

else:

print("Invalid criteria.")
def print_students(students):

for student in students:

print(student)

students = [

Student("Abrar", 30, "CS", "C"),

Student("Babar", 26, "Physics", "B"),

Student("Rizwan", 32, "Chemistry", "B+"),

Student("Shaheen", 23, "Geography", "C"),

Student("Fakhar", 28, "Physics", "D")

print("Enter students details:")

print_students(students)

criteria = int(input("Choose criteria to sort: 1. Name, 2. Age, 3. Department, 4. Grade: "))

sort_students(students, criteria)

if criteria in [1, 2, 3, 4]:

print(f"\nSorting {['Name', 'Age', 'Department', 'Grade'][criteria - 1]} wise:")

print_students(students)

question 2 solution:
Ans: class Node:
def __init__(self, value):

self.value = value
self.left = None

self.right = None

def construct_tree(elements):

if not elements:

return None

root = Node(elements[0])

queue = [root]

i=1

while queue and i < len(elements):

current_node = queue.pop(0)

if elements[i] is not None:

current_node.left = Node(elements[i])

queue.append(current_node.left)

i += 1

if i < len(elements) and elements[i] is not None:

current_node.right = Node(elements[i])

queue.append(current_node.right)

i += 1

return root

def find_lca(root, node1, node2):

if root is None:
return None

if root.value == node1 or root.value == node2:

return root

left_lca = find_lca(root.left, node1, node2)

right_lca = find_lca(root.right, node1, node2)

if left_lca and right_lca:

return root

return left_lca if left_lca else right_lca

def find_greatest_value(root):

if root is None:

return float('-inf')

queue = [root]

max_value = root.value

while queue:

current_node = queue.pop(0)

max_value = max(max_value, current_node.value)

if current_node.left:

queue.append(current_node.left)

if current_node.right:
queue.append(current_node.right)

return max_value

# Example usage

nodes = [20, 8, 22, 4, 12, 10, 14]

root_node = 20

binary_tree = construct_tree(nodes)

lca_node1 = 10

lca_node2 = 14

lca = find_lca(binary_tree, lca_node1, lca_node2)

greatest_value = find_greatest_value(binary_tree)

print("LCA of", lca_node1, "and", lca_node2, "is", lca.value)

print("The greatest value is:", greatest_value)

OUTPUT:

LCA of 10 and 14 is 12

The greatest value is: 22

QUESTION 3 SOLUTION:
Ans:
class Graph:

def __init__(self, vertices):


self.graph = defaultdict(list)

self.V = vertices

def addEdge(self, u, v):

self.graph[u].append(v)

def topologicalSortUtil(self, v, visited, stack):

visited[v] = True

for i in self.graph[v]:

if visited[i] == False:

self.topologicalSortUtil(i, visited, stack)

stack.append(v)

def topologicalSort(self):

visited = [False] * self.V

stack = []

for i in range(self.V):

if visited[i] == False:

self.topologicalSortUtil(i, visited, stack)

stack.reverse()

return stack

# Example:

g = Graph(6)

g.addEdge(5, 2)
g.addEdge(5, 0)

g.addEdge(4, 0)

g.addEdge(4, 1)

g.addEdge(2, 3)

g.addEdge(3, 1)

output:

Following is a Topological Sort of the given graph:

542310

Question 4 solution:
Ans:
class CustomList:

def __init__(self):

self._data = []

def append(self, element):

"""Add an element to the end of the list."""

self._data.append(element)

def insert(self, index, element):

"""Insert an element at the specified index."""

self._data.insert(index, element)

def remove(self, element):

"""Remove the first occurrence of the specified element from the list."""

self._data.remove(element)
def index(self, element):

"""Return the index of the first occurrence of the specified element."""

return self._data.index(element)

def count(self, element):

"""Return the number of occurrences of the specified element in the list."""

return self._data.count(element)

def size(self):

"""Return the number of elements in the list."""

return len(self._data)

def get(self, index):

"""Return the element at the specified index."""

if index < 0 or index >= len(self._data):

raise IndexError("Index out of range")

return self._data[index]

def set(self, index, element):

"""Set the element at the specified index to a new value."""

if index < 0 or index >= len(self._data):

raise IndexError("Index out of range")

self._data[index] = element

def sort(self):

"""Sort the elements in the list in ascending order."""

self._data.sort()

def reverse(self):
"""Reverse the order of the elements in the list."""

self._data.reverse()

# Create an instance of the custom list

my_list = CustomList()

# Add elements to the list using append and insert methods

my_list.append(10)

my_list.append(20)

my_list.insert(1, 15)

# Retrieve elements from the list using get method

print(my_list.get(0)) # Output: 10

print(my_list.get(1)) # Output: 15

print(my_list.get(2)) # Output: 20

# Modify elements in the list using set method

my_list.set(2, 25)

print(my_list.get(2)) # Output: 25

# Remove elements from the list using remove method

my_list.remove(15)

print(my_list.size()) # Output: 2

# Perform operations such as finding index, counting occurrences, and sorting/reversing the list

print(my_list.index(20)) # Output: 1

print(my_list.count(10)) # Output: 1

my_list.sort()

print(my_list.get(0)) # Output: 10
my_list.reverse()

print(my_list.get(0)) # Output: 25

# Print the final state of the list

print(my_list.size()) # Output: 2

print(my_list.get(0)) # Output: 25

print(my_list.get(1)) # Output: 10

You might also like