0% found this document useful (0 votes)
7 views14 pages

AL3391_AI_Answer_Key_final[1]

The document contains the answer key for the B.E/B.Tech Degree Examinations in Artificial Intelligence and Data Science for the Third Semester, focusing on Problem Solving and Python Programming. It includes questions and answers related to algorithms, Python operators, data types, recursion, and searching algorithms, providing a comprehensive overview of essential programming concepts. The document is structured in two parts, with Part A consisting of short answer questions and Part B containing detailed explanations and examples.

Uploaded by

rajeshwaris
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)
7 views14 pages

AL3391_AI_Answer_Key_final[1]

The document contains the answer key for the B.E/B.Tech Degree Examinations in Artificial Intelligence and Data Science for the Third Semester, focusing on Problem Solving and Python Programming. It includes questions and answers related to algorithms, Python operators, data types, recursion, and searching algorithms, providing a comprehensive overview of essential programming concepts. The document is structured in two parts, with Part A consisting of short answer questions and Part B containing detailed explanations and examples.

Uploaded by

rajeshwaris
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/ 14

B.E/B.

Tech Degree Examinations –NOV/DEC 2024


Artificial Intelligence and Data Science

Third Semester

23GE102 & Problem Solving & Python Programming

(NPRCET Regulation 2023)

ANSWER KEY

QP Code :2324GE152 Date of Exam : 07/01/2024

K
-
L
PART A (10x2=20 Marks) Marks CO
e
v
el
Write an algorithm to find the sum of first ‘N’ natural 2 K CO1
numbers. 1
Algorithm:
1. Start
1. 2. Read the value of N
3. Compute sum = N * (N + 1) / 2
4. Print sum
5. Stop

2. List the types of operators available in Python with 2 K CO1


examples. 1

