Sample Question of AI/DS Intern Test
QUESTION 1
# Initialize graph as a dictionary of dictionaries
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
# Initialize distances and previous node dictionaries
distances = {}
previous_nodes = {}
# Initialize all distances to infinity and previous nodes to None
for node in graph:
distances[node] = float('infinity')
previous_nodes[node] = None
# Set distance to starting node to 0
distances['A'] = 0
# Create a set of all nodes
nodes = set(graph.keys())
while nodes:
# Select node with smallest distance
current_node = min(nodes, key=lambda node: distances[node])
# Remove current node from the set
nodes.remove(current_node)
# Update distances to neighboring nodes
for neighbor, weight in graph[current_node].items():
alternative_route = distances[current_node] + weight
if alternative_route < distances[neighbor]:
distances[neighbor] = alternative_route
previous_nodes[neighbor] = current_node
# Print shortest path from start node to all other nodes
for node in graph:
path = []
current = node
while current is not None:
path.insert(0, current)
current = previous_nodes[current]
print(f"Shortest path to {node}: {' -> '.join(path)}, Distance:
{distances[node]}")
QUESTION 2
# Initialize weights, values, and knapsack capacity
weights = [2, 3, 4, 5]
values = [3, 4, 5, 6]
capacity = 5
n = len(values)
# Create a 2D array to store the maximum value at each n and capacity
dp = [[0 for x in range(capacity + 1)] for x in range(n + 1)]
# Build the table dp[][] in a bottom-up manner
for i in range(n + 1):
for w in range(capacity + 1):
if i == 0 or w == 0:
dp[i][w] = 0
elif weights[i-1] <= w:
dp[i][w] = max(values[i-1] + dp[i-1][w-weights[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
# The maximum value that can be put in a knapsack of capacity W
print(f"Maximum value in knapsack: {dp[n][capacity]}")
QUESTION 3
import itertools
# Create a function to calculate the minimum cost
def tsp(graph, s):
n = len(graph)
all_sets = []
g = {}
p = []
for x in range(1, n):
g[x + 1, ()] = graph[x][0]
def get_minimum(k, a):
if (k, a) in g:
return g[k, a]
values = []
all_min = []
for j in a:
set_a = list(a)
set_a.remove(j)
all_min.append([graph[k - 1][j - 1] + get_minimum(j, tuple(set_a)), j])
g[k, a] = min(all_min)[0]
p.append((k, a, min(all_min)[1]))
return min(all_min)[0]
a = tuple(range(2, n + 1))
res = get_minimum(1, a)
# Follow path to find solution
print(f"Minimum cost: {res}")
print("Path: ", end='')
solution = p.pop()
print("1 ->", end=' ')
for x in range(len(p)):
for new_solution in p:
if tuple(solution[1]) == new_solution[1] and solution[2] == new_solution[0]:
solution = new_solution
print(solution[0], "->", end=' ')
break
print("1")
# Sample graph as adjacency matrix
graph = [[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]]
tsp(graph, 0)
QUESTION 4
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
# Merge the left and right halves
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
# Checking if any element was left
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
# Sample array
arr = [12, 11, 13, 5, 6, 7]
print("Given array is")
print(arr)
merge_sort(arr)
print("Sorted array is")
print(arr)
QUESTION 5
import heapq
def heuristic(a, b):
# Example heuristic function (Manhattan distance for a grid)
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star_search(graph, start, goal):
open_set = []
heapq.heappush(open_set, (0, start))
came_from = {}
g_score = {node: float('inf') for node in graph}
g_score[start] = 0
f_score = {node: float('inf') for node in graph}
f_score[start] = heuristic(start, goal)
while open_set:
current = heapq.heappop(open_set)[1]
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1] # Return reversed path
for neighbor, cost in graph[current].items():
tentative_g_score = g_score[current] + cost
if tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
heapq.heappush(open_set, (f_score[neighbor], neighbor))
return None # Return None if there is no path
# Example graph as an adjacency list
graph = {
(0, 0): {(0, 1): 1, (1, 0): 1},
(0, 1): {(0, 0): 1, (1, 1): 1},
(1, 0): {(0, 0): 1, (1, 1): 1},
(1, 1): {(0, 1): 1, (1, 0): 1, (2, 2): 2},
(2, 2): {(1, 1): 2}
}
start = (0, 0)
goal = (2, 2)
path = a_star_search(graph, start, goal)
if path:
print("Path found:", path)
else:
print("No path found")
QUESTION 6
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, len(board)), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_n_queens(board, col):
if col >= len(board):
return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1
if solve_n_queens(board, col + 1):
return True
board[i][col] = 0 # Backtrack
return False
def print_board(board):
for row in board:
print(" ".join(str(cell) for cell in row))
def n_queens(n):
board = [[0] * n for _ in range(n)]
if solve_n_queens(board, 0):
print_board(board)
else:
print("No solution exists")
# Example for 8-queens
n_queens(8)