0% found this document useful (0 votes)
7 views

UNIT III QB

Uploaded by

Deepika V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

UNIT III QB

Uploaded by

Deepika V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022

GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING


QUESTION BANK

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS

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)

1. Define Boolean Expression with example.


A Boolean expression is an expression that is either true or false. The values true and false are called boolean
values. The following examples use the operator “==” which compares two operands and produces True if
they are equal and False otherwise:
Example :>>> 5 == 6
False
True and False are special values that belongs to the type bool; they are not strings.

2. What are the different types of operators?


• Arithmetic Operator (+, -, *, /, %, **, // )
• Relational operator ( == , !=, <>, < , > ,<=, >=)
• Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
• Logical Operator (AND, OR, NOT)
• Membership Operator (in, not in)
• Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary left shift), >>
(binary right shift))
• Identity(is, is not)

3. Explain modulus operator with example.


The modulus operator works on integers and yields the remainder when the first operand is divided by the
second. In Python, the modulus operator is a percent sign (%). The syntax is the same as for other operators:
Example:
>>> remainder = 7 % 3
>>> print remainder
1
So 7 divided by 3 is 2 with 1 left over.

4. Explain ‘for loop’ with example.


for loops are traditionally used when you have a block of code which you want to repeat a fixed number of
times. he Python for statement iterates over the members of a sequence in order, executing the block each
time.
The general form of a for statement is
Syntax:
for variable in sequence:
code block
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022

Example:
x=4
for i in range(0, x):
print i

Output: 0 1 2 3

5. Explain relational operators.


The == operator is one of the relational operators; the others are:
X! = y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

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!'

10. What is a continue statement?


The continue statement works somewhat like a break statement. Instead of forcing termination, it forces the
next iteration of the loop to take place, skipping any code in between.
Example:
for num in range(2,10):
if num%2==0:
print “Found an even number”, num
continue
print “Found a number”, num

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.

Return Value Composition


Return gives back or replies to the caller of the Calling one function from another is called
function. The return statement causes your composition.
function to exit and hand back a value to its caller.
Example:
Example: def circle_area(xc, yc, xp, yp):
def area(radius): radius = distance(xc, yc, xp, yp)
temp = math.pi * radius**2 result = area(radius)
return temp return result

13. Define string immutability.


Python strings are immutable. ‘a’ is not a string. It is a variable with string value. You can’t mutate the
string but can change what value of the variable to a new string.

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

14. Explain about string module.


The string module contains number of useful constants and classes, as well as some deprecated legacy
functions that are also available as methods on strings.
Example:

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”)

16. Compare string and string slices.


String :
A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg: >>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

17. Mention a few string functions.


s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string

18. What are string methods?


A method is similar to a function. It takes arguments and returns a value. But the syntax is different. For
example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper()
>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

19. Write a Python program to accept two numbers, multiply them and print the result. (Jan-2018)

print(“Enter two numbers”)


val1=int(input())
val2=int(input())
prod=val1*val2
print(“The product of the two numbers is:”,prod)

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

21. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.
Example:
def bar():
pass
If the function bar() is called, it does absolutely nothing.
22. What is range() function?
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates arithmetic progressions:
Example:
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)

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.

23. Define Fruitful Function.


The functions that return values, is called fruitful functions. The first example is area, which returns the area
of a circle with the given radius:
def area(radius):
area_circle = 3.14159 * radius**2
return area_circle

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.

24. What is dead code?


Code that appears after a return statement, or any other place the flow of execution can never reach, is called
dead code.
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022

25. Explain Logical operators


There are three logical operators: and, or, and not.
For example,
x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not(x > y) is true if x > y is false, that is, if x is
less than or equal to y. Non-zero number is said to be true in Boolean expressions.
26. Do loop statements have else clauses? When will it be executed? (Nov / Dec 2019)
Loop statements may have an else clause, it is executed when the loop terminates through exhaustion of the
list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a
break statement.

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])

PART B (16 MARKS)


1. Discuss conditional alternative and chained conditional in detail. (Jan 2019)
Ans: Refer Unit III notes page no. 02

2. Explain in detail about iterations.


Ans: Refer Unit III notes page no. 06

3. Explain in detail about Fruitful Functions.


Ans: Refer Unit III notes page no. 24

4. Describe in detail about Recursion.


Ans: Refer Unit III notes page no. 31

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

6. Explain string functions and methods in detail.


Ans: Refer Unit III notes page no. 35

7. Write a Python program to find the square root of a number.


Ans: Refer Unit III notes page no. 41

8. a) Write a Python program to find GCD of two numbers.


Ans: Refer Unit III notes page no. 41

b) Write a Python program to find the exponentiation of a number.


Ans: Refer Unit III notes page no.: 42

c) Write a Python program to sum an array of numbers.


Ans: Refer Unit III notes page no.: 43
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022

9. Explain in detail about list as arrays.


Ans: Refer Unit III notes page no. 39

10. a) Write a Python program to perform linear search.


Ans: Refer Unit III notes page no. 44

b) Write a Python program to perform binary search. (Jan 2019)


Ans: Refer 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)

#Factorial with recursion


def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)

n=int(input("Enter the number: ")


result=fact(n)
print("Factorial of",n,"is",result)

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:

def permute(data, i, length):


if i == length:
result.append(''.join(data) )
else:
for j in range(i, length):
data[i], data[j] = data[j], data[i]
permute(data, i + 1, length)
data[i], data[j] = data[j], data[i]

s = input("Enter a string")
print("Initial string", s)
result = []
permute(list(s), 0, len(s))
print("Resultant permutations", str(result))

Output:

Enter a string ads


Initial string ads
Resultant permutations ['ads', 'asd', 'das', 'dsa', 'sda', 'sad']

14. (a) Compare lists and array with example. Can list be considered as an array? Justify. (6) (Nov / Dec
2019)

Ans:
List Array

Can consist of elements belonging Only consists of elements belonging


to different data types to the same data type

No need to explicitly import a Need to explicitly import a module


module for declaration for declaration

Cannot directly handle arithmetic Can directly handle arithmetic


operations operations

Can be nested to contain different Must contain either all nested


type of elements elements of same size

Preferred for shorter sequence of Preferred for longer sequence of data


data items items
GE3151 – Problem Solving and Python Programming Common to all Branches 2021-2022

List Array

Greater flexibility allows easy


modification (addition, deletion) of Less flexibility since addition,
data deletion has to be done element wise

The entire list can be printed A loop has to be formed to print or


without any explicit looping access the components of array

Consume larger memory for easy Comparatively more compact in


addition of elements memory size

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.

import array as arr


import numpy as np

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'>

You might also like