Types of operators in Python:

 - Arithmetic Operators (+, -, *, /, //, %, **)


 - Relational (Comparison) Operators (==, !=, >, <, >=,
<=)
 - Logical Operators (and, or, not)
 - Assignment Operators (=, +=, -=, *=, etc.)
 - Bitwise Operators (&, |, ^, ~, <<, >>)
 - Membership Operators (in, not in)
 - Identity Operators (is, is not)

Write a simple script to display "Hello World" in Python 2 K CO2


interpreter. 1
3.
print("Hello World")

Define Identifiers with an example. 2 K CO2


1
Identifiers are the names used to identify variables, functions,
classes, etc., in Python.
4.
Example:
x = 10 # 'x' is an identifier

Illustrate the use of * and + operators in string with an 2 K CO3


example. 2
str1 = "Hello"
5. str2 = "World"
print(str1 + " " + str2) # Output: Hello World
print(str1 * 3) # Output: HelloHelloHello

Define Fruitful Function 2 K CO3


1
A Fruitful Function is a function that returns a value after
execution. Example:
6.
def add(a, b):
return a + b
Compare list and tuple: 2 K CO4
2
 List: Mutable, allows changes (add, remove, modify
elements), uses [].
 Tuple: Immutable, cannot be modified after creation,
uses ().
7.
Example:
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

8. Let list=['a', 'b', 'c', 'd', 'e', 'f']. Find the following: 2 K CO4
- List[1:3]: ['b', 'c'] 2
- List[:4]: ['a', 'b', 'c', 'd']
- List[::3]: ['a', 'd']

Define relative path and absolute path with respect to files: 2 K CO5
1
 Absolute Path: Complete directory path from root.
9.
 Relative Path: Path relative to the current working
directory.

Differentiate binary file and text file: 2 K CO5


1
 Binary files store data in binary format (e.g., images,
10.
videos).
 Text files store data in human-readable characters.

Part B(5x13=65Marks)

11. a Explain the building blocks of algorithms in detail. 16 K3 CO1


Algorithms are step-by-step procedures designed to
solve specific problems. The main building blocks of
algorithms include input, output, definiteness, finiteness,
effectiveness, and the steps involved.
1. Input: Algorithms must take some data as input
to begin execution. This data is provided
externally by the user or is extracted from a
database. For instance, in a sorting algorithm, the
input is the list of numbers to be sorted.
2. Output: Every algorithm is designed to produce
one or more outputs. The output is the result
obtained after processing the input data. For
example, in a sorting algorithm, the output is the
sorted list.
3. Definiteness: Each step of an algorithm must be
clearly defined and unambiguous. This ensures
that the algorithm can be implemented precisely
without confusion. For instance, specifying "add
1 to x" is unambiguous, whereas "increase x"
can be confusing.
4. Finiteness: Algorithms must terminate after a
finite number of steps. If an algorithm goes into
an infinite loop, it cannot be considered a valid
algorithm. Finiteness ensures that the process
concludes with a result.
5. Effectiveness: Every step in an algorithm should
be simple enough to be executed by a computer
or a human. This property ensures that the
algorithm is feasible.
6. Steps (Flow): The steps in an algorithm can
include:
o Sequence: A series of actions performed
in order.
o Decision-making: Involves conditional
statements like "if-else."
o Iteration: Repetition of steps using loops
(e.g., for or while).
Algorithms also rely on concepts like modularity
(breaking down the problem into sub-problems) and
efficiency (measured in terms of time and space
complexity). A good algorithm is efficient, reliable, and
optimized for the problem it addresses.
For example, consider an algorithm for adding two
numbers:
1. Input two numbers.
2. Add the numbers.
3. Print the result.
This basic algorithm illustrates how the building
blocks come together in a logical manner to
achieve a goal.

OR
11 b (i)What is recursion? Write an algorithm to solve the 8 K3 CO1
Towers of Hanoi problem using recursion.
Recursion is a technique where a function calls itself to
solve smaller instances of a problem until it reaches a
base case. It is a fundamental concept in computer
science that simplifies problems by breaking them into
sub-problems. A recursive function has two main parts:
1. Base Case: This stops the recursion when a
specific condition is met.
2. Recursive Case: This is where the function calls
itself to solve a smaller part of the problem.
Algorithm for the Towers of Hanoi:
The Towers of Hanoi is a classic problem involving
three rods and n disks of different sizes, which must be
moved from the source rod to the destination rod,
following these rules:
1. Only one disk can be moved at a time.
2. No larger disk can be placed on top of a smaller
disk.
3. A temporary auxiliary rod can be used to
facilitate the process.
The algorithm to solve the problem using recursion:
1. Move n-1 disks from the source rod to the
auxiliary rod.
2. Move the nth disk from the source rod to the
destination rod.
3. Move n-1 disks from the auxiliary rod to the
destination rod.
Pseudocode:
ToH(n, source, destination, auxiliary):
If n == 1:
Print "Move disk 1 from source to destination"
Return
ToH(n-1, source, auxiliary, destination)
Print "Move disk", n, "from source to destination"
ToH(n-1, auxiliary, destination, source)
For example, with 3 disks, the function calls itself to
move smaller subsets of disks between the rods until the
base case is reached. Towers of Hanoi showcases the
elegance and efficiency of recursion in problem-solving,
as the recursive calls systematically break the problem
into manageable components.
11 b (ii) Draw a flowchart to check whether the string is 8 K2 CO1
palindrome or not.
A palindrome is a string that reads the same forward and
backward.
Steps for the Flowchart:
1. Start.
2. Input the string.
3. Reverse the string using a function or manual
method.
4. Compare the original string with the reversed
string.
o If both are equal, print “Palindrome.”
o Else, print “Not a Palindrome.”
5. End.
12 a Outline the data types supported by Python with an 16 K2 CO2
example.
Python supports a variety of data types, each tailored for
specific purposes. These are broadly categorized into
numeric, sequence, text, set, mapping, and boolean
types.
1. Numeric Types:
o int: Represents whole numbers.
Example: a = 10
o float: Represents decimal numbers.
Example: b = 3.14
o complex: Represents complex numbers
with real and imaginary parts.
Example: c = 3 + 4j
2. Sequence Types:
o list: A mutable collection of elements.
Example: lst = [1, 2, 3]
o tuple: An immutable collection of
elements.
Example: tup = (1, 2, 3)
o range: Represents a sequence of
numbers.
Example: r = range(5) gives 0, 1, 2, 3, 4.
3. Text Type:
o str: Represents a string of characters.
Example: s = "Hello"
4. Set Types:
o set: An unordered collection of unique
elements.
Example: st = {1, 2, 3}
o frozenset: An immutable version of a set.
5. Mapping Type:
o dict: Represents key-value pairs.
Example: d = {'a': 1, 'b': 2}
6. Boolean Type:
o bool: Represents True or False.
Example: is_active = True
Python’s flexibility with data types makes it ideal for
various applications. These data types are not only used
for storing data but also provide numerous methods for
data manipulation, such as sorting a list, accessing
dictionary values, or concatenating strings. Python’s
dynamic typing further allows variables to change their
data types during execution, enhancing its adaptability
for complex tasks.
OR

12 b (i)Elaborate on membership, identity, and bitwise 8 K2 CO2


operators of Python with suitable examples.
Membership Operators:
 in: Checks if a value is present in a sequence.
list1 = [1, 2, 3, 4]
print(2 in list1) # True
print(5 in list1) # False
 not in: Checks if a value is not present in a
sequence.
print(5 not in list1) # True
Identity Operators:
 is: Compares if two variables point to the same
object.
x = [1, 2, 3]
y=x
print(x is y) # True
 is not: Checks if two variables do not point to
the same object.
z = [1, 2, 3]
print(x is not z) # True
Bitwise Operators:
 &: Bitwise AND
print(5 & 3) # 1 (0101 & 0011)
 |: Bitwise OR
print(5 | 3) # 7 (0101 | 0011)
 ^: Bitwise XOR
print(5 ^ 3) # 6 (0101 ^ 0011)
 ~: Bitwise NOT
print(~5) # -6
 <<: Left shift
print(5 << 1) # 10
 >>: Right shift
print(5 >> 1) # 2
12 b (ii) Python program to find the factorial of N 8 K3 CO2
numbers.
The factorial of a number N is the product of all positive
integers from 1 to N. Mathematically, N! = N × (N-1)
× ... × 1.
Program:
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

# Input
num = int(input("Enter a number: "))
print(f"The factorial of {num} is {factorial(num)}")
Example:
Input: 5
Output: The factorial of 5 is 120
13 a Describe the conditional branching statements of 16 K3 CO3
Python with an example program.
Conditional Branching in Python:
1. if Statement: Executes a block of code if the
condition is true.
if condition:
# Block of code
2. if-else Statement: Executes one block if the
condition is true and another block if it is false.
if condition:
# Block of code if true
else:
# Block of code if false
3. if-elif-else Statement: Checks multiple
conditions and executes the block corresponding
to the first true condition.
if condition1:
# Block of code for condition1
elif condition2:
# Block of code for condition2
else:
# Block of code if none are true
Example Program:
# Determine if a number is positive, negative, or zero
num = int(input("Enter a number: "))

if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Explanation of the Program:
 The user inputs a number.
 The program checks if the number is greater
than, less than, or equal to zero.
 Based on the condition, an appropriate message
is displayed.
Output Example:
Input: 7
Output: The number is positive.
OR

13 b Write a Python program for linear search and 16 K3 CO3


binary search and explain its implementation in
detail.
Linear search and binary search are two fundamental
searching algorithms. While linear search is
straightforward, binary search is more efficient for
sorted datasets.
Linear Search:
Linear search involves checking each element of the list
sequentially until the desired element is found or the end
of the list is reached.
def linear_search(arr, key):
for i in range(len(arr)):
if arr[i] == key:
return i
return -1
# Example:
arr = [3, 5, 2, 1, 7]
key = 5
result = linear_search(arr, key)
print("Element found at index:", result)
Linear search has a time complexity of O(n), as it
examines each element. It is simple but inefficient for
large datasets.
Binary Search:
Binary search, on the other hand, works only on sorted
datasets. It divides the dataset into halves, comparing
the middle element with the target. Based on the
comparison, it either narrows the search to the left or
right half.
def binary_search(arr, key):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == key:
return mid
elif arr[mid] < key:
low = mid + 1
else:
high = mid - 1
return -1
# Example:
arr = [1, 2, 3, 4, 5]
key = 4
result = binary_search(arr, key)
print("Element found at index:", result)
Binary search is highly efficient with a time complexity
of O(log n). While linear search is versatile, binary
search is the better choice for sorted data.

14 a Explain in detail about lists, list operations, and list 16 K3 CO4


slices with an example.
A list in Python is an ordered, mutable collection that
can hold elements of different data types. It is defined
using square brackets []. Lists allow operations like
addition, removal, slicing, and iteration.
1. Creating a List:
my_list = [1, 2, 3, 4, 5]
2. Common List Operations:
o Appending an element:
my_list.append(6) # [1, 2, 3, 4, 5, 6]
o Inserting an element:
my_list.insert(2, 99) # [1, 2, 99, 3, 4, 5, 6]
o Removing an element:
my_list.remove(99) # [1, 2, 3, 4, 5, 6]
o Sorting:
my_list.sort() # [1, 2, 3, 4, 5, 6]
3. List Slicing:
Slicing retrieves a subset of the list using the
start:stop:step format.
sliced_list = my_list[1:4] # [2, 3, 4]
reverse_list = my_list[::-1] # [6, 5, 4, 3, 2, 1]
Lists are highly versatile, making them suitable for
various data-handling tasks in Python.
OR

14 b Explain the following: 16 K4 CO4


1. Creating a dictionary
2. Adding items into the dictionary
3. Accessing the dictionary
4. Printing the dictionary
A dictionary in Python is a collection of key-value
pairs, defined using {}. Each key must be unique.
1. Creating a Dictionary:

my_dict = {"name": "Alice", "age": 25}

2. Adding Items:

my_dict["city"] = "New York" # {"name": "Alice",


"age": 25, "city": "New York"}

3. Accessing Items:

name = my_dict["name"] # "Alice"

4. Printing a Dictionary:

print(my_dict) # {"name": "Alice", "age": 25, "city":


"New York"}

Dictionaries are efficient for fast lookups and are widely


used in Python programming.

15 a Explain the purpose of creating, reading, and 16 K3 CO5


appending a text file in Python.

File handling in Python enables working with text files


to store and retrieve data. Common modes include:
 'w' (write): Overwrites the file or creates a new
one.
 'r' (read): Reads the file.
 'a' (append): Adds content to the file without
overwriting.
1. Creating and Writing:
with open("example.txt", "w") as file:
file.write("Hello, World!")
2. Reading:
with open("example.txt", "r") as file:
content = file.read()
print(content)
3. Appending:
with open("example.txt", "a") as file:
file.write("\nWelcome to Python!")
Text file operations are critical for persistent data
storage.
OR

15 b Explain about CSV file/module in Python with a 16 K4 CO5


suitable example.

The CSV (Comma-Separated Values) module in Python


simplifies reading and writing tabular data.
1. Reading a CSV File:
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
2. Writing to a CSV File:
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
The CSV module is useful for handling structured data
efficiently.

Faculty-in-charge
HoD(i/c)/AI&DS

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy