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

Python Answer Key

The document discusses recursion and iteration in programming. It provides advantages and disadvantages of recursion, such as reducing unnecessary function calls but being slower than iteration. Recursion uses self-referential calls while iteration uses loops. Recursion risks stack overflow from excessive calls, but can reduce code size for problems well-suited to recursive solutions like towers of Hanoi. Iteration is faster but can make code longer. Overall, recursion and iteration each have trade-offs around speed, overhead, and code size depending on the problem.

Uploaded by

LATHA P
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
811 views

Python Answer Key

The document discusses recursion and iteration in programming. It provides advantages and disadvantages of recursion, such as reducing unnecessary function calls but being slower than iteration. Recursion uses self-referential calls while iteration uses loops. Recursion risks stack overflow from excessive calls, but can reduce code size for problems well-suited to recursive solutions like towers of Hanoi. Iteration is faster but can make code longer. Overall, recursion and iteration each have trade-offs around speed, overhead, and code size depending on the problem.

Uploaded by

LATHA P
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

V.S.

B ENGINEERING COLLEGE, KARUR

Academic Year 2019-2020(ODD Semester)

GE 8151- PROBLEM SOLVING AND PYTHON PROGRAMMING

Nov/Dec 2019 Examination - 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.

2. An algorithm is a set of steps to be followed in solving some particular problem. Flowcharts


and pseudo codes are representations of algorithms. ... For example, a pseudo code for
printing the sum of all numbers between 1 and 100 would be: A flowchart is more of a
diagrammatic representation of the algorithm.

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.

4. Python Program for cube sum of first n natural numbers

Sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term.


Examples:
def sumOfSeries(n):
sum = 0
for i in range(1, n+1):
sum +=i*i*i
return sum

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

9. Python Command Line Arguments. Python Command line arguments are


input parameters passed to the script when executing them. Almost all programming
language provide support for command line arguments. Then we also have command
line options to set some specific options for the program.

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

Python is an interpreted, object-oriented programming language similar to PERL, that


has gained popularity because of its clear syntax and readability. ... Python offers dynamic data
type, ready-made class, and interfaces to many system calls and libraries. It can be extended,
using the C or C++ language.

Types of Programming Languages

 Procedural Programming Language. ...


 Functional Programming Language. ...
 Object-oriented Programming Language. ...
 Scripting Programming Language. ...
 Logic Programming Language. ...
 C++ Language. ...
 C Language. ...
 Pascal Language.

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.

An important advantage of Python language is that it has wide applicability, and is


extensively used by scientists, engineers, and mathematicians. It is for this reason that Python is
so useful for prototyping and all kinds of experiments. It is used in many groundbreaking fields.
It is also used when producing animation for movies and in machine learning.The language
includes a large library with memory management which is another one of the advantages of
Python programming.

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;

// iterate until generated fibonacci number


// is less than given fibonacci number
while (c < n)
{
c = a + b;

// res keeps track of number of generated


// fibonacci number

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.

Disadvantages of Python Recursion

 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

Basic The statement in a body of Allows the set of instructions to be


function calls the function itself. repeatedly executed.

Format In recursive function, only Iteration includes initialization,


termination condition (base case) condition, execution of statement
is specified. within loop and update (increments
and decrements) the control
variable.

Termination A conditional statement is The iteration statement is


included in the body of the repeatedly executed until a certain
function to force the function to condition is reached.
return without recursion call being
executed.

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

case), it leads to infinite recursion. false, it leads to infinite iteration.

Infinite Repetition Infinite recursion can crash the Infinite loop uses CPU cycles
system. repeatedly.

Stack Iteration is applied to iteration Does not uses stack.


statements or "loops".

Overhead Recursion possesses the overhead No overhead of repeated function


of repeated function calls. call.

Speed Slow in execution. Fast in execution.

Size of Code Recursion reduces the size of the Iteration makes the code longer.
code.

Basic The statement in a body of Allows the set of instructions to be


function calls the function itself. repeatedly executed.

Format In recursive function, only Iteration includes initialization,


termination condition (base case) condition, execution of statement
is specified. within loop and update (increments
and decrements) the control
variable.

Termination A conditional statement is The iteration statement is


included in the body of the repeatedly executed until a certain
function to force the function to condition is reached.
return without recursion call being
executed.
11 b ii

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

def rightRotate(lists, num):


output_list = []
# Will add values from n to the new list
for item in range(len(lists) - num, len(lists)):
output_list.append(lists[item])
# Will add the values before
# n to the end of new list
for item in range(0, len(lists) - num):
output_list.append(lists[item])

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.

def func(a, b=5, c=10):


print 'a is', a, 'and b is', b, 'and c is', c

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!" .

def sum(a=4, b=2): #2 is supplied as default argument

""" This function will print sum of two numbers


if the arguments are not supplied
it will add the default value """
print (a+b)
sum(1,2) #calling with arguments
sum( ) #calling without arguments
Output
3

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

