May 2025
Exam - Semester Examination
Session - May 2025
Question 1 (20 Marks)
Question Statement
- i) Is String a mutable data type? Also explain the various string operations, indexing and slicing in detail with an appropriate example. (10 Marks)
- ii) Create a NumPy array of the following product prices: [100, 250, 300, 450, 150]. Perform the following operations: (10 Marks)
- a. Find the mean price of the products.
- b. Filter and display the rows where the Category is "Electronics" and the Total_Sales is greater than 10,000.
- c. Create a bar plot using Matplotlib that shows the Product_Name on the x-axis and the Total_Sales on the y-axis for the top 5 products with the highest total sales.
- d. Add appropriate labels for the x-axis, y-axis, and the title for the plot.
- e. Identify and explain which columns in the "sales_data.csv" dataset are examples of categorical data and which ones are numerical data.
| Product_ID | Product_Name | Category | Price | Quantity_Sold | Date |
|---|---|---|---|---|---|
| P001 | Laptop | Electronics | 1000 | 10 | 2023-01-01 |
| P002 | Chair | Furniture | 150 | 50 | 2023-01-05 |
| P003 | Headphones | Electronics | 200 | 25 | 2023-02-10 |
| P004 | Jacket | Clothing | 300 | 20 | 2023-03-15 |
| P005 | Sofa | Furniture | 800 | 5 | 2023-04-20 |
Solution 1 (20 Marks)
(i) String Immutability, Operations, Indexing, and Slicing (10 Marks)
1. Is String a Mutable Data Type?
No, strings in Python are strictly immutable. Once a string object is created in memory, its characters cannot be modified, replaced, or deleted in place.
- Attempting in-place modification (e.g.,
s[0] = 'H') raises aTypeError: 'str' object does not support item assignment. - Concatenation or modification methods (like
.replace()or.upper()) return a brand-new string object at a different memory address (id()).
2. String Operations
- Concatenation (
+): Combines strings ("Data" + " " + "Science""Data Science"). - Repetition (
*): Replicates strings ("AI" * 3"AIAIAI"). - Membership (
in,not in): Tests substring presence ("Art" in "Artificial"True).
3. Indexing and Slicing
Python strings use zero-based positive indexing (left-to-right: to ) and negative indexing (right-to-left: to ):
- Indexing Syntax:
string[index] - Slicing Syntax:
string[start:stop:step](extracts characters fromstartup to but not includingstop).
text = "ARTIFICIAL"
# Indexing
first_char = text[0] # 'A'
last_char = text[-1] # 'L'
# Slicing
prefix = text[0:3] # 'ART'
stride_two = text[::2] # 'ATFCL'
reversed_text = text[::-1] # 'LAICIFITRA'
(ii) NumPy and Sales Dataset Analysis (10 Marks)
a. NumPy Array Creation and Mean Price Calculation
import numpy as np
# Create NumPy array of product prices
prices = np.array([100, 250, 300, 450, 150])
# Compute mean price
mean_price = np.mean(prices)
print(f"Mean Product Price: ${mean_price:.2f}") # Output: $250.00
b. Filtering Rows where Category is "Electronics" and Total_Sales > 10,000
Total sales for each row is computed as :
- P001 (Laptop): 1000 \times 10 = \mathbf{\10,000}> 10,000$)
- P002 (Chair): 150 \times 50 = \7,500$ (Furniture)
- P003 (Headphones): 200 \times 25 = \5,000$ (Electronics)
- P004 (Jacket): 300 \times 20 = \6,000$ (Clothing)
- P005 (Sofa): 800 \times 5 = \4,000$ (Furniture)
import pandas as pd
# Load dataset
df = pd.DataFrame(
{
"Product_ID": ["P001", "P002", "P003", "P004", "P005"],
"Product_Name": [
"Laptop",
"Chair",
"Headphones",
"Jacket",
"Sofa",
],
"Category": [
"Electronics",
"Furniture",
"Electronics",
"Clothing",
"Furniture",
],
"Price": [1000, 150, 200, 300, 800],
"Quantity_Sold": [10, 50, 25, 20, 5],
}
)
df["Total_Sales"] = df["Price"] * df["Quantity_Sold"]
# Filter condition: Category == 'Electronics' and Total_Sales > 10000
filtered_df = df[
(df["Category"] == "Electronics") & (df["Total_Sales"] > 10000)
]
print(filtered_df) # Returns empty DataFrame (P001 equals exactly 10,000)
c & d. Matplotlib Bar Plot of Top 5 Products by Total Sales
import matplotlib.pyplot as plt
# Sort by Total_Sales descending
top_5 = df.sort_values(by="Total_Sales", ascending=False).head(5)
plt.figure(figsize=(8, 5))
plt.bar(
top_5["Product_Name"],
top_5["Total_Sales"],
color="#1f77b4",
edgecolor="black",
)
plt.title("Top 5 Products by Total Sales", fontsize=14, fontweight="bold")
plt.xlabel("Product Name", fontsize=12)
plt.ylabel("Total Sales ($)", fontsize=12)
plt.grid(axis="y", linestyle="--", alpha=0.7)
plt.tight_layout()
plt.show()
e. Categorical vs. Numerical Data Identification
- Categorical Columns (Qualitative Attributes):
Product_ID: Nominal identifier (labels items without arithmetic meaning).Product_Name: Nominal string label.Category: Nominal group classification (Electronics,Furniture,Clothing).Date: Temporal categorical / chronological timestamp.
- Numerical Columns (Quantitative Measures):
Price: Continuous numerical ratio scale ($).Quantity_Sold: Discrete numerical ratio scale (integer count).Total_Sales: Continuous numerical scale ().
Examiner's Note
In part (ii)(b), explicitly point out that Laptop has . Since the question specifies strictly greater than (> 10,000), zero rows meet the strict inequality, whereas captures P001.
Question 2 (20 Marks)
Question Statement
Demonstrate how to load a dataset into a Pandas DataFrame and clean the data (handle missing values, drop unnecessary columns) and Perform group by operations and calculate summary Statistics, display the first 10 rows, and perform basic data manipulation (sorting, filtering). (20 Marks)
| Date | Store | Product | Sales | Quantity |
|---|---|---|---|---|
| 2023-01-01 | Store A | Widget A | 200 | 10 |
| 2023-01-02 | Store A | Widget B | 150 | 5 |
| 2023-01-03 | Store B | Widget A | 300 | 15 |
| 2023-01-04 | Store B | Widget C | NaN | 8 |
| 2023-01-05 | Store A | NaN | 250 | 20 |
| 2023-01-06 | Store C | Widget A | 400 | 20 |
| 2023-01-07 | Store C | Widget B | 100 | 2 |
| 2023-01-08 | Store A | Widget C | 150 | 6 |
| 2023-01-09 | Store B | Widget B | NaN | 5 |
| 2023-01-10 | Store C | Widget C | 350 | 10 |
Demonstrate how to create different types of plots (line plot, bar plot, scatter plot) using Matplotlib. Provide code examples. Explain how to add titles, labels (x and y axis), and customize colors in these plots. Include examples of customization in your code.
Solution 2 (20 Marks)
1. Data Cleaning and Manipulation via Pandas (10 Marks)
import numpy as np
import pandas as pd
# Step 1: Load Dataset into DataFrame
data = {
"Date": [
"2023-01-01",
"2023-01-02",
"2023-01-03",
"2023-01-04",
"2023-01-05",
"2023-01-06",
"2023-01-07",
"2023-01-08",
"2023-01-09",
"2023-01-10",
],
"Store": [
"Store A",
"Store A",
"Store B",
"Store B",
"Store A",
"Store C",
"Store C",
"Store A",
"Store B",
"Store C",
],
"Product": [
"Widget A",
"Widget B",
"Widget A",
"Widget C",
np.nan,
"Widget A",
"Widget B",
"Widget C",
"Widget B",
"Widget C",
],
"Sales": [200, 150, 300, np.nan, 250, 400, 100, 150, np.nan, 350],
"Quantity": [10, 5, 15, 8, 20, 20, 2, 6, 5, 10],
}
df = pd.DataFrame(data)
# Step 2: Data Cleaning
# A. Handle Missing Values: Impute numerical Sales with median, fill categorical Product with mode
df["Sales"] = df["Sales"].fillna(df["Sales"].median())
df["Product"] = df["Product"].fillna(df["Product"].mode()[0])
# B. Drop Unnecessary Columns (Demonstration: drop 'Date' if not modeling time-series)
df_cleaned = df.drop(columns=["Date"])
# Step 3: Display First 10 Rows
print("--- Cleaned DataFrame (First 10 Rows) ---")
print(df_cleaned.head(10))
# Step 4: Group By Operations and Summary Statistics
store_summary = df_cleaned.groupby("Store").agg(
Total_Sales=("Sales", "sum"),
Mean_Sales=("Sales", "mean"),
Total_Quantity=("Quantity", "sum"),
)
print("\n--- Summary Statistics by Store ---")
print(store_summary)
# Step 5: Basic Data Manipulation (Sorting and Filtering)
# Filter: Sales >= 200, then sort by Sales descending
filtered_sorted = df_cleaned[df_cleaned["Sales"] >= 200].sort_values(
by="Sales", ascending=False
)
print("\n--- Filtered (Sales >= 200) and Sorted ---")
print(filtered_sorted)
2. Visualizations with Matplotlib: Customization and Code (10 Marks)
Code Examples for Line, Bar, and Scatter Plots
import matplotlib.pyplot as plt
# Generate Plot Grid
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
# 1. Line Plot: Sales Trend across Days
axes[0].plot(
df["Date"],
df["Sales"],
color="#2b5c8f",
marker="o",
linewidth=2,
linestyle="-",
)
axes[0].set_title(
"Sales Trend Over Time", fontsize=12, fontweight="bold", color="#1c3d5a"
)
axes[0].set_xlabel("Transaction Date", fontsize=10)
axes[0].set_ylabel("Sales Revenue ($)", fontsize=10)
axes[0].tick_params(axis="x", rotation=45)
axes[0].grid(True, linestyle=":", alpha=0.6)
# 2. Bar Plot: Total Quantity Sold per Store
store_qty = df.groupby("Store")["Quantity"].sum()
axes[1].bar(
store_qty.index,
store_qty.values,
color=["#e6550d", "#fdae6b", "#fee6ce"],
edgecolor="black",
)
axes[1].set_title(
"Total Quantity by Store", fontsize=12, fontweight="bold", color="#8c2d04"
)
axes[1].set_xlabel("Store Location", fontsize=10)
axes[1].set_ylabel("Quantity Sold", fontsize=10)
axes[1].grid(axis="y", linestyle="--", alpha=0.5)
# 3. Scatter Plot: Sales vs. Quantity (Relationship)
axes[2].scatter(
df["Quantity"],
df["Sales"],
color="#31a354",
s=df["Quantity"] * 10,
alpha=0.8,
edgecolor="black",
)
axes[2].set_title(
"Sales vs. Quantity Sold", fontsize=12, fontweight="bold", color="#006d2c"
)
axes[2].set_xlabel("Units Sold", fontsize=10)
axes[2].set_ylabel("Sales ($)", fontsize=10)
axes[2].grid(True, linestyle="--", alpha=0.4)
plt.tight_layout()
plt.show()
Customization Explanations:
- Labels and Titles:
.set_title(),.set_xlabel(), and.set_ylabel()clearly establish coordinate semantics and units. - Color Customization: Hex codes (
#2b5c8f,#e6550d) provide consistent visual hierarchy. - Styling Attributes:
linestyle=":",alpha=0.8(transparency for density), and variable sizings=df['Quantity']*10enhance visual clarity.
Examiner's Note
State explicit strategies for missing values (median imputation for skewed continuous sales; mode imputation for categorical product labels) before presenting grouped aggregation code.
Question 3 (20 Marks)
Question Statement
Solve the 8-Puzzle Problem Using A* Search Algorithm. A robot is trying to solve an 8 puzzle game where tiles need to be rearranged to match the final state. The blank tile (represented as -) can move up, down, left, or right to swap positions with adjacent tiles.
(The blank space - is at position (2,1))
- Using A search*, find the optimal path from the initial state to the final state. (10 Marks)
- What will be the sequence of moves with f(n) calculation taken by the blank tile (-) to reach the final goal state? (10 Marks)
Solution 3 (20 Marks)
1. A* Formulation and Heuristic Definition (10 Marks)
The A* evaluation function is:
- : Number of moves executed from the initial state to current state .
- : Manhattan Distance Heuristic (the sum of absolute horizontal and vertical distances of each numbered tile from its goal position): Admissibility: Because a tile can move at most one square per step and cannot hop over others, the Manhattan distance never overestimates the true remaining moves ().
Goal Coordinate Map ():
Initial State Heuristic Computation:
- Tile 1 at :
- Tile 2 at :
- Tile 3 at :
- Tile 4 at :
- Tile 5 at :
- Tile 6 at :
- Tile 7 at :
- Tile 8 at :
2. Step-by-Step Sequence of Moves and Calculations (10 Marks)
Step 1: Move Blank UP (Swap with Tile 6)
Blank moves from to :
- Tiles 6, 7, 5, 4, 3 are now in their correct goal slots.
- Misplaced tiles: 1 at (dist 1), 2 at (dist 1), 8 at (dist 2).
Step 2: Move Blank UP (Swap with Tile 8)
Blank moves from to :
- Tile 8 is now in its correct goal slot (wait, tile 8 swapped to , distance to is 1).
- Misplaced tiles: 1 at (dist 1), 2 at (dist 1), 8 at (dist 1).
Step 3: Move Blank LEFT (Swap with Tile 2)
Blank moves from to :
- Tile 2 is now in its correct goal slot !
- Misplaced tiles: 1 at (dist 1), 8 at (dist 1).
Step 4: Move Blank DOWN (Swap with Tile 1)
Blank moves from to :
- Tile 1 is now in its correct goal slot !
- Misplaced tiles: 8 at (dist 1 to ).
Step 5: Move Blank RIGHT (Swap with Tile 8)
Blank moves from to :
- All 8 tiles match the goal state configuration perfectly.
Summary of Moves Taken by Blank Tile (-):
- Total Moves: steps (Optimal Path Cost = ).
Examiner's Note
Notice that along the entire optimal path, is perfectly invariant. This demonstrates the consistency (monotonicity) of the Manhattan distance heuristic on the 8-puzzle problem.
Question 4 (20 Marks)
Question Statement
- i) Solve the following crypt arithmetic problem and write the step-by-step process. (10 Marks)
Find the value of if:
- ii) Describe the main idea behind Alpha-Beta Pruning and how it reduces the number of nodes evaluated in a search tree. Find the pruning part of the tree given below: (10 Marks)
Level 0 (MAX): A
/ | \
Level 1 (MIN): B C D
/ \ / \ / \
Level 2 (MAX): E F G H I J
/ \ / \ | / \ / \ / \
Level 3 (Leaves): 2 3 5 9 0 7 4 2 1 5 6
Solution 4 (20 Marks)
(i) Step-by-Step Cryptarithmetic Solution () (10 Marks)
Each letter represents a distinct digit , with leading digits .
Step 1: Determine
The sum of two 4-digit numbers yields a 5-digit number. The maximum carry from the thousands column is . Since is the leading digit of the sum:
Step 2: Determine and
In the thousands column: . Since , , and :
- Maximum possible sum is .
- To produce a carry of into the ten-thousands column without making (since ):
- Then .
- If .
- If (would require , leading to digit collision).
Step 3: Determine and
In the hundreds column: . Since and : Because all letters represent distinct digits, , so there must be a carry from the tens column:
Step 4: Determine
In the tens column: . Substitute :
- If (invalid, as ).
- Therefore, .
Step 5: Determine
In the units column: . Available unused digits from :
- To produce a carry of , .
- If .
- Then .
- With remaining digits , setting .
Verified Complete Mapping:
Compute :
(ii) Alpha-Beta Pruning: Mechanics and Tree Pruning (10 Marks)
1. Principle of Alpha-Beta Pruning
Alpha-Beta pruning eliminates subtrees that cannot influence the final Minimax decision:
- : Lower bound for MAX (maximum score MAX can secure).
- : Upper bound for MIN (minimum score MIN can hold MAX to).
- Pruning Rule: Prune if .
2. Step-by-Step Tree Walkthrough
Level 0: Root A (MAX, alpha = -inf, beta = +inf)
Subtree Under Node B (MIN):
- Node E (MAX):
- Evaluate .
- Evaluate .
- Node returns .
- Node B (MIN): Updates . Current .
- Node F (MAX): Inherits .
- Evaluate leaf .
- Test condition: .
- holds! PRUNE leaf ()!
- Node returns .
- Node B (MIN): . Returns to Root .
Root updates . Current at Root: .
Subtree Under Node C (MIN):
- Node G (MAX): Inherits .
- Evaluate leaf .
- Node C (MIN): Updates .
- Test Pruning at Node C:
- Current bounds: .
- holds!
- PRUNE the entire subtree under Node H (including leaves and )!
- Node returns .
Root retains .
Subtree Under Node D (MIN):
- Node I (MAX): Inherits .
- Evaluate leaf .
- Evaluate leaf .
- Node returns .
- Node D (MIN): Updates .
- Test Pruning at Node D:
- Current bounds: .
- holds!
- PRUNE the entire subtree under Node J (including leaves and )!
- Node returns .
Root retains .
Summary of Results:
- Optimal Value at Root Node A: (via Node B).
- Pruned Parts of the Search Tree:
- Leaf (Value 9) under Node .
- Entire Subtree (Node and leaves ).
- Entire Subtree (Node and leaves ).
Examiner's Note
In part (i), state each step logically from to , and compute . In part (ii), identifying the 3 distinct cutoffs (, subtree , subtree ) accounts for full rubric marks.
Question 5 (20 Marks)
Question Statement
- i) Explain Knowledge based Agents and its Architecture. (6 Marks)
- ii) Brief about Data Mining Techniques in Uncertain knowledge reasoning (7 Marks)
- iii) Write in brief about Bayes theorem in Uncertain knowledge reasoning. (7 Marks)
Solution 5 (20 Marks)
(i) Knowledge-Based Agents and Architecture (6 Marks)
1. Conceptual Definition
A Knowledge-Based Agent (KBA) maintains an internal explicit representation of the world (Knowledge Base) and employs an automated inference engine to deduce new assertions and determine rational actions.
2. Core Architectural Operations
TELL(KB, sentence): Informs the knowledge base about newly perceived facts.ASK(KB, query): Queries the knowledge base using inference rules to deduce the next action.- Inference Engine: Decoupled reasoning mechanism (e.g., propositional resolution or first-order logic unification).
(ii) Data Mining Techniques in Uncertain Knowledge Reasoning (7 Marks)
In real-world environments, knowledge is incomplete, noisy, or imprecise. Data mining leverages statistical techniques to reason under uncertainty:
- Association Rule Mining (Support & Confidence):
- Discovers probabilistic co-occurrences of events (e.g., with confidence ).
- Bayesian Belief Networks:
- Directed Acyclic Graphs (DAGs) representing conditional dependencies and joint probability factorizations:
- Fuzzy Logic Systems:
- Employs continuous membership functions rather than boolean values to handle linguistic vagueness (e.g., "temperature is moderately high").
- Dempster-Shafer Theory of Evidence:
- Models degrees of belief over sets of propositions using belief () and plausibility () intervals, separating ignorance from refuting evidence.
(iii) Bayes' Theorem in Uncertain Knowledge Reasoning (7 Marks)
1. Mathematical Formulation
Bayes' Theorem provides the primary formal foundation for updating subjective or empirical degrees of belief in a hypothesis given observed evidence :
- : Prior Probability (baseline belief before evidence).
- : Likelihood (probability of evidence assuming is true).
- : Posterior Probability (updated belief after observing ).
2. Role in AI Uncertain Reasoning
- Diagnostic Reasoning from Symptoms to Causes: Inverts causal likelihoods () into diagnostic posteriors ().
- Handling Noisy Sensor Observations: In autonomous robotics, Kalman filters use Gaussian Bayesian updates to fuse noisy GPS/odometry signals into precise vehicle location estimates.
- Sequential Evidence Accumulation: Posteriors from initial observations serve as priors for subsequent evidence updates.
Examiner's Note
Contrast Bayesian probabilistic reasoning (managing uncertain degrees of truth) with Fuzzy logic (managing degrees of linguistic vagueness). Include the formal architecture diagram (TELL and ASK interfacing with the KB).
Question 6 (20 Marks)
Question Statement
- i) Calculate the probability that the Alarm rings (A) given that: (10 Marks)
- a. John Calls (J)
- b. Mary Calls (M)
- c. Earthquake doesn't happen (~E)
- d. Burglary doesn't happen (~B)
Bayesian Network Structure:
Burglary (B) ----> Alarm (A) <---- Earthquake (E)
/ \
v v
JohnCalls (J) MaryCalls (M)
Conditional Probability Tables:
P(B) = 0.001
P(E) = 0.002
P(A | B, E) = 0.95
P(A | B, ~E) = 0.94
P(A | ~B, E) = 0.29
P(A | ~B, ~E) = 0.001
P(J | A) = 0.90 P(J | ~A) = 0.05
P(M | A) = 0.70 P(M | ~A) = 0.01
- ii) Give the syntax, semantic and inference mechanisms in Frames with example (10 Marks)
Solution 6 (20 Marks)
(i) Bayesian Network Inference: (10 Marks)
1. Joint Probability Factorization
By conditional independence in the network, and are conditionally independent given :
Expanding the numerator using the chain rule of Bayesian networks:
The denominator is the sum over :
Canceling the common prior term :
2. Numerical Values from CPTs
3. Term Computations
- Case 1: Alarm Occurred ():
- Case 2: Alarm Did Not Occur ():
4. Normalization and Posterior Calculation
- Final Answer:
(ii) Frames in Knowledge Representation (10 Marks)
1. Concept and Syntax
Introduced by Marvin Minsky (1974), a Frame is a structured object-oriented knowledge representation schema consisting of a collection of named Slots, each holding one or more Facets and values.
Frame_Name:
Slot_1: Value_1
Slot_2: Value_2 (Default_Value)
Slot_3: If-Needed Procedural_Attachment
2. Semantics and Components
- Slots: Attributes or properties characterizing the frame entity (e.g.,
Color,Engine,Owner). - Facets: Constraints, ranges, or metadata describing a slot (e.g.,
Value,Default,Range). - Procedural Attachments (Demons): Active code blocks triggered by slot actions:
if-needed: Executed when a slot value is queried but missing.if-added: Executed when a new value is inserted into a slot.if-removed: Executed when a value is deleted.
3. Concrete Example: Vehicle Hierarchy
Frame: AUTOMOBILE
SuperClass: Vehicle
Wheels: 4 (Default)
Fuel: Petrol / Diesel (Range)
Frame: CAR (Inherits from AUTOMOBILE)
Body_Type: Sedan
Passenger_Capacity: 5
Mileage: if-needed Compute_Mileage()
Frame: MY_SEDAN (Instance of CAR)
Color: Silver
Registration_No: "TN-09-AB-1234"
4. Inference Mechanisms in Frames
- Inheritance Reasoning: Instances inherit slots and default values automatically along
is-a(taxonomy) andinstance-ofhierarchies. - Default Reasoning: If an instance lacks a slot value, it uses the inherited default.
- Procedural Daemon Invocation: If a slot is queried without a default, an
if-neededdemon executes to compute the value dynamically.
Examiner's Note
Show the cancellation of the prior terms in part (i), leading to . For part (ii), define slots, facets, and the three procedural demons (if-needed, if-added, if-removed).
Question 7 (20 Marks)
Question Statement
- i) Explain the working principle of Breadth First Search (BFS) and depth first search (DFS) algorithm. Provide a step-by-step illustration with the help of a sample graph. (10 Marks)
- ii) You are developing an AI system to find the shortest path for a delivery robot navigating through a city grid given below with varying terrain costs. Describe how you would implement the A* Search algorithm for this scenario, considering factors such as heuristic functions, node expansion, and path cost evaluation (10 Marks)
Delivery Grid Graph:
Start -> A : cost 2
Start -> B : cost 1
A -> C : cost 3
A -> B : cost 1
A -> D : cost 1
B -> D : cost 5
B -> Goal : cost 10
C -> Goal : cost 7
D -> Goal : cost 4
Heuristics:
h(A) = 3, h(B) = 3, h(C) = 1, h(D) = 2, h(Goal) = 0
Solution 7 (20 Marks)
(i) Breadth-First Search (BFS) vs. Depth-First Search (DFS) (10 Marks)
1. Working Principles
- Breadth-First Search (BFS): Explores all nodes at the current depth before descending to nodes at the next depth level.
- Data Structure: First-In, First-Out (FIFO) Queue.
- Properties: Complete and optimal for unweighted graphs ( time and space).
- Depth-First Search (DFS): Explores as deeply as possible along each branch before backtracking.
- Data Structure: Last-In, First-Out (LIFO) Stack.
- Properties: Incomplete on infinite graphs; non-optimal; low memory ( space).
2. Step-by-Step Illustration on a Sample Graph
- BFS Queue Execution:
- Enqueue Root Queue: . Dequeue , enqueue children: .
- Dequeue , enqueue children: .
- Dequeue , enqueue children: .
- Dequeue level-2 leaves: .
- BFS Visit Order: (Level-by-Level).
- DFS Stack Execution:
- Push Root Stack: . Pop , push children: .
- Pop , push children: .
- Pop (leaf). Pop (leaf).
- Pop , push children: .
- Pop (leaf). Pop (leaf).
- DFS Visit Order: (Branch-by-Branch).
(ii) A* Search Implementation for the Delivery Robot Scenario (10 Marks)
1. Algorithm Components
- : Exact accumulated terrain movement cost from to current node .
- : Estimated remaining distance/cost to .
- : Total estimated path cost through node .
- Priority Queue (Open List): Dequeues the node with minimum .
2. Step-by-Step Node Expansion Trace
| Step | Node Expanded | Neighbors Generated | Priority Queue (Open List sorted by ) | |||
|---|---|---|---|---|---|---|
| 0 | - | Start Node S | 0 | - | - | |
| 1 | Start | A B | 3 3 | |||
| 2 | B () | D Goal | 2 0 | |||
| 3 | A () | B (via A) C D (via A) | (pruned) | - 1 2 | - | |
| 4 | D () | Goal (via D) | 0 | |||
| 5 | C () | Goal (via C) | (pruned) | 0 | - | |
| 6 | Goal | Goal Dequeued | 7 | 0 | 7 | Optimal Goal Reached. Terminate. |
3. Optimal Path and Evaluation
- Optimal Robot Delivery Path:
- Total Optimal Path Cost:
(Comparison with alternative routes: ; ; . A identifies the globally optimal path with cost .)*
Examiner's Note
Show that expanding node updates the cost of reaching from (via ) down to (via ). This leads directly to the optimal path with cost .