PROGRAMMING LABORATORY-1(MIT010067)
ACTIVITY NO. 1:
COMPUTATIONAL PROBLEM OF CAR RENTAL PROBLEM
1.1 INTRODUCTION TO THE PROBLEM
ABC car rental agency closely connected with car rental operators who provide best possible
service to the users. This agency rents the following types to cars.
Economy
Compact
Mid-Size
Full Size
The Economy car rents for Rs. 1000 per day. The Compact car rents for Rs. 1500 per day. The
Mid-size car rents for Rs. 2000 per day. The Full-size car rents for 2500 per day. Further, they
offer 10% discount if car is rented for more than 7 days. This agency also has policy that car
cannot own rent for more than 30 days. The user is requested to select car type and the number of
days for which he wants to take car on rent. Calculate the final amount to be paid to the agency.
As discussed, following steps need to be followed to solve the given problem.
1.2 ANALYZING THE PROBLEM
In this step, we thoroughly understand the problem. After going through the problem, we find
that problem statement contains the conditions which are summarized as follow.
The user can select only four types of cars for rentals: Economy, Compact, Midsize and
Full size with car rentals Rupees 1000, 1500, 2000, 2500 respectively.
The user can take a car for rent maximum for 30 days.
The user gets 10% discount if car is rented for more than 7 days.
The table below shows the name of the data items along with its data type and its name.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 1
PROGRAMMING LABORATORY-1(MIT010067)
Name of the Data Data Type Domain Description
Item (Range Values)
Car Type Char E, C, M, F Type of Car
Number of days Integer 1 to 30 Desired no. of days
for which car will be
rented
1.3 DESIGN THE SOLUTION
During analysis, the first step of the problem solving, we specified what a program is going to
do, what is the input and What should be the desired output of the program. In this phase, we
design the solution. It describes how the program is going to solve it. This is achieved by writing
an algorithm for the same.
1.3.1 PRODUCTION RULES:
1. Start
2. Prompts user to enter the car type.
3. Prompts user to read the number of days for Which to rent a car
4. if (days > 30):
Write” Sorry we cannot rent a car for more than 30 days”
else:
Discount_%=0.10
if(days>7):
E= 1000
If (car_type == ‘E’ or car_type == ‘e’):
without_discount = E * Days
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 2
PROGRAMMING LABORATORY-1(MIT010067)
Discount_amount = without_discount * Discount
Final_discount = without_discount - Discount_amount
else:
without_discount = E * Days
elif:
C= 1500
if (car type= = ‘C’ or car type ==’c’):
else:
# Same as car_type E
elif:
M= 2000
if (car type = ‘M’ or car type == ‘m’)
else:
# Same as car_type E
elif:
F = 2000
if (car type = ‘F’ or car type == ‘f’)
else:
# Same as car_type E
else:
#Invalid character entered
}
1.4 CODE THE SOLUTION
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 3
PROGRAMMING LABORATORY-1(MIT010067)
“Code the Solution” is after developing an algorithm to solve a problem, then writing
excutable instructions to implement it or We can say Once we design the algorithm for the
program, the next step is to translate the algorithm into its equivalent python code which
performs the task as specified in the design .
The python code is as follows,
# Car rental problem
print("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)")
car_type = input ("Enter the Type of the car (E, C, M, F) = ")
Days = int (input ("Please Enter the required days for rent a car
= "))
if (Days >= 30):
print ("sorry we cannot rent the car for more than 30 days")
else:
E = 1000
C = 1500
M = 2000
F = 2500
Discount = 0.10
if (car_type == 'E' or car_type =='e'):
if (Days > 7):
without_discount = E * Days
Discount_amount = without_discount * Discount
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 4
PROGRAMMING LABORATORY-1(MIT010067)
Final_discount = without_discount - Discount_amount
print ("The amount you have to pay is = ",
Final_discount)
else:
print ("The amount you have to pay is =", E*Days)
elif (car_type == 'C' or car_type == 'c'):
if (Days > 7):
without_discount = C * Days
Discount_amount = without_discount * Discount
Final_discount = without_discount - Discount_amount
print ("The amount you have to pay is = ",
Final_discount)
else:
print ("The amount you have to pay is =", C*Days)
elif (car_type == 'M' or car_type == 'm'):
if (Days > 7):
without_discount = M * Days
Discount_amount = without_discount * Discount
Final_discount = without_discount - Discount_amount
print ("The amount you have to pay is = ",
Final_discount)
else:
print ("The amount you have to pay is =", M*Days)
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 5
PROGRAMMING LABORATORY-1(MIT010067)
elif (car_type == 'F' or car_type == 'f'):
if (Days > 7):
without_discount = F * Days
Discount_amount = without_discount * Discount
Final_discount = without_discount - Discount_amount
print ("The amount you have to pay is = ",
Final_discount)
else:
print ("The amount you have to pay is =", F*Days)
else:
print ("Invalid character entered")
1.4.1 OUTPUT
1.5 TESTING THE SOLUTION
In the Code Testing we check the running each line of code with a controlled input, logic
and we verifying if it performs the expected output. If any error occurs, this is fix easily from an
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 6
PROGRAMMING LABORATORY-1(MIT010067)
IDLE window. The programmer repeatedly loads the program into the shell and enters different
set of inputs.
Car Type No. of Days Expected Actual Result Evaluation
Result
E 4 4000 4000 Passed
B 6 Error Name Error Passed
0 0 0.0 Passed
f 10 22500 22500.0 Passed
G 12 Error Name Error Passed
-4 Should not work -4000.0 Should have
some check
3 3000 3000.0 Passed
M 12 21600 21600.0 Passed
C 33 Should not work Appropriate Passed
message
ACTIVITY NO. 2:
COMPUTATIONAL PROBLEM OF FARMER, GOAT, WOLF AND CABAGE
PROBLEM
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 7
PROGRAMMING LABORATORY-1(MIT010067)
2.1 INTRODUCTION TO THE PROBLEM
The Farmer, wolf, goat and cabbage problem is a classic logic puzzle that involves finding a
sequence of moves to transport three items (wolf, goat, cabbage) across a river, subject to certain
constraints. The puzzle originated in ancient Europe in 9th century. Following Steps need to be
followed to solve this problem:
2.2 ANALYZING THE PROBLEM
In this step, we will break down complex information into smaller parts to understand and solve
the problem. Identifying key considerations and solution requirements. Following are Conditions
which are summarized below:
Initial state: All on one side.
Constraints:
o The Wolf and Goat cannot be left together.
o The Goat and Cabbage cannot be left together.
o The farmer must be present to move an item.
o The boat can only hold the farmer and one item.
o Required the minimal moves.
Goal state: All on other side.
The table below shows the name of the data items along with its data type and its name.
Name of the Data Data Type Domain Description
Item (Range Values)
Farmer Char F Location of farmer
Wolf Char W Location of wolf
Goat Char G Location of goat
Cabbage Char C Location of cabbage
2.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a goal.
Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 8
PROGRAMMING LABORATORY-1(MIT010067)
2.3.1 PRODUCTION RULES :
1. If the farmer is on one side, he can move to the other side.
2. If the farmer is on one side with an item, he can move that item to the other side.
3. If the wolf and goat are on the same side, the farmer must be present.
4. If the goat and cabbage are on the same side, the farmer must be present.
5. The boat can only hold the farmer and one item at a time.
6. The farmer cannot move more than one item at a time.
7. The farmer cannot leave the wolf and goat or cabbage together.
2.4 CODE THE SOLUTION
“Code the Solution” is after developing an algorithm to solve a problem, then writing
excutable instructions to implement it or We can say Once we design the algorithm for the
program, the next step is to translate the algorithm into its equivalent python code which
performs the task as specified in the design .
The python code is as follows,
# 3.Farmer, Goat, Wolf and Cabbage Puzzle
print("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)")
left_side = ['farmer', 'goat', 'wolf', 'cabbage']
right_side = []
steps = []
# shows the current state
def show_state():
print("Left Side:", left_side)
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 9
PROGRAMMING LABORATORY-1(MIT010067)
print("Right Side:", right_side)
print()
# Moving function to transfer items from left to right side and
vice versa
def move_to_right(item):
left_side.remove('farmer')
right_side.append('farmer')
if item:
left_side.remove(item)
right_side.append(item)
steps.append(('Move to right', item))
show_state()
def move_to_left(item):
right_side.remove('farmer')
left_side.append('farmer')
if item:
right_side.remove(item)
left_side.append(item)
steps.append(('Move to left', item))
show_state()
def solve_puzzle():
print("Initial State:")
show_state()
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 10
PROGRAMMING LABORATORY-1(MIT010067)
move_to_right('goat') # Farmer takes the goat to the
right side
move_to_left(None) # Farmer returns alone
move_to_right('wolf') # Farmer takes the wolf to the
right side
move_to_left('goat') # Farmer returns with the goat
2.1 move_to_right('cabbage') # Farmer
takes the cabbage to the right side
move_to_left(None) # Farmer returns alone
move_to_right('goat') # Farmer takes the goat to the
right b
print("Solution Complete!")
print("Steps taken:")
for i, step in enumerate(steps, 1):
print(f"Step {i}: {step[0]}, Item: {step[1]}")
# Run the solution
solve_puzzle()
2.4.1 OUTPUT
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 11
PROGRAMMING LABORATORY-1(MIT010067)
2.5 TESTING THE SOLUTION
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 12
PROGRAMMING LABORATORY-1(MIT010067)
Location Location Location Location Expected Actual Evaluation
of Man of Wolf of Goat of Result Result
Cabbage
A B B B Passed
B-A A A Passed
A B B B Passed
B A A A Passed
A B B B Passed
B-A A A Passed
A B B B Passed
ACTIVITY NO. 3:
COMPUTATIONAL PROBLEM OF TOWER OF HANOI
3.1 INTRODUCTION TO THE PROBLEM
The Tower of Hanoi is a classic mathematical puzzle that involves moving a stack of disks from
one rod to another. It is often used to teach recursion in computer science. This recursive
application of rules ensures all disks reach the target rod in the correct order.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 13
PROGRAMMING LABORATORY-1(MIT010067)
Following Steps need to be followed to solve this problem:
3.2 ANALYZING THE PROBLEM
In this step, we will break down complex information into smaller parts to understand and solve
the problem. Identifying key considerations and solution requirements.
Following are Conditions which are summarized below:
Move only one disk at a time.
Never place a larger disk on a smaller disk.
Ensure all disks reach the target rod in the minimum number of moves.
The table below shows the name of the data items along with its data type and its name.
Name of the Data Data Type Domain Description
Item (Range Values)
Number of Disks Integer 1,2,3 Moves of Disks
Number of Rods Char A, B, C Moves of Rods on
Disks
3.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a goal.
Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution.
3.3.1 PRODUCTION RULES :
1. Move Disks to Auxiliary Rod: Move the top disks to the auxiliary rod using the
target rod as temporary storage.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 14
PROGRAMMING LABORATORY-1(MIT010067)
2. Move the Largest Disk to Target Rod: Move the largest disk from the source rod
directly to the target rod.
3. Move Disks to Target Rod: Move the disks from the auxiliary rod to the target rod
using the source rod as temporary storage.
3.4 CODE THE SOLUTION
“Code the Solution” is after developing an algorithm to solve a problem, then writing
excutable instructions to implement it or We can say Once we design the algorithm for the
program, the next step is to translate the algorithm into its equivalent python code which
performs the task as specified in the design .
The python code is as follows,
print ("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 Sem (2024-26)")
def tower_of_hanoi (n, source, destination, auxiliary):
# Base case: If there's only one disk, move it from source to
destination
if n == 1:
print (f"Move disk 1 from {source} to {destination}")
return
# Recursive case: Move the top n-1 disks from source to
auxiliary
tower_of_hanoi (n - 1, source, auxiliary, destination)
# Move the nth disk from source to destination
print (f"Move disk {n} from {source} to {destination}")
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 15
PROGRAMMING LABORATORY-1(MIT010067)
# Move the n-1 disks from auxiliary to destination
tower_of_hanoi (n - 1, auxiliary, destination, source)
# Example usage:
n = 3 # Number of disks
tower_of_hanoi (n, 'A', 'C', 'B')
3.4.1 OUTPUT
3.5 TESTING THE SOLUTION
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 16
PROGRAMMING LABORATORY-1(MIT010067)
Moves of No. of Rods Expected Actual Result Evaluation
Disks Result
1 A to C C C Passed
2 A to B B B Passed
1 C to B B B Passed
3 A to C C C Passed
1 B to A A A Passed
2 B to C C C Passed
1 A to C C C Passed
ACTIVITY NO. 4:
COMPUTATIONAL PROBLEM OF MONKEY BANANA PROBLEM
4.1 INTRODUCTION TO THE PROBLEM
The Monkey Banana Problem is a classic puzzle that is a classic puzzle that requires creative
thinking. This is a fun and engaging brain teaser. A monkey wants to eat a banana hanging from
the ceiling. The monkey cannot reach it directly.
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 17
PROGRAMMING LABORATORY-1(MIT010067)
The monkey can use objects which are present in the room to get the banana. Following Steps
need to be followed to solve this problem:
4.2 ANALYZING THE PROBLEM
In this step, we will break down complex information into smaller parts to understand and solve
the problem. Identifying key considerations and solution requirements.
Following are Conditions which are summarized below:
A monkey wants to eat a banana hanging from the ceiling.
The monkey can use box to reach the banana.
The table below shows the name of the data items along with its data type and its name.
Name of the Data Data Type Domain Description
Item (Range Values)
Monkey Integer 1,2,3 Movement of
monkey
Box Integer 1,2,3 Movement of box
Banana Integer 1,2,3 State of banana
4.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a goal.
Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution.
4.3.1 PRODUCTION RULES :
1. Initial State
a. Monkey on Floor
b. Banana out of reach
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 18
PROGRAMMING LABORATORY-1(MIT010067)
c. Box nearby
2. Rule 1: Move to Box
a. IF Monkey on Floor
b. THEN Move to Box
3. Rule 2: Climb Box
4. IF Monkey at Box
5. THEN Climb Box
6. Rule 3: Pull Banana
a. IF Monkey on Box
b. AND Banana reachable
c. THEN Pull Banana
7. Goal State
a. Monkey get Banana
4.4 CODE THE SOLUTION
“Code the Solution” is after developing an algorithm to solve a problem, then writing excutable
instructions to implement it or We can say Once we design the algorithm for the program, the
next step is to translate the algorithm into its equivalent python code which performs the task as
specified in the design .
The python code is as follows,
# 6. Monkey Banana problem
print("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)\n")
# Define the initial state
state = {
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 19
PROGRAMMING LABORATORY-1(MIT010067)
"monkey": "floor", # "floor" or "box"
"box_position": "room", # "room" or "under_banana"
"monkey_position": "room", # "room" or "under_banana"
"banana": "hanging", # "hanging" or "grabbed"
def move_to_box(state):
if state["monkey_position"] != state["box_position"]:
print("Monkey moves to the box.")
state["monkey_position"] = "room"
return state
def push_box_under_banana(state):
if state["monkey_position"] == "room" and
state["box_position"] == "room":
print("Monkey pushes the box under the banana.")
state["box_position"] = "under_banana"
state["monkey_position"] = "under_banana"
return state
def climb_box(state):
if state["monkey_position"] == "under_banana" and
state["box_position"] == "under_banana":
print("Monkey climbs on the box.")
state["monkey"] = "box"
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 20
PROGRAMMING LABORATORY-1(MIT010067)
return state
def grab_banana(state):
if state["monkey"] == "box" and state["box_position"] ==
"under_banana":
print("Monkey grabs the banana!")
state["banana"] = "grabbed"
return state
def monkey_banana_problem(state):
state = move_to_box(state)
state = push_box_under_banana(state)
state = climb_box(state)
state = grab_banana(state)
# Check if the goal is reached
if state["banana"] == "grabbed":
print("Goal achieved: The monkey has the banana!")
else:
print("The monkey could not reach the banana.")
# Run the solution
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 21
PROGRAMMING LABORATORY-1(MIT010067)
monkey_banana_problem(state)
4.4.1 OUTPUT
4.5 TESTING THE SOLUTION
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs.
No. of No. of State of Expected Actual Evaluation
moves of moves of Banana Result Result
monkey Chair
1 to 2 2 2 Passed
2 to 3 3 3 Passed
3 to 2 Chair at 2 2 Passed
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 22
PROGRAMMING LABORATORY-1(MIT010067)
Climb chair Chair at 2 2 Passed
at 2
Get banana at Banana at 2 2 Passed
2
ACTIVITY NO. 5:
COMPUTATIONAL PROBLEM OF WATER JUG PROBLEM
5.1 INTRODUCTION TO THE PROBLEM
The Water Jug Problem is a classic mathematical puzzle that requires mathematical puzzle that
requires creative problem-solving and logical thinking. This problem involves measuring a
specific amount of water using two Jug of different capacities. The objective is to find a
sequence of operation (filling, emptying, and pouring) that will yield the desired measurement.
Using two water jugs with capacities of 3 liters and 5 liters, measure exactly 4 liters of water.
Following Steps need to be followed to solve this problem:
5.2 ANALYZING THE PROBLEM
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 23
PROGRAMMING LABORATORY-1(MIT010067)
In this step, we will break down complex information into smaller parts to understand and solve
the problem. Identifying key considerations and solution requirements.
Following are Conditions which are summarized below:
Measure 4 liters using 3 liters and 5 liters jugs.
Limited jug capacities, no measuring cups.
Find sequence of operations to measure 4 liters.
The table below shows the name of the data items along with its data type and its name.
Name of Data Data type Domain Description
Item (Range Values)
Jug 1 & Jug 2 Int 0 -7 Filling of Jug
Quantity of water Int 0-7 Quantity of water in
Jug
5.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a
goal. Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution.
5.3.1 PRODUCTION RULES :
1. If 3L Jug is empty, Fill 3L Jug.
2. If 5L Jug is not full and 3L Jug has water, Pour 3L into 5L.
3. If 5L Jug is full, Empty 5L Jug.
4. If 3L Jug has water and 5L Jug is empty, pour 3L into 5L.
5. If 3L Jug id full and 5L Jug has space, Pour 3L into 5L.
5.4 CODE THE SOLUTION
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 24
PROGRAMMING LABORATORY-1(MIT010067)
“Code the Solution” is after developing an algorithm to solve a problem, then writing excutable
instructions to implement it or We can say Once we design the algorithm for the program, the
next step is to translate the algorithm into its equivalent python code which performs the task as
specified in the design .
The python code is as follows,
print("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)")
cap_a = 3
cap_b = 5
# Target amount
goal = 4
# Initialize the amount in each jug
jug_a = 0
jug_b = 0
# Steps to reach the goal
steps = []
# Process to reach the target amount of 4 liters
while jug_a != goal and jug_b != goal:
# Step 1: Fill Jug B (5 liters capacity)
if jug_b == 0:
jug_b = cap_b
steps.append((jug_a, jug_b))
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 25
PROGRAMMING LABORATORY-1(MIT010067)
# Step 2: Pour from Jug B to Jug A until Jug A is full or Jug
B is empty
elif jug_b > 0 and jug_a < cap_a:
transfer = min(cap_a - jug_a, jug_b)
jug_a += transfer
jug_b -= transfer
steps.append((jug_a, jug_b))
# Step 3: Empty Jug A if it's full and we haven't reached the
goal
elif jug_a == cap_a:
jug_a = 0
steps.append((jug_a, jug_b))
# Step 4: Fill Jug B again if it's empty and we haven't
reached the goal
elif jug_b == 0:
jug_b = cap_b
steps.append((jug_a, jug_b))
# Print the solution steps
print("Steps to reach the goal of 4 liters:")
for step in steps:
print(step)
5.4.1 OUTPUT
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 26
PROGRAMMING LABORATORY-1(MIT010067)
5.5 TESTING THE SOLUTION
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs.
Jug 1 Water Jug 2 Water Expected Actual Result Evaluation
Result
0 5 5 5 Passed
3 2 2 2 Passed
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 27
PROGRAMMING LABORATORY-1(MIT010067)
0 2 2 2 Passed
2 0 0 0 Passed
2 5 5 5 Passed
3 4 4 4 Passed
ACTIVITY NO. 6:
COMPUTATIONAL PROBLEM OF SLIDING PUZZLE
6.1 INTRODUCTION TO THE PROBLEM
The Sliding Puzzle, also known as the “15 Puzzle” or “Sliding Tile Puzzle”, is a mind-bending
challenge that tests spatial reasoning and logical thinking. This captivating puzzle requires re-
arranging tiles to unlock a hidden order, developing problem-solving strategies and critical
thinking skills.
By sliding and solving, individuals enhance their cognitive abilities and mental agility, providing
endless entertainment and intellectual stimulation.
Following Steps need to be followed to solve this problem:
6.2 ANALYZING THE PROBLEM
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 28
PROGRAMMING LABORATORY-1(MIT010067)
In this step, we will break down complex information into smaller parts to understand and solve
the problem. Identifying key considerations and solution requirements.
Following are Conditions which are summarized below:
4*4 grid with 15 numbered tiles and 1 Empty space(E).
Tiles are randomly shuffled initially.
Goal: Arrange Tiles in ascending order (1-15) with E at bottom-right.
The table below shows the name of the data items along with its data type and its name.
Name of Data Data type Domain Description
Item (Range Values)
Int Int 0 to 15 No. of Pieces
Empty space Char E Empty piece
6.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a
goal. Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution.
6.3.1 PRODUCTION RULES :
1. Shuffle the puzzle to create a random initial state.
2. Print the current puzzle state.
3. Check if the puzzle is solved.
4. Find valid moves for the empty space( E).
5. Apply a move by swapping E with a valid neighboring tile.
6. Repeat until the puzzle is solved.
6.4 CODE THE SOLUTION
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 29
PROGRAMMING LABORATORY-1(MIT010067)
“Code the Solution” is after developing an algorithm to solve a problem, then writing excutable
instructions to implement it or We can say Once we design the algorithm for the program, the
next step is to translate the algorithm into its equivalent python code which performs the task as
specified in the design .
The python code is as follows,
# Sliding Puzzle problem
print("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)")
# Define the grid size (4x4 puzzle)
GRID_SIZE = 4
# Create the solved puzzle (initial state)
def create_solved_puzzle():
# Initialize a 4x4 grid with numbers 1 to 15 and 'E' (empty
space) at the bottom-right
grid = [list(range(i * GRID_SIZE + 1, (i + 1) * GRID_SIZE +
1)) for i in range(GRID_SIZE - 1)]
grid.append(list(range(GRID_SIZE * (GRID_SIZE - 1) + 1,
GRID_SIZE * GRID_SIZE)))
grid[-1][-1] = 0 # Set the last element to 0 (empty tile,
'E')
return grid
# Print the grid, using "E" for the empty space
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 30
PROGRAMMING LABORATORY-1(MIT010067)
def print_grid(grid):
for row in grid:
print(" ".join(f"{x if x != 0 else 'E':>2}" for x in
row))
print() # Print a blank line after the grid
# Find the position of the empty space (0) in the grid
def find_empty_tile(grid):
for row in range(GRID_SIZE):
for col in range(GRID_SIZE):
if grid[row][col] == 0:
return row, col
# Move the empty space based on the direction (up, down, left,
right)
def move_tile(grid, direction):
row, col = find_empty_tile(grid)
if direction == "left" and col < GRID_SIZE - 2:
grid[row][col], grid[row][col + 1] = grid[row][col + 1],
grid[row][col]
elif direction == "down" and row > 0:
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 31
PROGRAMMING LABORATORY-1(MIT010067)
grid[row][col], grid[row - 1][col] = grid[row - 1][col],
grid[row][col
elif direction == "right" and col > 0:
grid[row][col], grid[row][col - 1] = grid[row][col - 1],
grid[row][col]
return grid
# Main function to show the puzzle's movement and the solved
state at the bottom
def main():
# Start with the solved puzzle (initial state
grid = create_solved_puzzle()
# Print the initial solved puzzle
print("Initial Puzzle:")
print_grid(grid)
# Define a few moves to scramble the puzzle
moves = ["left", "down", "right"]
# Apply moves and print the grid after each move
for move in moves:
grid = move_tile(grid, move)
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 32
PROGRAMMING LABORATORY-1(MIT010067)
print(f"After move {move}:")
print_grid(grid)
# Print the solved puzzle again at the end (bottom-right 'E')
print("Solved Puzzle (End state):")
print_grid(create_solved_puzzle())
if __name__ == "__main__":
main()
6.4.1 OUTPUT
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 33
PROGRAMMING LABORATORY-1(MIT010067)
6.5 TESTING THE SOLUTION
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs.
Movement of Position of Expected Actual Result Evaluation
piece Empty Space Result
09 2nd 2 2 Passed
01 3rd 3 3 Passed
02 4th 4 4 Passed
08 8th 8 8 Passed
05 7th 7 7 Passed
06 6th 6 6 Passed
10 5th 5 5 Passed
09 1st 1 1 Passed
01 2nd 2 2 Passed
02 3rd 3 3 Passed
06 6th 6 6 Passed
11 12th 12 12 Passed
07 11th 11 11 Passed
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 34
PROGRAMMING LABORATORY-1(MIT010067)
04 9th 9 9 Passed
09 5th 5 5 Passed
10 6th 6 6 Passed
04 10th 10 10 Passed
07 11th 11 11 Passed
14 12th 12 12 Passed
15 16th 16 16 Passed
Activity No. 7:
COMPUTATIONAL PROBLEM OF TIC-TAC-TOE
7.1 INTRODUCTION TO THE PROBLEM
Tic Tac Toe is very popular game, it’s also known as Noughs and Crosses, let’s implement an
automatic Tic Tac Toe Game using Python. The game is automatically played by the program
and hence, no computer is needed for playing this game.
Following Steps need to be followed to solve this game:
7.2 ANALYZING THE PROBLEM
In this step, we thoroughly understand the problem. After going through the problem. The Tic-
Tac-Toe is 2-players game where players take turns marking a square on a 3*3 grid. We find that
problem statement contains the Condition which are summarized as follows:
In Which player_1 and player_2 can play this game.
In which player_1(X) makes the first move.
In which player_2(O) makes the second move.
A player cannot place their symbol in a occupied space.
Name of Data Data Type Domain (Range Description
Item values)
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 35
PROGRAMMING LABORATORY-1(MIT010067)
Player_1 Chars 1 to 9 User
Player_2 Chares 1 to 9 User
7.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a goal.
Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution. Tic-Tac-Toe involves creating a 3*3 grid, implementing game logic for
wins/losses/ties, and display the game board/interface.
7.3.1 PRODUCTION RULES :
1. Initialize game board using 3*3 grid.
2. Player X makes move (selects empty square).
3. Update Game board(Marks selected square with X).
4. Check win/tie condition.
5. Switch player(X to O).Repeat steps until game end and display the result.
7.4 CODE THE SOLUTION
“Code the Solution” means after developing an algorithm to solve a problem, then writing
excutable instructions to implement it or We can say Once we design the algorithm for the
program, the next step is to translate the algorithm into its equivalent python code which
performs the task as specified in the design .
Transforming design specification into a functional program.
#Tic-Tac-Toe Game
print("The computational Problem is solved by Simran.\n"
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 36
PROGRAMMING LABORATORY-1(MIT010067)
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)")
board=[" " for x in range(9)]
def print_board():
first_row= "| {} | {} | {} |". format(board[0], board[1],
board[2])
second_row= "| {} | {} | {} |". format(board[3], board[4],
board[5])
third_row= "| {} | {} | {} |". format(board[6], board[7],
board[8])
print()
print(first_row)
print(second_row)
print(third_row)
print()
def player_move(icon):
if icon == "X":
number = 1
elif icon == "O":
number = 2
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 37
PROGRAMMING LABORATORY-1(MIT010067)
print("It's your turn player {}". format(number))
choice = int(input("Enter your move(1-9):").strip())
if board[choice - 1] == " ":
board[choice - 1] = icon
else:
print()
print("That space is taken!")
def is_victory(icon):
if (board[0] == icon and board[1] == icon and board[2] ==
icon) or \
(board[3] == icon and board[4] == icon and board[5] ==
icon) or \
(board[6] == icon and board[7] == icon and board[8] ==
icon) or \
(board[0] == icon and board[3] == icon and board[6] ==
icon) or \
(board[1] == icon and board[4] == icon and board[7] ==
icon) or \
(board[2] == icon and board[5] == icon and board[8] ==
icon) or \
(board[0] == icon and board[4] == icon and board[8] ==
icon) or \
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 38
PROGRAMMING LABORATORY-1(MIT010067)
(board[2] == icon and board[4] == icon and board[6] ==
icon):
return True
else:
return False
def is_draw():
if " " not in board:
return True
else:
return False
while True:
print_board()
player_move("X")
print_board()
if is_victory("X"):
print("X wins! Congratulation!")
break
elif is_draw():
print("It's a Draw!")
break
player_move("O")
if is_victory("O"):
print_board()
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 39
PROGRAMMING LABORATORY-1(MIT010067)
print("O wins! Congratulation!")
break
elif is_draw():
print("It's a draw!")
break
7.4.1 OUTPUT
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 40
PROGRAMMING LABORATORY-1(MIT010067)
7.5 TESTING THE SOLUTION:
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs.
Player 1 Player 2 Moves Expected Actual Description
Result Result
P1 P2 P1 P2
X O 3 0 4 to 9 1 to 9 0 Passed
X O 5 2 6 to 9 3 to 9 2 Passed
X O 0 1 1 to 9 2 to 9 1 Passed
X O 7 0 8 to 9 1 to 9 9 Passed
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 41
PROGRAMMING LABORATORY-1(MIT010067)
ACTIVITY NO. 8:
SOLITAIRE GAME
8.1 INTRODUCTION TO THE PROBLEM
Solitaire is any tabletop game which one can play by oneself, usually with cards, but also with
dominoes. The game is most often played by one person, but can incorporate others. As
discussed, following steps need to be followed to solve the given problem.
8.2 ANALYZING THE PROBLEM
In this step, we thoroughly understand the problem. After going through the problem, we find
that problem statement contains the conditions which are summarized as follows,
In this game requires 1 player and a standard 52 deck of playing cards.
Solitaire is to organize a shuffled deck of cards into 4 stacks in ascending order.
The table below shows the name of the data item along with its date type its name.
Name of the data Data Type Domain Description
Item (Range Values)
Cards String A, K, Q, J, 2 -10 Name of Cards
8.3 DESIGN THE SOLUTION
During analysis, the first step of the problem solving, we specified what a program to do, what is
the input and what should be the desired output of the program. In the next phase, we design the
solution. It describes how the program is going to solve it. This is achieved by writing an
algorithm for the same.
8.3.1 PRODUCTION RULES
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 42
PROGRAMMING LABORATORY-1(MIT010067)
for round = 1, 2, 3, 4, 5, 6, LOOP
for iter = 1,2, …, 1000 LOOP
Enumerate all legal moves (except dealing from the stock).
Let N be the number of such moves. If N>0, then choose a random legal move,
assigning each move a probability of 1/N.
END LOOP
If round < 6, then deal 10 cards from the stock.
if round = 6, then
if all eight suits have been removed, then declare VICTORY;
otherwise, concede DEFEAT.
END LOOP
8.4 CODE THE SOLUTION
“Code the Solution” means after developing an algorithm to solve a problem, then writing
excutable instructions to implement it or We can say Once we design the algorithm for the
program, the next step is to translate the algorithm into its equivalent python code which
performs the task as specified in the design .
Transforming design specification into a functional program.
print ("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem (2024-26) \n")
import random
# Card suits and ranks
SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
# Generate a deck of cards
def generate_deck ():
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 43
PROGRAMMING LABORATORY-1(MIT010067)
return [f"{rank} of {suit}" for suit in SUITS for rank in RANKS]
# Shuffle the deck
def shuffle_deck(deck):
random. shuffle(deck)
return deck
# Deal cards to the tableau
def deal_tableau(deck):
tableau = []
for i in range (7):
tableau. append (deck [: i + 1]) # Deal i+1 cards to the ith pile
deck = deck [i + 1:] # Remove dealt cards from the deck
return tableau, deck
# Display the tableau
def display_tableau(tableau):
print("\nTableau:")
for i, pile in enumerate(tableau):
print (f"Pile {i + 1}: {', ‘. join(pile) if pile else 'Empty'}")
# Main game function
def play_solitaire ():
# Initialize the game
deck = generate_deck ()
deck = shuffle_deck(deck)
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 44
PROGRAMMING LABORATORY-1(MIT010067)
tableau, stock = deal_tableau(deck)
print ("Welcome to Solitaire!")
print ("Cards have been dealt.\n")
while True:
display_tableau(tableau)
print("\nOptions:")
print ("1. Draw a card from the stock.")
print ("2. Quit.")
# Get the player's choice
choice = input ("Choose an option: ")
if choice == "1":
if stock:
drawn_card = stock.pop (0)
print (f"\nYou drew: {drawn_card}")
print (f"Cards remaining in stock: {len(stock)}")
else:
print ("\nThe stock is empty!")
elif choice == "2":
print ("\nThanks for playing Solitaire!")
break
else:
print ("\nInvalid choice. Please choose again.")
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 45
PROGRAMMING LABORATORY-1(MIT010067)
# Run the game
if __name__ == "__main__":
play_solitaire ()
8.4.1 OUTPUT
8.5 TESTING THE SOLUTION
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 46
PROGRAMMING LABORATORY-1(MIT010067)
In this step of problem solving, we check for the logical errors, if any, in the program that we
have created. This is done easily from an IDLE window. The Programmer repeatedly loads the
program into the shell and enters different set of inputs.
Card to move Where card Expected Actual Result Evaluation
to be moved Result
mv-stock Waste w w Passed
wf-stock Foundation F f Passed
tf #T waste Tableau t T Passed
Tt #T #T2 To another To another To another Passed
One Tableau column column column
column
h Help Help Help Passed
q Quit Quit Quit Passed
ACTIVITY NO. 9:
COMPUTATIONAL PROBLEM OF 8-QUEEN PROBLEM
9.1 INTRODUCTION TO THE PROBLEM
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 47
PROGRAMMING LABORATORY-1(MIT010067)
The 8-Queen problem is a classic computational puzzle requiring strategic placement of 8 queens
on an 8*8 chessboard, ensuring none attack each other and none share rows, columns, or
diagonals. With 92 possible configurations, finding a solution demands efficient algorithms and
logical reasoning.
Following Steps need to be followed to solve this game:
9.2 ANALYZING THE PROBLEM
In this step, we thoroughly understand the problem. We will break down complex information
into smaller parts to understand and solve the problem. Identifying key considerations and
solution requirements. After going through the problem. In this problem that involves 8 Queens
on an 8*8 chessboard and that no two queens attack each other.
Condition which are summarized as follows:
8 queens on an 8*8 chessboard.
Unique rows, columns, and diagonals.
No Queen attack another.
Name of Data Data Type Domain (Range Description
Item values)
Board Size Integer 8*8 Rows, Columns
Number of Queens Integer 8 Queens
9.3 DESIGN THE SOLUTION
Designing the solution involves creating a detailed plan to solve a problem or achieve a goal.
Also, it involves Identifying the problem or requirement. Evaluating and selecting the best
solution.
9.3.1 PRODUCTION RULES :
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 48
PROGRAMMING LABORATORY-1(MIT010067)
1. Place one queen per row.
2. No two queens can share a columns.
3. No two queens can shares a diagnol.
9.4 CODE THE SOLUTION
“Code the Solution” is after developing an algorithm to solve a problem, then writing excutable
instructions to implement it or We can say Once we design the algorithm for the program, the
next step is to translate the algorithm into its equivalent python code which performs the task as
specified in the design .
The python code is as follows,
# 8-Queen Problem
print("The computational Problem is solved by Simran.\n"
"Roll Number: 244615 of MSC(IT)-1 sem(2024-26)")
def is_safe (board, row, col, n):
# Check for queens in the same column
for i in range(row):
if board[i] == col:
return False
# Check upper-left diagonal
for i, j in zip (range (row, -1, -1), range (col, -1, -1)):
if board[i] == j:
return False
# Check upper-right diagonal
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 49
PROGRAMMING LABORATORY-1(MIT010067)
for i, j in zip (range (row, -1, -1), range (col, n)):
if board[i] == j:
return False
return True
def solve_n_queens (board, row, n):
# If all queens are placed, return the solution
if row == n:
solution = []
for i in range(n):
line = ['.'] * n
line[board[i]] = 'Q'
solution. append ("“. join(line))
solutions. append(solution)
return
# Try placing a queen in each column
for col in range(n):
if is_safe (board, row, col, n):
board[row] = col
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 50
PROGRAMMING LABORATORY-1(MIT010067)
solve_n_queens (board, row + 1, n)
# Backtrack: remove the queen by setting the position
to -1
board[row] = -1
# Main function to find all solutions
def queens(n):
global solutions
solutions = []
board = [-1] * n
solve_n_queens (board, 0, n)
n = 8 # Example usage
solutions = n_queens(n)
print (f"Number of solutions: {len(solutions)}")
for sol in solutions:
for line in sol:
print(line)
print ()
9.4.1 OUTPUT
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 51
PROGRAMMING LABORATORY-1(MIT010067)
9.5 TESTING THE SOLUTION:
In the Code Testing we check the running each line of code with a controlled input, logic and we
verifying if it performs the expected output. If any error occurs, this is fix easily from an IDLE
window. The programmer repeatedly loads the program into the shell and enters different set of
inputs. In 8*8 chessboard.
Queen in Position of Expected Actual Result Evaluation
Row Queen Result
1 1 1 1 Passed
2 7 7 7 Passed
3 5 5 5 Passed
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 52
PROGRAMMING LABORATORY-1(MIT010067)
4 8 8 8 Passed
5 2 2 2 Passed
6 4 4 4 Passed
7 6 6 6 Passed
8 3 3 3 Passed
BIBLIOGRAPHY
For the successful completion of this Computational problem-solving using
python practical file. I have taken help from the following sources which help me
to through out of completion of the file.
WEBSITES: -
1. https://www.w3resources.com
2. https://www.tutorialspoint.com
3. https://www.techvidan.com
4. https://www.geeksforgeeks.org
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 53
PROGRAMMING LABORATORY-1(MIT010067)
BOOKS: -
1. Introduction to Computer Science Using Python: A Computational
Problem-Solving Focus, Charles Dierbach, Wiley Publications, 2012, ISBN:
978-0-470-91204-1
2. Introduction To Computation and Programming Using Python,
GUTTAG JOHN V, PHI, 2014, ISBN-13: 978-8120348660
3. Introduction to Computating& Problem Solving Through Python, Jeeva
Jose andSojan P. Lal,Khanna Publishers, 2015, ISBN-13: 978-9382609810
4. Introduction to Computing and Programming in Python, Mark J.
Guzdial, Pearson Education, 2015, ISBN-13: 978-9332556591
5. Fundamentals of Python by Kenneth Lambert, Course Technology,
Cengage Learning, 2015
6. Learning Python by Mark Lutz, 5th Edition, O'Reilly Media, 2013
LKC\DCSIT\M.SC (IT)-1 Sem\2024-26\244615\22382433116 54