UNIT III QB
UNIT III QB
SYLLABUS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if- elif-
else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, local and
global scope, function composition, recursion; Strings: string slices, immutability, string functions and methods,
string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array of numbers,
linear search, binary search.
PART- A (2 Marks)
Example:
x=4
for i in range(0, x):
print i
Output: 0 1 2 3
6. Explain while loop with example.(or)Explain flow of execution of while loop with Example.(Jan 2019)
The statements inside the while loop is executed only if the condition is evaluated to true.
Syntax:
while condition:
statements
Example:
# Program to add natural numbers upto, sum = 1+2+3+...+10
n = 10
# initialize sum and counter sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
7. Explain if-statement and if-else statement with example (or) What are conditional and alternative
executions?
If statement:
The simplest form of if statement is:
Syntax:
if (condition):
statement
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement gets
executed. If not, nothing happens.
If-else:
A second form of if statement is alternative execution, in which there are two possibilities and the condition
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022
determines which one gets executed. The syntax looks like this:
Example:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed. Since the condition
must be true or false, exactly one of the alternatives will be executed.
8. What are chained conditionals?
Sometimes there are more than two possibilities and we need more than two branches. One way to express
a computation like that is a chained conditional:
Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the
number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.
9. What is a break statement?
When a break statement is encountered inside a loop, the loop is immediately terminated and the program
control resumes at the next statement following the loop.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print'Done!'
11. What is recursion? (or) Define Recursion with an example.(Jan 2019) (May 2019)
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite
easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals,
Depth First Search (DFS) of Graph, etc.
Example:
def factorial(n):
if n == 1:
return 1
else:
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022
return n * factorial(n-1)
12. Compare return value and composition.
Program: Output:
a = “foo” #foofoo
# a now points to foo #foo
b=a It is observed that ‘b’ hasn’t changed even
# b now points to the same foo that a points to though ‘a’ has changed.
a=a+a
# a points to the new string “foofoo”, but b points to the
same old “foo”
print a
print b
Program: Output:
import string upper=>MONTY PYTHON'S FLYING
text = "Monty Python's Flying Circus" CIRCUS
print "upper", "=>", string.upper(text) lower => monty python's flying circus
print "lower", "=>", string.lower(text) split=>['Monty',"Python's", 'Flying',
print "split", "=>", string.split(text) 'Circus']
print "join", "=>", string.join(string.split(text), "+") join=>Monty+Python's+Flying+Circus
print "replace", "=>", string.replace(text, "Python", "Java") replace => Monty Java's Flying Circus
print "find", "=>", string.find(text, "Python"), string.find(text, find => 6 -1
"Java") count => 3
print "count", "=>", string.count(text, "n")
15. Explain global and local scope. (or) Comment with an example on the use of local and global variable
with the same identifier name. (May 2019)
The scope of a variable refers to the places that you can see or access a variable. If we define a variable on
the top of the script or module, the variable is called global variable. The variables that are defined inside a
class or function is called local variable.
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022
Example:
def my_local():
a=10
print(“This is local variable”)
Example:
a=10
def my_global():
print(“This is global variable”)
19. Write a Python program to accept two numbers, multiply them and print the result. (Jan-2018)
Output:
Enter two numbers
2
3
The product of the two numbers is: 6
20. Write a Python program to accept two numbers, find the greatest and print the result. (Jan-2018)
print(“Enter two numbers”)
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022
val1=int(input())
val2=int(input())
if (val1>val2):
largest=val1
else:
largest=val2
print(“Largest of two numbers is:”,largest)
Output:
Enter two numbers
6
7
Largest of two numbers is: 7
This function does not store all the values in memory, it would be inefficient. So it remembers the start,
stop, step size and generates the next number on the go.
In a fruitful function the return statement includes a return value. This statement means: Return immediately
from this function and use the following expression as a return value.
27. Write a program to display a set of strings using range( ) function (Nov / Dec 2019)
for i in range(len(a)):
print(i,a[i])
5. a). Discuss in detail about string slices and string immutability. (Jan 2019) (or) Analyse String slicing.
Illustrate how it is done in python with example. (May 2019)
Ans: Refer Unit III notes page no. 33
b). Write a python code to search a string in the given list. (May 2019)
Ans: Refer Unit III notes page no. 44
11. a) Appraise with an example nested if and elif header in Python (6) (Jan 2018)
Ans: Refer Unit III notes page no.5
b) Explain with an example while loop, break statement and continue statement in Python. (10) (Jan 2018)
Ans: Refer Unit III notes page no. 10, 14,15
12. a) Write a Python program to find the factorial of the given number without recursion and with recursion. (8)
(Jan-2018)
Ans:
#Factorial without recursion
n=int(input("Enter the number: "))
fact=1
if n<0:
print("factorial doesn't exist for negative numbers")
else:
for i in range(1,n+1):
fact=fact*i
print("factorial of", n, "is", fact)
b) Write a Python program to generate first ‘N’ Fibonacci series numbers. (Note: Fibonacci numbers
are 0,1,1,2,3,5,8… where each number is the sum of the preceding two). (8) (Jan-2018)
Ans:
def Fibonacci(n):
f1 = 0
f2 = 1
if n < 0:
print("Incorrect input")
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022
elif n == 0:
print("0")
elif n == 1:
print("1")
else:
print(f1,end=" ")
for x in range(1,n):
print(f2, end=" ")
term = f1 + f2
f1 = f2
f2 = term
n=int(input("Enter n terms"))
Fibonacci(n)
13. (a) If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if
one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short
sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a
triangle. If any of the three lengths is greater than the sum of the other two, then you cannot form a
triangle. Otherwise, you can. (Nov / Dec 2019)
i) Write a function named is_triangle that takes three integers as arguments, and that prints either “yes” or
“no”, depending on whether you can or cannot form a triangle from sticks with the given lengths. (4)
Ans:
def is_triangle(x, y, z):
if z > (x+y) or y > (x+z) or x > (y+z):
print('No')
else:
print('Yes')
is_triangle(12, 2, 3)
ii) Write a function that prompts the user to input three stick lengths, converts them to integers, and uses
is_triangle to check whether sticks with the given lengths can form a triangle. (4)
Ans:
def is_triangle(x, y, z):
if z > (x+y) or y > (x+z) or x > (y+z):
print('No')
else:
print('Yes')
def triangle():
x = int(input('Please enter the length of the 1st stick:\n'))
y = int(input('Please enter the length of the 2nd stick:\n'))
z = int(input('Please enter the length of the 3rd stick:\n'))
is_triangle(x, y, z)
triangle()
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022
(b) Write a python program to generate all permutations of a given string using built-in function (8) (Nov /
Dec 2019)
Ans:
s = input("Enter a string")
print("Initial string", s)
result = []
permute(list(s), 0, len(s))
print("Resultant permutations", str(result))
Output:
14. (a) Compare lists and array with example. Can list be considered as an array? Justify. (6) (Nov / Dec
2019)
Ans:
List Array
List Array
An array is also a data structure that stores a collection of items. Like lists, arrays are ordered, mutable,
enclosed in square brackets, and able to store non-unique items. But when it comes to the array's
ability to store different data types, the answer is not as straightforward. It depends on the kind of
array used. To use arrays in Python, you need to import either an array module or a NumPy package.
The Python array module requires all array elements to be of the same type. Moreover, to create an
array, you'll need to specify a value type. In the code below, the "i" signifies that all elements in
array_1 are integers:
Code:
array_1 = arr.array("i", [3, 6, 9, 12])
print(array_1)
print(type(array_1))
Output:
array('i', [3, 6, 9, 12])
<class 'array.array'>