You are on page 1of 4

18/02/2024, 08:25 K214548 Ai Lab 3.

ipynb - Colaboratory

Task 1 :

1 import math
2
3 def calculate_distance(x,y,n):
4 rx,ry=4,0;
5 distance=[]
6 for i in range(n):
7 distance.append(math.sqrt((x[i]-rx)**2 + (y[i]-ry)**2))
8
9 return distance
10
11 def input_cordinate(point):
12 x=int(input(f"Enter x cordinate for {chr(point)} : "));
13 y=int(input(f"Enter y cordinate for {chr(point)} : "));
14
15 return x,y;
16
17 x,y=[],[];
18 n=int(input("Enter no of points to calculate distance : "));
19 print('\n');
20
21 for i in range(n):
22 point= 65+i;
23 a,b=input_cordinate(point);
24 x.append(a);
25 y.append(b);
26
27 dist=[];
28 dist=calculate_distance(x,y,n)
29 print('\n')
30
31 for i in range(n):
32 print(f"Distance from R to {chr(65+i)} : {round(dist[i],3)}");
33
34

output Enter no of points to calculate distance : 2

Enter x cordinate for A : 1


Enter y cordinate for A : 2
Enter x cordinate for B : 1
Enter y cordinate for B : 2

Distance from R to A : 3.606


Distance from R to B : 3.606

Task 2:

1 class Car:
2 def Left(self):
3 print("Moving to left lane")
4
5 def Right(self):
6 print("Moving to right lane")
7
8 def Break(self):
9 print("Brake Applied")
10
11 def Car_Movement(self, camera_side, distance):
12 if camera_side == "front" and distance <= 8:
13 self.Break()
14 elif camera_side == "left" and distance <= 2:
15 self.Right()
16 elif camera_side == "right" and distance <= 2:
17 self.Left()
18 elif camera_side == "rear" and distance <= 0.05:
19 self.Brake()
20 else:
21 print("Moving Straight")
22
23 car = Car()
24
25 camera_side = input("Enter Object side: ")
26 distance = int(input(f"Enter object distance from {camera_side} of Car: "))
27
28 car.Car_Movement(camera_side, distance)
29

Enter Object side: front


Enter object distance from front of Car: 9
Moving Straight

Task 3:

https://colab.research.google.com/drive/1LLBfKGvZ7ISgdXPrUGCCA7PwY5tet3C_#scrollTo=_p4bwlrX-c9X&uniqifier=1&printMode=true 1/4
18/02/2024, 08:25 K214548 Ai Lab 3.ipynb - Colaboratory
1 def cel_to_frh(celsius):
2 return (celsius * 9/5) + 32
3
4 def average_temp(sensor_data):
5 t_temp = sum(sensor_data)
6 avg_temp = t_temp / len(sensor_data)
7 return cel_to_frh(avg_temp)
8
9 sensor_data = []
10 for i in range(9):
11 temperature = float(input(f"Enter temperature reading from sensor {i+1} in Celsius: "))
12 sensor_data.append(temperature)
13
14 avg_fr = average_temp(sensor_data)
15 print(f"Average Temperature: {avg_fr:.2f}°F")
16

Enter temperature reading from sensor 1 in Celsius: 1


Enter temperature reading from sensor 2 in Celsius: 2
Enter temperature reading from sensor 3 in Celsius: 3
Enter temperature reading from sensor 4 in Celsius: 4
Enter temperature reading from sensor 5 in Celsius: 5
Enter temperature reading from sensor 6 in Celsius: 6
Enter temperature reading from sensor 7 in Celsius: 7
Enter temperature reading from sensor 8 in Celsius: 8
Enter temperature reading from sensor 9 in Celsius: 9
Average Temperature: 41.00°F

Task 4:

1 class automatic_vacum_cleaner:
2
3 def __init__(self,room,i,j):
4 self.room=room
5 self.n=len(room)
6 self.x=i
7 self.y=j
8 self.path=[]
9
10 def display(self):
11 print("")
12 for row in self.room:
13 print(' '.join(row));
14 print("\n");
15
16 def display_path(self):
17 print(f"Path : {self.path}")
18
19 def clean(self,i,j):
20 if self.room[i][j] == "D":
21 self.room[i][j]="C"
22 self.path.append((i,j))
23 self.x,self.y=i,j
24
25 def checking_for_cleaning(self):
26 if self.room[self.x][self.y]=="D":
27 self.clean(self.x,self.y)
28
29 while any(self.room[i][j] == "D" for i, j in [(self.x-1, self.y), (self.x+1, self.y), (self.x, self.y-1), (self.x, self.y+1)]):
30 directions = [(self.x-1, self.y), (self.x+1, self.y), (self.x, self.y-1), (self.x, self.y+1)]
31 for i, j in directions:
32 if 0 <= i and 0 <= j and self.room[i][j] == "D":
33 self.clean(i, j)
34
35 room=[
36 ['D', 'D', 'B', 'D', 'D'],
37 ['C', 'D', 'C', 'B', 'C'],
38 ['D', 'D', 'D', 'C', 'D'],
39 ['C', 'D', 'B', 'D', 'C'],
40 ['D', 'D', 'D', 'B', 'D']
41 ]
42
43 i=int(input("Enter starting row : "))
44 j=int(input("Enter starting column : "))
45
46 vac_clr=automatic_vacum_cleaner(room,i,j)
47 vac_clr.display()
48 vac_clr.checking_for_cleaning()
49 vac_clr.display_path()
50 vac_clr.display()

Enter starting row : 0


Enter starting column : 0

D D B D D
C D C B C
D D D C D
C D B D C
D D D B D

