Question Paper Code: 241105
B.E./[Link]. End Semester Theory Examinations, April/May 2024.
First Semester
Computer Science and Engineering
GE 3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to All Branches)
(Regulations 2021)
Time: Three Hours Answer ALL Questions Max. Marks 100
PART - A (10 x 2 = 20 Marks)
1. Write an algorithm to find the greatest of two numbers. [RE]
The algorithm starts by reading two input numbers. It compares the two numbers using a
conditional statement. If the first number is greater, it is displayed as the result. Otherwise, the second
number is displayed as the greatest. The algorithm ends after displaying the result.
Algorithm:
START
Read number1, number2
IF number1 > number2 THEN
Display number1 as the greatest
ELSE
Display number2 as the greatest
END IF
END
2. Give the rules for writing pseudocode. [UN]
Pseudocode should be written in simple and clear English statements. Each instruction should
be written on a separate line in logical order. Keywords like START, IF, and END should be
capitalized. Proper indentation must be used to show the structure of the logic.
3. Compare interpreter and compiler. What type of translator is used for python? [UN]
A compiler translates the entire program into machine code before execution. An interpreter
translates and executes the program line by line. Compilers show errors after compilation, while
interpreters show errors immediately. Python uses an interpreter as its translator.
4. Name the four types of scalar objects in python. [RE]
Scalar objects in Python store single values. The four types of scalar objects are integer, float,
Boolean, and string. These data types are used to store basic values. They do not store multiple
elements like lists or dictionaries.
5. Present the flow of execution for a while statement. [UN]
In a while statement, the condition is checked before entering the loop. If the condition is true,
the loop body is executed. After execution, the condition is checked again. This process continues
until the condition becomes false.
6. Write a python program to accept two numbers, multiply them and print the result. [UN]
The program accepts two numbers from the user using input statements. These values are
multiplied using the multiplication operator. The result is stored in a variable. Finally, the result is
displayed using the print statement.
Code:
# Accept two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Multiply the numbers
result = num1 * num2
# Display the result
print("The result of multiplication is:", result)
7. Relate strings and lists. [UN]
trings and lists are sequence data types in Python. Both support indexing, slicing, and
iteration. Strings are immutable, meaning they cannot be modified. Lists are mutable and allow
modification of elements.
8. What is tuple? Give an example. [RE]
A tuple is an ordered collection of elements enclosed in parentheses. Tuples can store
multiple values of different data types. They are immutable and cannot be changed after creation.
Example: (10, 20, 30).
9. Write the methods to rename and delete files. [RE]
Python provides file management methods through the os module. The rename() method is
used to change the name of a file. The remove() method is used to delete a file permanently. These
methods help manage files effectively.
10. What are packages? [RE]
Packages are collections of related Python modules stored in a directory. They help organize
large programs into a structured format. Packages improve code reusability and maintainability. They
support hierarchical module management.
PART - B (5 x 16 = 80 Marks)
11. a) i) What is recursive function? What are its advantages and disadvantages? [UN] (8)
Recursive Function
A recursive function is a function that calls itself either directly or indirectly to solve a
problem by breaking it into smaller sub-problems. Each recursive call works on a reduced version of
the original problem and stops when a base condition is satisfied. Without a base condition, recursion
leads to infinite calls and program failure.
In Python, recursion is commonly used in problems such as factorial calculation, Fibonacci series,
and Tower of Hanoi. A recursive function must always contain:
1. Base condition – stops recursion
2. Recursive call – function calling itself
Example:
Factorial of n = n × factorial(n−1)
Advantages of Recursive Functions
1. Simplifies complex problems by dividing them into smaller parts
2. Code becomes shorter and easier to understand
3. Suitable for problems with repetitive structure
4. Improves readability for mathematical problems
Disadvantages of Recursive Functions
1. Uses more memory due to function call stack
2. Slower compared to iterative solutions
3. Risk of stack overflow if base condition is incorrect
4. Difficult to debug and trace execution
11. a) ii) Write a recursive algorithm to solve towers of Hanoi problem. [UN] (8)
Tower of Hanoi – Recursive Algorithm
The Tower of Hanoi is a classical problem involving three pegs (Source, Auxiliary, Destination)
and n disks. The objective is to move all disks from the source peg to the destination peg, following
these rules:
1. Only one disk can be moved at a time
2. A larger disk cannot be placed on a smaller disk
Recursive Algorithm
Algorithm: TowerOfHanoi(n, source, auxiliary, destination)
1. If n = 1
o Move disk from source to destination
2. Else
o Move (n−1) disks from source to auxiliary using destination
o Move nth disk from source to destination
o Move (n−1) disks from auxiliary to destination using source
This algorithm continues until the base condition (n = 1) is reached.
OR
11. b) i) Discuss about the building blocks of algorithms. [UN] (8)
Building Blocks of Algorithms
An algorithm is a finite set of well-defined steps used to solve a problem. The fundamental
building blocks of algorithms are:
1. Sequence
o Instructions executed one after another in order
2. Selection (Decision)
o Uses conditions to choose different execution paths
o Example: if, if-else
3. Iteration (Looping)
o Repeats a set of instructions while a condition is true
o Example: for, while
4. Input
o Accepting data from the user or external source
5. Output
o Displaying the result of computation
These blocks help in designing structured, efficient, and understandable algorithms.
11. b) ii) Draw a flowchart to find the factorial of a algorithm [AP] (8)
Logic Explanation:
Factorial of a number n is calculated as:
n! = n × (n−1) × (n−2) × … × 1
Steps:
1. Start
2. Read n
3. Initialize fact = 1
4. While n > 0
o fact = fact × n
o n=n−1
5. Print fact
6. Stop
12. a) i) How do you create a tuple? [UN] (4)
A tuple in Python is created by placing elements inside parentheses (), separated by
commas. Tuples are ordered and immutable.
Example:
t = (10, 20, 30)
Single-element tuple must include a comma:
t = (5,)
12. a) ii) Evaluate the following expressions in python. [AP] (6)
a) 24 // 6% 3
b) float (4+ int (2.39) % 2)
c) 2**2**3
a) 24 // 6 % 3
24 // 6 = 4
4%3=1
b) float(4 + int(2.39) % 2)
int(2.39) = 2
2%2=0
4+0=4
float(4) = 4.0
c) 2 ** 2 ** 3
Exponentiation is right associative
2 ** (2 ** 3) = 2 ** 8 = 256
12. a) iii) Write a python program to exchange the value of two variables. [AP] (6)
Code:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)
OR
12. b) Explain the following with suitable example. [UN] (16)
a) Tuple assignment.
b) Precedence of operators.
a) Tuple Assignment
Tuple assignment is a feature in Python that allows multiple variables to be assigned
values simultaneously using a single statement. Python internally packs the values into a tuple and
then unpacks them into the variables on the left-hand side.
This concept is widely used to:
Swap values without a temporary variable
Assign multiple values in a single line
Improve readability and reduce code length
Syntax
variable1, variable2, ..., variablen = value1, value2, ..., valuen
Example 1: Basic Tuple Assignment
a, b = 10, 20
print(a)
print(b)
Output
10
20
Here, (10, 20) forms a tuple and values are unpacked into a and b.
Example 2: Swapping Two Variables
x=5
y = 10
x, y = y, x
print(x)
print(y)
Output
10
5
This swapping is done without using a temporary variable, which is an important
advantage of tuple assignment.
Advantages of Tuple Assignment
1. Reduces number of statements
2. Improves code readability
3. Avoids use of temporary variables
4. Faster and cleaner implementation
b) Precedence of Operators
Operator precedence defines the order in which operators are evaluated in an expression
when multiple operators are present. Operators with higher precedence are evaluated before operators
with lower precedence.
If operators have the same precedence, associativity determines the evaluation order (left to
right or right to left).
Order of Operator Precedence in Python (High → Low)
1. Parentheses ( )
2. Exponentiation **
3. Multiplication, Division, Floor division, Modulus * / // %
4. Addition, Subtraction + -
5. Relational operators < <= > >= == !=
6. Logical not
7. Logical and
8. Logical or
Example 1: Arithmetic Precedence
result = 10 + 2 * 3
print(result)
Output
16
Explanation:
* has higher precedence than +, so 2 * 3 = 6, then 10 + 6 = 16.
Example 2: Using Parentheses
result = (10 + 2) * 3
print(result)
Output
36
Explanation:
Parentheses override normal precedence.
Importance of Operator Precedence
1. Ensures correct evaluation of expressions
2. Avoids logical errors in programs
3. Improves readability when used with parentheses
4. Essential for writing complex expressions
13. a) i) What is typecasting? Give an example. [UN] (6)
Typecasting
Typecasting is the process of converting one data type into another. In Python, this is done
using built-in functions such as int(), float(), str(), etc. Typecasting is useful when performing
operations on mixed data types or when input values need conversion.
Python supports:
Implicit typecasting – automatically done by Python
Explicit typecasting – done by the programmer
Example:
x = "10"
y = int(x)
print(y + 5)
13. a) ii) Compare lists and array with example. Can list be considered as an array? Justify.
[AP] (16)
Lists vs Arrays
Feature List Array
Data type Can store mixed types Stores same data type
Size Dynamic Fixed
Built-in support Built-in in Python Requires array module
Flexibility High Less flexible
Example – List
L = [10, 2.5, "Python"]
Example – Array
from array import array
A = array('i', [10, 20,
30])
Can a List be Considered as an Array?
Yes, Python lists can be considered as arrays because:
1. Lists store multiple elements under one name
2. They support indexing and iteration
3. Lists are commonly used instead of arrays in Python
However, lists are more powerful than arrays because they allow heterogeneous elements and
dynamic resizing.
OR
13. b) What are the different operators available in python? Explain with examples.
[UN] (16)
Types of Operators in Python
1. Arithmetic Operators
+ - * / % // **
2. Relational Operators
< > <= >= == !=
3. Logical Operators
and, or, not
4. Assignment Operators
= += -= *=
5. Bitwise Operators
& | ^ << >>
6. Membership Operators
in, not in
7. Identity Operators
is, is not
14. a) i) Demonstrate the working of+, * and slice operators in python. [UN] (8)
+ Operator (Concatenation)
a = [1, 2]
b = [3, 4]
print(a + b)
Output:
[1, 2, 3, 4]
* Operator (Repetition)
print([1, 2] * 3)
Output:
[1, 2, 1, 2, 1, 2]
Slice Operator
L = [10, 20, 30, 40, 50]
print(L[1:4])
Output:
[20, 30, 40]
14. a) ii) Write a python program to perform linear search on a list. [UN] (8)
Code:
L = [10, 20, 30, 40, 50]
key = int(input("Enter element to search: "))
found = False
for i in range(len(L)):
if L[i] == key:
print("Element found at position", i)
found = True
break
if not found:
print("Element not found")
OR
14. b) i) Write a python program to add by two matrices. [AP] (10)
Code:
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
C[i][j] = A[i][j] + B[i][j]
print("Sum of matrices:")
for row in C:
print(row)
14. b) ii) How does tuple differ from list? [UN] (8)
List Tuple
Mutable Immutable
Uses [] Uses ()
Slower Faster
Suitable for dynamic data Suitable for fixed data
15. a) Tabulating the different modes for operating a file and explain the same. [AP] (16)
File Opening Modes in Python
Mode Description
r Read only
w Write (overwrites file)
a Append
r+ Read and write
w+ Write and read
a+ Append and read
rb / wb Binary modes
Each mode defines how the file is accessed and prevents data loss when used correctly.
OR
15. b) i) Appraise the use of try block and except block in python with syntax. [AP] (8)
Exception handling prevents abnormal termination of programs.
Syntax:
try:
x = int(input())
except ValueError:
print("Invalid input")
15. b) ii) Explain the commands used to read and write into a file with example. [UN] (8)
Code:
f = open("[Link]",
"w") [Link]("Hello")
[Link]()
f = open("[Link]", "r")
print([Link]())
[Link]()