Python QB With Answers
Python QB With Answers
Python QB With Answers
UNIT I
ALGORITHMIC PROBLEM SOLVING
PART- A (2 Marks)
1. What is an algorithm?(Jan-2018)
Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a
task. It is an English-like representation of the logic which is used to solve the problem. It is a step-by-
step procedure for solving a task or a problem. The steps must be ordered, unambiguous and finite in
number.
2. Write an algorithm to find minimum of three numbers.
ALGORITHM : Find Minimum of three numbers
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A,B and A,C. If A is minimum, perform step 4 else perform step 5.
Step 4:Compare B and C. If B is minimum, output “B is minimum” else output “C is minimum”.
Step 5: Stop
3. List the building blocks of algorithm.
The building blocks of an algorithm are
Statements
Sequence
Selection or Conditional
Repetition or Control flow
Functions
An action is one or more instructions that the computer performs in sequential order (from first to last).
A decision is making a choice among several actions. A loop is one or more instructions that the
computer performs repeatedly.
4. Define statement. List its types.
The instructions in Python, or indeed in any high-level language, are designed as components for
algorithmic problem solving, rather than as one-to-one translations of the underlying machine
language instruction set of the computer. Three types of high-level programming language statements.
Input/output statements make up one type of statement. An input statement collects a specific value
from the user for a variable within the program. An output statement writes a message or the value of a
program variable to the user’s screen.
5. Write the pseudocode to calculate the sum and product of two numbers and display it.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2
COMPUTE sum = number1 + number2
PRINT “The sum is", sum
COMPUTE product = number1 * number2
PRINT “The Product is", product
END program
6. How does flow of control work?
Control flow (or flow of control) is the order in which individual statements, instructions or function
calls of an imperative program are executed or evaluated. A control flow statement is a statement in
which execution results in a choice being made as to which of two or more paths to follow.
7. What is a function?
Functions are named sequence of statements that accomplish a specific task. Functions usually "take
in" data, process it, and "return" a result. Once a function is written, it can be used over and over and
over again. Functions can be "called" from the inside of other functions.
8. Write the algorithm to calculate the average of three numbers and display it.
Step 1: Start
St.Joseph’s Institute of Technology 1
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Step 2: Read values of X,Y,Z
Step 3: S = X+Y+Z
Step 4: A = S/3
Step 5: Write value of A
Step 6: Stop
9. Give the rules for writing Pseudocode.
Write one statement per line.
Capitalize initial keywords.
Indent to show hierarchy.
End multiline structure.
Keep statements language independent.
10. Give the difference between flowchart and pseudocode.
Flowchart Pseudocode
Algorithm is the approach / idea to solve some A program is a set of instructions for the computer
problem. to follow.
28. List the Symbols used in drawing the flowcart. (Apr 2019)
Flowcharts are usually drawn using some standard symbols
Terminator
Process
Decision
Connector
Data
Delay
Arrow
29. Give the python code to find the minimum among the list of 10 numbers. (Apr 2019)
numList = []
n=int(raw_input('Enter The Number of Elements in List :'))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
numList.append(x)
maxNum = numList[0]
for i in numList:
if i > maxNum:
maxNum = i
print('Maximum Element of the Given List is %d' %(int(maxNum)))
-Selection
St.Joseph’s Institute of Technology 5
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The selection structure is the construct where statements can executed or skipped depending on
whether a condition evaluates to TRUE or FALSE. There are three selection structures in C:
1. IF
2. IF – ELSE
3. SWITCH
-Repetition
The repetition structure is the construct where statements can be executed repeatedly until a condition
evaluates to TRUE or FALSE. There are two repetition structures in C:
1. WHILE
2. FOR
Functions:
A function is a block of organized reusable code that is used to perform a single action.
1 The process is repeated until the The function calls itself until the base condition is
condition fails. satisfied.
3 It is faster It is slower
Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop
factorial(n)
Step 1: Initialize f=1,i=1
Step 2: Repeat step 2.1 and 2.2 until i<=n
Step 2.1: f= f*i
Step 2.2: Increment i by 1 (i=i+1)
Step 3: Return f
Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop
factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return f
Flowchart:
St.Joseph’s Institute of Technology 7
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
7. a) Write an algorithm and give the flowchart to find the net salary of an employee.
Algorithm:
Step 1: Start
Step 2: Read the basic salary
Step 3: IF the basic is greater than or equal to 4000 ELSE Goto Step 4
Step 3.1: DA= 0.32 * basic (Dearness Allowance)
Step 3.2: HRA = 0.15 * basic (House Rent Allowance)
Step 3.3: CCA = 325 (City Compensatory Allowance)
Step 3.4: Net Salary = basic +DA + HRA + CCA
Step 4: Print the Net Salary
Step 5: Stop
b) Write an algorithm and give the pseudo code to guess an integer number in a range.
Algorithm:
step 1: Start the program
step 2: Read an 'n' number
step 3: Read an Guess number
step 4: if Guess> n; print "Your Guess too high" Step 5: elif Guess <n ; print "Your Guess
too low" step 6: elif Guess = = n; print "Good job"
Step 7: else print"Nope "
Step :8 Stop the program
Pseudocode:
BEGIN
READ n
READ Guess = 20
IF Guess> n
print"Your Guess too High" elif Guess< n
print "Your Guess too low" elif Guess = = 20
print "Good Job"
ELSE
PRINT "Nope"
Pseudocode:
BEGIN
SET numlist=[ ]
GET n
FOR i=1 to n
GET numlist elements
ENDFOR
SET minimum = numlist[0]
FOR i in numlist
IF (n < minimum)
minimum = n
ENDIF
ENDFOR
PRINT minimum
END
9. a) Draw a flowchart to accept three distinct numbers, find the greatest and print the result.
(Jan 2018 (8 Marks))
St.Joseph’s Institute of Technology 12
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Start
Input a, b, c
yes
no yes yesyes
Output b b>c a>b a>c Output a
no
no
Output c
Stop
b) Draw a flowchart to find the sum of the series 1 + 2 + 3 + 4 + 5 ….. + 100. (Jan 2018 (8
Marks))
Start
SUM = 0
N=0
N=N+1
SUM=SUM + N
no
IS
yes
N=100
PRINT SUM
Stop
10. Outline the Towers of Hanoi problem. Suggest a solution to the Tower of Hanoi problem
with relevant diagrams. (Jan 2018(16 Marks))
Rules:
Only one disk can be moved among the towers at any given time
Only the “top” disk can be removed
No large disk can sit over a small disk
while statement
while
<test_expression>:
<body>
Eg:
def sequence(n):
while n != 1:
print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1
The condition for this loop is n != 1, so the loop will continue until n is 1, which makes
the condition false.
Each time through the loop, the program outputs the value of n and then checks whether
it is even or odd. If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3+1. For
example, if the argument passed to sequence is 3, the resulting sequence is 3,10, 5, 16, 8, 4, 2, 1.
The for Statement
Python’s for statement iterates over the items of any sequence (a list or a string), in the order
that they appear in the sequence.
Eg:
Eg:
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
The working of continue statement in for and while loop is shown below.
Eg:
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
13. (i) What is an algorithm? Summarise the characteristics of a good algorithm. (8) (Apr 2019)
1. What is the role of an interpreter? Give a detailed note on python interpreter and interactive
mode of operation. (or) Sketch the structures of interpreter and compiler. Detail the differences
between them. Explain how Python works in interactive mode and script mode with examples. (Jan
2019)
An interpreter is a computer program that executes instructions written in a programming language. It
can either
• execute the source code directly or
• translates the source code in a first step into a more efficient representation and executes this code
Python interpreter and interactive mode
With the Python interactive interpreter it is easy to check Python commands. The Python interpreter
can be invoked by typing the command "python" without any parameter followed by the "return" key
at the shell prompt:
$ python
>>>
Once the Python interpreter is started, you can issue any command at the command prompt ">>>".
For example,let us print the "Hello World" statement:
St.Joseph’s Institute of Technology 21
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
>>> print "Hello World"
Hello World
In the interactive Python interpreter the print is not necessary:
>>> "Hello World"
'Hello World'
>>> 3
3
Typing an end-of-file character (Ctrl+D on Unix, Ctrl+Z on Windows) at the primary prompt causes
the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by
typing the following command: quit().
When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it
prompts for the next command with the primary prompt, usually three greater-than signs (>>>); for
continuation lines it prompts with the secondary prompt, by default three dots (...). The interpreter
prints a welcome message stating its version number and a copyright notice before printing the first
prompt:
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this
if statement:
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
2. Illustrate values and different standard data types with relevant examples.
VALUES
A value is one of the fundamental things – like a letter or a number – that a program manipulates. Its
types are: integer, float, boolean, strings and lists.
Example: 5 is a integer value, ”hello” is a string value
STANDARD DATATYPES
Python has 5 standard data types.
• Numbers
• String
• List
• Tuple
• Dictionary
Numbers
• Integers, floating point numbers and complex numbers falls under Python numbers category.
• They are defined as int, float and complex class in Python.
Eg.a=5
Strings
• String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings.
• Multi-line strings can be denoted using triple quotes, ''' or """.
Eg. s = "This is a string"
Lists
• List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.
• Lists are mutable.ie. Values can be changed
• Lists are enclosed within the square brackets[ ].
Eg. >>> a = [1, 5.8, 'Hello World']
Tuples
Arithmetic Operators
Arithmetic Operators perform various arithmetic calculations like addition, subtraction,
multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic
calculation in Python like we can use the eval function, declare variable & calculate, or call functions.
Example: For arithmetic operators we will take simple example of addition where we will add two-
digit 4+5=9
x= 4
y= 5
print(x + y)
Similarly, we can use other arithmetic operators like for multiplication(*), division(/), substraction(-),
etc.
Comparison Operators
Example: For comparison operators we will compare the value of x to the value of y and print the
result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we
print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns
false.
x=4
y=5
print(('x > y is',x>y))
Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)
Assignment Operators
Python assignment operators are used for assigning the value of the right operand to the left operand.
Various assignment operators used in Python are (+=, - = , *=, /= , etc.)
Example:
Python assignment operators is simply to assign the value, for example
num1 = 4
num2 = 5
print(("Line 1 - Value of num1 : ", num1))
print(("Line 2 - Value of num2 : ", num2))
Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators in
Python are AND, OR and NOT. For logical operators following condition are applied.
For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
Example:
Here in example we get true or false based on the value of a and b
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
Identity Operators
To compare the memory location of two objects, Identity Operators are used. The two identify
operators used in Python are (is, is not).
Operator is: It returns true if two variables point the same object and false otherwise
Operator is not: It returns false if two variables point the same object and true otherwise
Example:
x = 20
y = 20
if ( x is y ):
print("x & y SAME identity")
y=30
if ( x is not y ):
print("x & y have DIFFERENT identity")
4. What do you mean by rule of precedence? List out the order of precedence and demonstrate
in detail with example. (Jan 2019)(Apr 2019)
When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence. For mathematical operators, Python follows mathematical convention. The acronym
PEMDAS is a useful way to remember the rules,
• Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2)
is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60,
even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4 and 3*1**3 is 3, not 27.
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To
divide by 2π, you can use parentheses or write degrees / 2 / pi.
A function is a named sequence of statements that performs a computation. When you define a
function, you specify the name and the sequence of statements. Later, you can “call” the function by
name.
Types of Function:
1. Built-in function
2. User-defined function
BUILT-IN FUNCTION
Python itself have many built-in functions. Programmers can use that function directly.
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the
function. The result, for this function, is the type of the argument. A function “takes” an argument and
“returns” a result. The result is called the return value.
>>> range()
>>> input()
USER-DEFINED FUCTION
Syntax for Function Definition
def functionname(parameters):
statements
Example
//Function definition
def add(a,b):
return a+b
//Fuction call
add(5,6)
>>> int(3.99999)
3
>>> int(-2.3)
-2
9. a) Write a Python program to check whether a given year is a leap year or not.
# To get year (integer input) from the user
year = int(input("Enter the year"))
if (( year%4 == 0) and (( year%100 == 0 ) and ( year%100 != 0))):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
ii) What are Statement? How are they constructed from variable and expression in Python. (8) (Apr
2019)
Expressions and statements
An expression is a combination of values, variables, and operators.
Eg:
17
x
x + 17
Instructions that a Python interpreter can execute are called statements. A statement is a unit of
code that the Python interpreter can execute. Two kinds of statement: print and assignment.
Eg:
a=1+2+3+\
4+5+6+\
7+8+9
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\).
Example:
>>> remainder = 7 % 3
>>> print remainder
1 #So 7 divided by 3 is 2 with 1 left over.
Example:
def bar():
pass
If the function bar() is called, it does absolutely nothing.
Example:
if x > 0:
print 'x is positive'
Example:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
10. 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
St.Joseph’s Institute of Technology 31
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Example:
x=4
for i in range(0, x):
print i
Composition:
Calling one function from another is called composition.
Example:
def circle_ area(a, b, c, d):
St.Joseph’s Institute of Technology 32
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
radius = distance(a, b, c, d)
result = area(radius)
return result
Example:
a=10
def my_global():
print(“This is global variable”, a)
17. Compare string and string slices.
A string is a sequence of character.
Example: fruit = ‘banana’
String Slices:
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Example:
>>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python
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", replace => Monty Java's Flying Circus
"Java") find => 6 -1
print "find", "=>", string.find(text, "Python"), count => 3
string.find(text, "Java")
print "count", "=>", string.count(text, "n")
22. Write a python program to accept two numbers and find the largest among them.(AU-
JAN’18)
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if (num1 == num2):
print("The numbers are equal")
// Floor Division The division of operands where the 9//2 = 4 and 9.0//2.0 =
result is the quotient in which the digits 4.0
after the decimal point are removed
Eg:
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 statements have the same structure as function definitions: a
header followed by an indented body. Statements like this are called compound statements. There is
no limit on the number of statements that can appear in the body, but there has to be at least one.
Occasionally, it is useful to have a body with no statements .In that case, you can use the pass
statement, which does nothing.
if x < 0:
pass # need to handle negative values!
Eg:
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
St.Joseph’s Institute of Technology 37
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
condition must be true or false, exactly one of the alternatives will be executed. The alternatives are
called branches, because they are branches in the flow of execution.
Chained conditionals(if-elif-else):
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:
Syntax:
if Test_expression:
statement
elif Test_expression:
statement
else:
statement
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.
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them
is true, the corresponding branch executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.
3. Explain in detail about Fruitful Functions.
Return values
Some of the built-in functions we have used, such as the math functions, produce results. Calling the
function generates a value, which we usually assign to a variable or use as part of an expression.
The first example is area, which returns the area of a circle with the given radius:
Eg:
def area(radius):
temp = math.pi * radius**2
return temp
We have seen the return statement before, but in a fruitful function the return statement includes an
expression. This statement means: “Return immediately from this function and use the following
expression as a return value.” The expression can be arbitrarily complicated, so we could have written
this function more concisely:
def area(radius):
return math.pi * radius**2
On the other hand, temporary variables like temp often make debugging easier. Sometimes it is useful
to have multiple return statements, one in each branch of a conditional:
St.Joseph’s Institute of Technology 38
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
def absolute_value(x):
if x < 0:
return -x
else:
return x
5. Explain RECURSION.
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, DFS of Graph, etc.
# take input from the user
num = int(input("Enter a number: "))
def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)
print(“Factorial of n numbers is :%d” %(fact(n)))
Eg:
>>> pathname = ‘/usr/local/bin/ls’
>>> pathname.split(‘/’)
[‘usr’, ‘local’, ‘bin’, ‘ls’]
The inverse of split is the function join. The argument to join is a list of strings. The value to the left
of the dot is the separator that will be placed between each element. Often this is simply an empty
string. The values in the list are laminated along with the separator to produce the result string.
String methods
This form of dot notation specifies the name of the method, upper, and the name of the string to apply
the method to, word. The empty parentheses indicate that this method takes no argument. A method
call is called an invocation ; in this case, we would say that we are invoking upper on the word. As it
turns out, there is a string method named find that is remarkably similar to the function we wrote:
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.
import string
text = "Monty Python's Flying Circus"
print "upper", "=>", string.upper(text)
print "lower", "=>", string.lower(text)
print "split", "=>", string.split(text)
print "join", "=>", string.join(string.split(text), "+")
print "replace", "=>", string.replace(text, "Python", "Java")
print "find", "=>", string.find(text, "Python"), string.find(text, "Java")
print "count", "=>", string.count(text, "n")
Eg: Using string methods instead of string module functions
text = "Monty Python's Flying Circus"
print "upper", "=>", text.upper()
print "lower", "=>", text.lower()
print "split", "=>", text.split()
print "join", "=>", "+".join(text.split())
print "replace", "=>", text.replace("Python", "Perl")
11. Explain with suitable examples the while loop, break statement and continue statement in
python. (AU-JAN’18)
While Loop:
A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
Syntax:
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. When the
condition becomes false, program control passes to the line immediately following the loop.
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)
Break Statement:
Continue Statement:
The continue statement in Python returns the control to the beginning of the while loop.
The continuestatement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
Example1:
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter
Example2:
var = 10
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
12. a) Write a python program to find the factorial of a given number with and without
recursion. (AU-JAN’18)
Without Recursion
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
b) Write a python program to generate the first ‘N’ Fibonacci numbers. (Note: Fibonacci
numbers are 0, 1,1,2,3,5,8… where each number is the sum of the preceding two). (AU-JAN’18)
a=int(input("Enter the first number of the series "))
b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b)
while(n-2):
c=a+b
a=b
b=c
print(c)
n=n-1
UNIT IV
LISTS, TUPLES AND DICTIONARIES
PART- A (2 Marks)
3. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:]
list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
a) list[1:3]
[’b’, ’c’]
Example:
animal = {"cat": 1, "dog": 2}
Lists Dictionary
They maintain their ordering unless explicitly re- Ordering is not guaranteed
ordered (for Example, by sorting the list).
They can be of any type, and types can be mixed. Key values can be of any
hashtable type (i.e. not a dict) and
types can be mixed
They are accessed via numeric (zero based) indices Elements are accessed using key
values.
There is no key and value for each entry Every entry has a key and a value
Output:
>>> numbers = [1, 2, 3]
>>> head(numbers)
13. Give a function that can take a value and return the first key mapping to that value in a
dictionary. (Jan 2019)
a={‘aa’:2, ”bb”:4}
print(a.keys()[0])
14. Write a program in Python returns a list that contains all but the first element of the given
list.
def tail(list):
return list[1:]
numbers = [1, 2, 3]
rest = tail(numbers)
print(rest)
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’
List Creation:
1. days = ['mon', 2]
2. days=[]
days[0]=’mon’
days[1]=2
Negative Indexing:
Example:
>>> print(days[-1])
Output: 2
>>> list[1] = 17
>>> list
[2, 17, 'usurp', 9.0, 'n']
We can assign new values to slices of the lists, which don't even have to be the same length:
It's even possible to append items onto the start of lists by assigning to an empty slice:
Similarly, you can append to the end of the list by specifying an empty slice after the end:
The right-hand side of a list assignment statement can be any iterable type:
With slicing you can create copy of list since slice returns a new list:
Note, however, that this is a shallow copy and contains references to elements from the original list,
so be careful with mutable types:
>>> list_copy[2].append('something')
>>> original
[1, 'element', ['something']]
Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence
of a list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the
slice to be operated upon.
>>> a = list.pop(0)
>>> list
[2, 3, 4]
>>> a
List methods are all void; they modify the list and return None.
LIST LOOPS
Here are two functions that both generate ten million random numbers, and return the sum of the
numbers. They both work.
import random
joe = random.Random()
def sum1():
""" Build a list of random numbers, then sum them """ # Generate one random ˓→number
xs = []
for i in range(10000000):
num = joe.randrange(1000 )
xs.append(num) # Save it in our list
tot = sum(xs)
return tot
def sum2():
""" Sum the random numbers as we generate them """
tot = 0
for i in range(10000000):
num = joe.randrange(1000)
St.Joseph’s Institute of Technology 52
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
tot += num
return tot
print(sum1())
print(sum2())
Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you have to use
a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to
its respective variable. All the expressions on the right side are evaluated before any of the
assignments. The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence
(string, list or tuple). For example, to split an email address into a user name and a domain, you could
write:
>>> addr = '[email protected]'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain.
>>> print uname monty
>>> len(eng2sp)
3
The in operator works on dictionaries; it tells you whether something appears as a key in the
dictionary (appearing as a value is not good enough).
>>> 'one' in eng2sp True
>>> 'uno' in eng2sp False
To see whether something appears as a value in a dictionary, you can use the method values, which
returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values()
>>> 'uno' in vals
True
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search
algorithm, as in Section 8.6. As the list gets longer, the search time gets longer in direct proportion.
For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in
operator takes about the same amount of time no matter how many items there are in a dictionary.
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value
Syntax
The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a
list.
List comprehension is a method to describe the process using which the list should be created. To do
that, the list is broken into two pieces. The first is a picture of what each element will look like, and
the second is what is done to get it.
For instance, let's say we have a list of words:
listOfWords = ["this","is","a","list","of","words"]
To take the first letter of each word and make a list out of it using list comprehension:
List comprehension supports more than one for statement. It will evaluate the items in all of the
objects sequentially and will loop over the shorter objects if one object is longer than the rest.
List comprehension supports an if statement, to only include members into the list that fulfill a certain
condition:
9. Write a Python program for a) selection sort [Anna Univ jan 2018][8m] b) insertion sort.
Selection sort: (Jan 2019)
PROGRAM:
def selectionsort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
St.Joseph’s Institute of Technology 57
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
A[x] = A[y]
A[y] = tmp
aList = [54,26,93,17,77,31,44,55,20]
selectionsort(aList)
print(aList)
Insertion sort:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
10. Write a Python program for a) merge sort b) quick sort.
Merge sort:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
Quicksort:
from random import randrange
def partition(lst, start, end, pivot):
lst[pivot], lst[end] = lst[end], lst[pivot]
store_index = start
for i in xrange(start, end):
if lst[i] < lst[end]:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort(lst, start, end):
if start >= end:
return lst
pivot = randrange(start, end + 1)
new_pivot = partition(lst, start, end, pivot)
quick_sort(lst, start, new_pivot - 1)
quick_sort(lst, new_pivot + 1, end)
def sort(lst):
quick_sort(lst, 0, len(lst) - 1)
return lst
print sort([-5, 3, -2, 3, 19, 5])
print sort([345,45,89,569,23,67,56,90,100])
b) Write a python program to perform linear search in a list. [Anna. Univ. Jan 2018] [8m]
Linear Search:
Linear search or sequential search is a method for finding a target value within a list. It sequentially
checks each element of the list for the target value until a match is found or until all the elements have
been searched
Algorithm:
Step1:Given a list L of n elements with values or records,L0 ... Ln-1 and key/target element K, linear
search is used to find the index/position of the target K in list L
Step2:Initialize a boolean variable found and set it to False initially
Step3:Start for loop with i ranging from 0 to the length of the list
Step4:Check if key element is equal to L[i]
Step5:if equals set found boolean variable to True print the position of the element found
UNIT V
FILES, MODULES AND PACKAGES
PART- A (2 Marks)
3. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes two
arguments: the exception type and specific information about the error.
5. What are the error messages that are displayed for the following exceptions?
a. Accessing a non-existent list item
b. Accessing a key that isn’t in the dictionary
c. Trying to open a non-existent file
a. IndexError: list index out of range
b. KeyError: what
c. IOError: [Errno 2] No such file or directory: 'filename'
12. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
try:
// try block code
except:
// except block code
Example:
try:
print "Hello World"
except:
print "This is an error message!"
15. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called _ _init_ _.py.
_ _init_ _.py can be an empty file but it is often used to perform setup needed for the package import
things, load things into path, etc.
17. Write a Python script to display the current date and time. (AU - Jan 2018)
import datetime
print(“date and time”, datetime.datetime.now())
18. What are modules? (or) Write a note on modular design. Give example. (AU - Jan 2018,
Jan 2019)
Modules are files containing Python definitions and statements (ex: name.py)
Modules can contain executable statements along with function definitions.
Each module has its own private symbol table used as the global symbol table all functions in the
module.
Modules can import other modules.
Syntax:
import <modulename>
Example:
import os
Example:
import os
os.remove("ChangedFile.csv")
print("File Removed!")
21. How do you use command line arguments to give input to the program? (AU - May 2019)
In python, sys module provides access to any command-line arguments via sys.argv.
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Example:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
26. Categorise the different types errors arises during programming. Interpret the following
python code (AU - May 2019)
>>>import os
>>>cwd = os.getcwd()
>>>print cwd
Basic types of errors:
Syntax Error:
Raised by the parser when a syntax error is encountered.
Semantic Error:
Raised by the parser when there is logical error in the program.
Here in the above given program, Syntax error occurs in the third line (print cwd)
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(cwd)?\
1. Write a function that copies a file reading and writing up to 50 characters at a time. (or)
Explain the commands used to read and write into a file with example. (AU - Jan 2019)
def copyFile(oldFile, newFile):
f1=open(oldFile,"r")
f2=open(newFile,"w")
while True:
text=f1.read(50)
if (text==""):
break
f2.write(text)
f1.close()
f2.close()
return
copyFile("src.txt","dst.txt")
3. Write a python program to count number of lines, words and characters in a text file. (AU -
May 2019)
def wordCount():
cl=0
cw=0
cc=0
f=open("src.txt","r")
for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
wordCount()
Example:
Program:
import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))
5. Mention the commands and their syntax for the following: get current directory, changing
directory, list, directories and files, make a new directory, renaming and removing directory.
(a)Get current directory: getcwd()
Syntax : import os
os.getcwd()
(a)Changing directory: chdir()
Syntax: os.chdir(‘C:\\Users’)
os.getcwd()
(b)List directories and files: listdir()
Syntax: os.listdir()
(c)Making a new directory: mkdir()
Syntax: os.mkdir(‘Newdir’)
(d)Renaming a directory: rename()
os.rename(‘Newdir’,’Newname’)
os.listdir()
(e)Removing a directory: remove()
os.remove(‘NewName’)
9. Tabulate the different modes for opening a file and briefly explain the same. (16) (AU - Jan
2018, Jan 2019)
The argument mode points to a string beginning with one of the following sequences (Additional
characters may follow these sequences.):
``r'' Open text file for reading. The stream is positioned at the beginning of the file.
``r+'' Open for reading and writing. The stream is positioned at the beginning of the file.
``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated.
The stream is positioned at the beginning of the file.
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of
the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of
any intervening fseek(3) or similar.
``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned
at the end of the file. Subsequent writes to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.
10. (a) Appraise the use of try block and except block in Python with example. (6) (AU - Jan
2018)
Handling Exceptions
The simplest way to handle exceptions is with a "try-except" block:
St.Joseph’s Institute of Technology 69
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print "divide by zero"
If we want to examine the exception from code, you could have:
Toggle line numbers
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError as e:
z=e
print z
output:
integer division or modulo by zero
(b) Explain with example exceptions with argument in Python. (10) (AU - Jan 2018)
Argument of an Exception
An exception can have an argument, which is a value that gives additional information about the
problem. The contents of the argument vary by exception. You capture an exception's argument by
supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a variable
follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.
Example
Following is an example for a single exception −
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
temp_convert("xyz");
This produces the following result −
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
11. a) Describe how exceptions are handled in python with necessary examples.(8) (AU - Jan
2019, May 2019)
Exception Handling:
When we have a code that can produce error, we can use exception handling. When runtime error occurs,
Python handles the exception avoiding program crash.
Handling a raised exception:
The part of the script that can raise an exception is defined within try block. Following try block, except
statement is given which gets executed if an exception is raised. If no errors are encountered while executing
the try block, except statements are ignored and else statement gets executed. If errors are encountered, else part
is ignored.
Type 1: try…except
try:
#Block that may or may not throw error
except:
#What to do if an error is encountered in try block?
Example:
try:
fp=fopen(‘testfile.txt’, ‘w’)
except:
print(“Error opening the file”)
Output:
CASE 1: #File opened
CASE 2: #File doesn’t open
Error opening the file
Type 2: try…except…else
try:
#Block that may or may not throw error
except <Error1>:
#What to do if Error1 is encountered in try block?
except <Error2>:
#What to do if Error2 is encountered in try block?
….
except <Errorn>:
#What to do if Errorn is encountered in try block?
else:
#What to do if there is no error?
Example:
Output:
CASE 1: #File opened
Success
CASE 2: #File doesn’t open
Error opening the file
Type 3: try…except…else…finally
try:
#Block that may or may not throw error
except:
#Block to handle error
else:
#What to do if there is no error?
finally:
#Always executed
Example:
try:
fp=fopen(‘testfile.txt’, ‘w’)
except:
print(“Error”)
else:
print(“Success”)
fp.close()
finally:
print(“End”)
Output:
CASE 1: #File opened
Success
End
CASE 2: #File doesn’t open
Error
End
In the above three types, a single try statement can contain multiple except statements which is useful when the
try statement can throw different types of exceptions. A generic except clause can be provided to handle any
type of exception.