Path : [(0, 0), (0, 1), (1, 1), (2, 1), (3, 1), (2, 0), (2, 2)]

C C B D D
C C C B C
C C C C D
C C B D C
D D D B D

https://colab.research.google.com/drive/1LLBfKGvZ7ISgdXPrUGCCA7PwY5tet3C_#scrollTo=_p4bwlrX-c9X&uniqifier=1&printMode=true 2/4
18/02/2024, 08:25 K214548 Ai Lab 3.ipynb - Colaboratory

Task 5:

1 import random
2
3 def print_board(board):
4 print("-" * 9)
5 for row in board:
6 print(" | ".join(row))
7 print("-" * 9)
8
9 def check_winner(board, player):
10 for i in range(3):
11 if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
12 return True
13
14 if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
15 return True
16
17 return False
18
19 def board_full(board):
20 return all(board[i][j] != ' ' for i in range(3) for j in range(3))
21
22 def player_turn(player_name, board):
23 while True:
24 row = int(input(f"{player_name}, enter row (0, 1, or 2): "))
25 col = int(input(f"{player_name}, enter column (0, 1, or 2): "))
26 if board[row][col] == ' ':
27 return row, col
28 else:
29 print("Cell already occupied. Try again.")
30
31
32 def comp_turn(board):
33 empty_cells = [(i, j) for i in range(3) for j in range(3) if board[i][j] == ' ']
34 return random.choice(empty_cells)
35
36 def play():
37 board = [[' ' for _ in range(3)] for _ in range(3)]
38 print("Welcome to Tic Tac Toe!")
39
40 while True:
41 print_board(board)
42
43 player_row, player_col = player_turn("Player 1", board)
44 board[player_row][player_col] = 'O'
45
46 if check_winner(board, 'O'):
47 print_board(board)
48 print("Player 1 wins! Congratulations!")
49 break
50
51 if board_full(board):
52 print_board(board)
53 print("It's a draw!")
54 break
55
56 player_row, player_col = comp_turn(board)
57 board[player_row][player_col] = 'X'
58
59 if check_winner(board, 'X'):
60 print_board(board)
61 print("Player 2 wins! Congratulations!")
62 break
63
64 play()
65

Welcome to Tic Tac Toe!


---------
| |
---------
| |
---------
| |
---------
Player 1, enter row (0, 1, or 2): 1
Player 1, enter column (0, 1, or 2): 1
---------
| | X
---------
| O |
---------
| |
---------
Player 1, enter row (0, 1, or 2): 0
Player 1, enter column (0, 1, or 2): 0
---------
O | X | X
---------
| O |
---------
| |
---------
Player 1, enter row (0, 1, or 2): 2
Player 1, enter column (0, 1, or 2): 2
---------
O | X | X
---------
| O |
---------

https://colab.research.google.com/drive/1LLBfKGvZ7ISgdXPrUGCCA7PwY5tet3C_#scrollTo=_p4bwlrX-c9X&uniqifier=1&printMode=true 3/4
18/02/2024, 08:25 K214548 Ai Lab 3.ipynb - Colaboratory
| | O
---------
Player 1 wins! Congratulations!

Task 6:

1 def dijkstra(graph, start, end):


2 n = len(graph)
3 unvisited = set(range(n))
4 dist = [float('inf')] * n
5 prev = [None] * n
6 dist[start] = 0
7
8 while unvisited:
9 current = min(unvisited, key=lambda node: dist[node])
10
11 unvisited.remove(current)
12
13 if current == end:
14 path = [end]
15 while prev[path[-1]] is not None:
16 path.append(prev[path[-1]])
17 path.reverse()
18 return dist[end], path
19
20 for nbr, w in enumerate(graph[current]):
21 if w != 0 and nbr in unvisited:
22 if dist[current] + w < dist[nbr]:
23 dist[nbr] = dist[current] + w
24 prev[nbr] = current
25
26 return float('inf'), []
27
28
29 locs = ["Fast Nu", "Karsaz", "Sadar", "Gulshan", "Korangi"]
30 g = [
31 [0, 15, 0, 30, 20],
32 [15, 0, 10, 8, 10],
33 [0, 10, 0, 20, 10],
34 [20, 10, 10, 0, 0]
35 [30, 8, 20, 0, 0],
36 ]
37
38 print("Available locations:")
39 for i, l in enumerate(locs):
40 print(f"{i}. {l}")
41
42 s = int(input("Enter the starting location: "))
43 e = int(input("Enter the destination location: "))
44
45 shortest_d, path = dijkstra(g, s, e)
46 print(" ")
47 print(f"Shortest distance from {locs[s]} to {locs[e]}: {shortest_d} km")
48 print("Shortest path:")
49 print(" -> ".join(locs[node] for node in path))
50
51
52

Available locations:
0. Fast Nu
1. Karsaz
2. Sadar
3. Gulshan
4. Korangi
Enter the starting location: 0
Enter the destination location: 4

Shortest distance from Fast Nu to Korangi: 20 km


Shortest path:
Fast Nu -> Korangi

Task 7:

For Task 4 : Using Q-learning method make it to learn and improve its responses to temperature data over time. Using calculation it make the
agent to predict the data more accurate

For Task 5 : Policy iteration method can be use where the agent continually refines its gameplay strategies. Through iterations, the agent adapts
its policies, making smarter moves to either win the game or prevent losses.

For Task 6 : Using value iteration method agent learns the most efficient paths by iteratively updating location values, improving its decision-
making for finding the shortest routes

https://colab.research.google.com/drive/1LLBfKGvZ7ISgdXPrUGCCA7PwY5tet3C_#scrollTo=_p4bwlrX-c9X&uniqifier=1&printMode=true 4/4

You might also like