Python Answer Key
Python Answer Key
PART-A
1. The efficiency of an algorithm is analyzed by finding out their space and time complexity. ...
The time and space complexity should be minimum as well as the algorithm should satisfy
all different test cases for a given problem.
3. A compiler is a translator which transforms source language (high-level language) into object
language (machine language). In contrast with a compiler, an interpreter is a program which
imitates the execution of programs written in a source language.
# Driver Function
n=5
print(sumOfSeries(n))
5. No. The Do loop doesn’t have else clause in python. ‘else’ clause is used in While, For, If,
Exception handling methods.
6. L= [‘one’,’two’,’three’,’four’]
for i in range(len(l)):
print(l[i], end =" ")
Output :
One two three four
7. append(): Adds a new entry to the end of the list.
clear(): Removes all entries from the list.
copy(): Creates a copy of the current list and places it in a new list.
extend(): Adds items from an existing list and into the current list.
insert(): Adds a new entry to the position specified in the list.
8. def test2():
return 'abc', 100, [0, 1, 2]
a, b, c = test2()
print(a)
# abc
print(b)
# 100
print(c)
# [0, 1, 2]
10. rename() method is used to rename a file or directory. This method is a part of the os module
and comes extremely handy. Syntax for os.rename() : os.rename(src, dst) : src is source
address of file to be renamed and dst is destination with the new name.
To delete a file, import the OS module, and run its os.remove() function:
Example:Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
PART B
11 a i
Advantages of Python
Compared to other programming languages Python is the most broadly applied by the
developers lately. Within the next paragraphs, we will take a look at the advantages of Python
programming language for developers in contrast with other languages.
The main Python language advantages are that it is easy to read and easy to learn. It is
easier to write a program in Python than in C or C++. With this language, you gain the
possibility to think clearly while coding, which also makes the code easier to sustain. Which
reduces the cost for maintenance of the program and seen as one of Python programming
advantages.
Python has some unique characteristics that are valuable for programmers because they
make coding easier. Another advantage of Python programming is that no bug can originate a
segmentation fault.
Disadvantages of Python
As an interpreted language, Python has a slow speed of execution. It is slower than C and
C++ because it works with an interpreter, not the compiler.
The language is seen as less suitable for mobile development and game development. It is
often used on desktop and server, but there are only several mobile applications that were
developed with Python. Another disadvantage Python has is the runtime error. The language has
a lot of design limits and needs more testing time. The programmer has the possibility to see
bugs only during run time. Python has high memory consumption and is not used in web
browsers because it is not secure. Language flexibility is considered among both advantages and
disadvantages of Python.
Developers like Python for its simplicity in learning and coding, so much that it might be
difficult for some of them to learn and use other languages.In spite of all the disadvantages of
Python programming language, it has a lot more pros than cons.
11 a ii
int findIndex(int n)
{
// if Fibonacci number is less than 2,
// its index will be same as number
if (n <= 1)
return n;
int a = 0, b = 1, c = 1;
int res = 1;
res++;
a = b;
b = c;
}
return res;
}
int main()
{
int result = findIndex(21);
printf("%d\n", result);
}
Output
8
11 b i
A recursive function is a function defined in terms of itself via self-referential
expressions. This means that the function will continue to call itself and repeat its behavior until
some condition is met to return a result.
Advantages of Recursion:
1. Reduce unnecessary calling of function. 2. Through Recursion one can Solve problems in
easy way while its iterative solution is very big and complex.For example to reduce the code size
for Tower of Honai application, a recursive function is bet suited.
Slow.
Logical but difficult to trace and debug.
Requires extra storage space. For every recursive calls separate memory is
allocated for the variables.
Recursive functions often throw a Stack Overflow Exception when processing or
operations are too large.
BASIS FOR
RECURSION ITERATION
COMPARISON
Condition If the function does not converge If the control condition in the
to some condition called (base iteration statement never become
BASIS FOR
RECURSION ITERATION
COMPARISON
Infinite Repetition Infinite recursion can crash the Infinite loop uses CPU cycles
system. repeatedly.
Size of Code Recursion reduces the size of the Iteration makes the code longer.
code.
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p=2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
prime[0]= False
prime[1]= False
for p in range(n + 1):
if prime[p]:
print p,
if __name__=='__main__':
n = 30
print "Following are the prime numbers smaller",
print "than or equal to", n
SieveOfEratosthenes(n)
Output:
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29
12a i
return output_list
# Driver Code
rotate_num = 3
list_1 = [1, 2, 3, 4, 5, 6]
print(rightRotate(list_1, rotate_num))
Output :
[4, 5, 6, 1, 2, 3]
12a ii
When we call a function with some values, these values get assigned to the arguments according
to their position. ... Python allows functions to be called using keyword arguments. When we
call functions in this way, the order (position) of the arguments can be changed.
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
Python Default Arguments
In python can provide a default value to an argument by using the assignment operator
(=). Here is an example. ... In this function, the parameter name does not have a default value
and is required (mandatory) during a call. On the other hand, the parameter msg has
a default value of "Good morning!" .
12b i
def Nmaxelements(list1, N):
final_list = []
for i in range(0, N):
max1 = 0
for j in range(len(list1)):
if list1[j] > max1:
max1 = list1[j];
list1.remove(max1);
final_list.append(max1)
print(final_list)
# Driver code
list1 = [2, 6, 41, 85, 0, 3, 7, 6, 10]
N=2
i) def triangle(s1,s2,s3):
if ((s1+s2)>s3):
print("NO. Not possible to form a triangle")
else:
print("Yes. Possible to form a triangle")
s1=int(input("Enter s1"))
s2=int(input("Enter s2"))
s3=int(input("Enter s3"))
triangle(s1,s2,s3)
OUTPUT:
Enter s13
Enter s25
Enter s310
Yes. Possible to form a triangle
ii) def triangle():
s1=int(12)
s2=int(12)
s3=int(12)
if(s1==s2==s3):
print("Pssible to form triangle")
else:
print("Not possible to from triangle")
triangle()
13.a)ii)
from itertools import permutations
def allPermutations(str):
permList = permutations(str)
OUTPUT:
ABC
ACB
BAC
BCA
CAB
CBA
13.b)i)
Python has two data structures, lists and tuples, that consist of a list of one or more
elements. The elements of lists or tuples can be numbers or strings, or both. Lists (we will
discuss tuples later) are defined by a pair of square brackets on either end with individual
elements separated by commas.
L1=[1,2,354,6]
L2=[1,’a’,4.6]
Python lists can store values of different data types. But, arrays in python can only store
values of same data type. Array is not a fundamental data type in Python. So, the standard ‘array’
module has to be imported as:
from array import *
Then an array has to be declared as:
arrayID = array(typecode, [Initializers])
Here, ‘arrayID’ is the name of an array, ‘typecode’ is the type of array and ‘Initializers’ are
the values with which an array is initialized.
Example:
my_array = array(‘i’,[1,2,3,4])
Sample Code
from array import *
myArray = array(‘i’, [1,2,3])
for i in myArray:
print i
Sample Output:
1
2
3
13.b)ii)
14 a) i) Define Dictionary in python. Initialize two dictionaries with key and value pairs.
Dictionary is one of the compound data type like string, list and tuple.
In dictionary the index can be immutable data type.
It is a set of zero or more ordered pairs(key, value) such that:
o The value can be any type.
o Each key may occur only once in the dictionary
o No key may be mutable. A key may not be a list or tuple or dictionary and so on.
A dictionary is set of pairs of value with each pair containing a key and an item and is
enclosed in curly brackets.
There are two ways to create dictionaries.
o It is created by specifying the key and value separated by a colon(:) and the
elements separated by commas and entire set of elements must be enclosed by
curly braces.
o dict() constructor that uses a sequence to create dictionary.
Example.py
d1={1:'fruit',2:'vegetables',3:'cereals'}
d2=dict({'name':'aa','age':40})
print(d1[1])
print(d2)
Output:
fruit
{'name': 'aa', 'age': 40}
ii) Compare the two dictionaries with master key list and print missing keys.
In python, dictionaries are containers which map one key to its value with access time
complexity to be O(1). But in many applications, the user doesn’t know all the keys present in
the dictionaries. In such instances, if user tries to access a missing key, an error is popped
indicating missing keys.
import collections
defd = collections.defaultdict(lambda : 'Key Not found')
defd['a'] = 1
defd['b'] = 2
print ("The value associated with 'a' is : ",end="")
print (defd['a'])
# printing value associated with 'c'
print ("The value associated with 'c' is : ",end="")
print (defd['c'])
Output :
3 The list is better for performing Tuple data type is appropriate for accessing the
operations, such as insertion and elements
deletion.
4 Lists consume more memory Tuple consume less memory as compared to the list
5 Lists have several built-in methods Tuple does no have must built-in methods.
6 The unexpected changes and errors are In tuple, it is hard to take place.
more likely to occur
15. a) i) What are exceptions? Explain the methods to handle them with example.
The try: block, include an except: statement, followed by a block of code which handles
the problem as elegantly as possible.
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
15 a) ii) Write a python program to count the number of words in a text file.
from collections import Counter
fn=input("enter the file name")
c=open(fn,"r")
print("no. of words in the file")
print(Counter(c.read().split()))
c.close()
Output:
enter the file namee:/source.txt
no. of words in the file
Counter({'welcome': 1, 'to': 1, 'python': 1, 'i': 1, 'am': 1, 'using': 1, 'module': 1})
import os
file_names = os.listdir(‘DirectoryNameWithAllTweets/’)
output = ‘’
for file in file_names:
with open(file) as f:
content = f.read().strip(‘\n’)
output += content + ‘\t0\n’
with open(‘OutputFileName’, ‘wb’) as f:
f.write(output)
15) b) ii) What are modules in python? How will you import them? Explain the concept by
creating and importing a module.
A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python object
with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Types of modules:
1. Pre-defined modules
2. User-defined modules
Pre-defined modules
These modules are already defined in Python package itself.
Example: math,random,calendar,os,sys,numpy,string etc.,
Example.py
import math
print(math.sqrt(16))
print(math.pi)
Output:
4
3.1467
User-defined modules
These modules are created by the user.
User has to write function definitions in a file and give a name with an extension .py
Then is name used in python program along with import keyword.
But first this module file has to be executed before the execution of python program.
Example (calc.py)
def add(a,b)
c=a+b
return c
def sub(a,b)
c=a-b
return c
def mul(a,b)
c=a*b
return c
def div(a,b)
c=a/b
return c
def mod(a,b)
c=a%b
return c
main.py
import calc
print(calc.add(4,2))
print(calc.sub(4,2))
print(calc.mul(4,2))
print(calc.div(4,2))
print(calc.mod(4,2))
Output:
6
2
8
2
0
1. The import Statement
Python source file can be used as a module by executing an import statement in some
other Python source file.
Syntax: import module1, module2, module n
Example: import calendar
2. The from...import Statement
Python's from statement lets you import specific attributes from a module into the current
namespace.i.e only when some methods are needed from a module.
Syntax: from modname import name1, name2, ... name n
Example: from calc import add
3. Aliasing Modules
It is also possible to give another name to the existing modules.
This is done using ‘as’ keyword.
Syntax: import module_name as another_name
Example: import math as m