# Calling the function


Nmaxelements(list1, N)
Output :
[85, 41]
12.b)ii)
i) 1
ii) 4.0
iii) 256
13.a)i)

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)

for perm in list(permList):


print (''.join(perm))
if __name__ == "__main__":
str = 'ABC'
allPermutations(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.

Here are two examples of lists:

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

Table 3.1 Typescodes in Python arrays


Typecode Description
‘b’ signed integer of size 1 byte
‘B’ unsigned integer of size 1 byte
‘c’ character of size 1 byte
‘u’ unicode character of size 2 bytes
‘h’ signed integer of size 2 bytes
‘H’ unsigned integer of size 2 bytes
‘i’ signed integer of size 2 bytes
‘I’ unsigned integer of size 2 bytes
‘w’ unicode character of size 4 bytes
‘l’ signed integer of size 4 bytes
‘L’ unsigned integer of size 4 bytes
‘f’ floating point of size 4 bytes
‘d’ floating point of size 8 bytes

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)

def check(s1, s2):


if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
s1 ="listen"
s2 ="silent"
check(s1, s2)
Output:
The strings are anagrams

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 :

The value associated with 'a' is : 1


The value associated with 'c' is : Key Not found
iii) Find Keys that are in first and not in second dictionary.
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary
# using a naive approach
rev_dict = {}
for key, value in ini_dict.items():
rev_dict.setdefault(value, set()).add(key)
result = [key for key, values in rev_dict.items()
if len(values) > 1]
# printing result
print("duplicate values", str(result))

iv) Find same keys in two dictionaries


myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
for key in myRDP:
for jey in myNames:
if key == jey:
print key, myNames[key]
V) Merge two dictionaries and create a new dictionary using a single expression.
def Merge(dict1, dict2):
return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# This return None
print(Merge(dict1, dict2))
# changes made in dict2
print(dict2)

14 a) ii) What is list Comprehension in python? Explain with example.


 List comprehension is used to construct lists in an easy and natural way.
 It create a list with a subset of elements from another list by applying condition.
 The list comprehension makes code simpler and efficient.
 The execution is much faster than for loop.
Example.py
x=[i for i in range(10)]
print(x)
x1=[i for i in range(10) if i%2==0]
print(x1)
x2=[i*2 for i in range(10)]
print(x2)
vowels=('a','e','i','o','u')
w="hello"
x3=[ch for ch in w if ch in vowels]
print(x3)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
['e', 'o']

14 b) i) What is tuple in python? How does it differ from list?

 A tuple consists of number of values separated by commas and enclosed within


parentheses.Tuples are similar to lists.Tuples are immutable sequences. The elements in
the tuple cannot be modified.The difference between tuple and lists are the tuple cannot
be modified like lists and tuples use parentheses, whereas list use square brackets.
Example.py
fruits=(‘apple’, ‘orange’)
print(fruits)
Output:
(‘apple’, ‘orange’)

Creating and Accessing tuple


Tuples can be created by putting different values separated by commas and enclosed
within parenthesis.
Example.py
no=(1,2,3)
print(no)
#Nested Tuple
n1=(“python”,[‘list’,’in’,’tuple])
print(n1[0])
print(n2[1])
#mixed tuple
m1=(3,”aaa”)
nos,value=m1
print(nos)
print(value)
Output:
(1,2,3)
python
[‘list’,’in’,’tuple’]
3
aaa

S.NO LIST TUPLE

1 Lists are mutable Tuple are immutable

2 Implication of iterations is Time- Implication of iterations is comparatively Faster


onsuming

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

14 b) ii) Write a python program to sort n number using mergesort.


a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)
Output:
Enter number of elements:3
Enter element:10
Enter element:0
Enter element:45
Enter number of elements:2
Enter element:78
Enter element:99
Sorted list is: [0, 10, 45, 78, 99]

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.

1.The except Clause with No Exceptions


You can also use the except statement with no exceptions defined as follows −
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
2.The try-finally Clause
The finally block is a place to put any code that must execute, whether the try-block
raised an exception or not.
Syntax :
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
 We cannot use else clause as well along with a finally clause.
Example.py(divide by 0)
try:
x=10/0
print("Never executed")
except:
print("this is an error message")
Output:
this is an error message
Example.py (except statements)
try:
a=int(input("Enter a :"))
b=int(input("Enter b:"))
print(a+b)
print(a/b)
except ArithmeticError:
print("Divide by 0")
Output:
Enter a :10
Enter b:0
10
Divide by 0
Example.py (finally)
try:
f=open("D:/input.txt","r")
x=f.read()
except IOError:
print("Cannot find the file")
except:
print("Some other error")
else:
print("Contents of file",x)
finally:
f.close()
print("File closed")
Output:1
Contents of file
Welcome to world of robotics
This will be intresting
This is the end
File closed
Output:2
Cannot find the file

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

15) b) i) How to merge multiple files in to a new file using python.

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

You might also like