PP APR-18 (Sol) (E-next.in)
PP APR-18 (Sol) (E-next.in)
Total Marks: 75
Note :
1. The answers given here are just a guidance and the teachers must give consideration
to any other logic[for theory and code snippets] used by the student in
framing the same.
2. Make necessary changes in answers if necessary. I have tried to give the answers after
executing each code.
1. Attempt any three of the following: 15
a. Python programs are executed by an interpreter. There are two ways to use the interpreter. What
are they?
Answer:
There are two ways to use the interpreter: interactive mode and script mode. In interactive
mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 1 +
1, the interpreter replies 2.
Alternatively, you can store code in a file and use the interpreter to execute the contents of the
file, which is called a script. By convention, Python scripts have names that end with .py. To
execute the script, you have to tell the interpreter the name of the file.
b. When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. The acronym PEMDAS is an useful way to remember the rules. Explain
the same with a Python expression.
Answer:
• 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.
c. The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a
numerical approximation of 1/π:
∞
1 2√2 (4𝑘)! (1103 + 26390𝑘)
= ∑
𝜋 9801 (𝑘!)4 3964𝑘
𝑘=0
Write a function called estimate_pi that uses this formula to compute and return an estimate of
π. It should use a while loop to compute terms of the summation until the last term is smaller
than 1e-15 (Python notation for 10−15).
Answer:
Output:
Output:
f. Explain for loop in Python with an example code to print Fibonacci series up to 10 terms.
Answer:
Note:
For loop to be explained with this example as theory.
Output
Answer:
Infinite recursion
If a recursion never reaches a base case, it goes on making recursive calls forever, and the
program never terminates. This is known as infinite recursion, and it is generally not a good
idea. In most programming environments, a program within finite recursion does not really run
forever. Python reports an error message when the maximum recursion depth is reached:
ii) def countdown(n):
if n <= 0:
print ('Blastoff!')
else:
print( n)
countdown(n-1)
Answer:
Output:
b. Write a Python program to list all the factorial numbers less than or equal to an input number n.
A number N is called a factorial number if it is the factorial of a positive integer. For example,
the first few factorial numbers are
1, 2, 6, 24, 120, ...
Note: We do not list the factorial of 0.
Input: A positive integer, say n.
Output: All factorial numbers less than or equal to n.
Use recursive function to calculate factorial.
Answer:
Output:
c. i) Write the output for the following if the variable fruit = 'banana' :
>>> fruit[:3]
>>> fruit[3:]
>>> fruit[3:3]
>>> fruit[:]
Output:
iii) Explain any 2 methods under strings in Python with suitable examples.
Answer:
>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA
-----------------------------------------------
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
-----------------------------------------------
>>> word.find('na')
2
d. i) Write a function in_both(string1, string2) that does the following:
>>> in_both('apples', 'oranges')
a
e
s
Answer:
Output:
Output:
e. Write a Python code to check whether the given number is a strong number. Strong Numbers are
numbers whose sum of factorial of digits is equal to the original number (Example: 145 = 1!
+4! + 5!) .
Answer:
Output:
Output:
2) >>> [1, 2, 3] * 3
Answer:
Answer:
Answer:
Python provides methods that operate on lists. For example, append adds a new element to the
end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']
iii) Write the function tail(l) to get the following output:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']
Answer:
Output :
b. i) What is meant by Variable-length argument tuples? Explain with an example.
Answer:
Functions can take a variable number of arguments. A parameter name that begins with
*gathers arguments into a tuple. For example, printall takes any number of arguments and
prints them:
def printall(*args):
print args
The gather parameter can have any name you like, but args is conventional. Here’s how the
function works:
>>> printall(1, 2.0, '3') (1, 2.0, '3') The
Complement of gather is scatter. If you have a sequence of values and you want to pass it to a
function as multiple arguments, you can use the * operator.
For example, divmod takes exactly two arguments; it doesn’t work with a tuple:
>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
Answer:
Any 3 methods to be explained in one line or with a small code snippet.
Open() - The open() function is used to open files in our system
Write() - Used to write a fixed sequence of characters to a file
Read() - Reads at most size bytes from the file
Close() - When you’re done with a file, use close() to close it and free up any system resources
taken up by the open file
Seek() - Sets the file's current position
Tell() - Returns the file's current position
Output:
iii) What is the output of the code given below:
>>> squares = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> print(squares[5])
>>> print(squares[6])
Answer:
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
>>> print domain
python.org
iii) >>> t = divmod(7, 3)
>>> print( t)
Answer:
(2, 1)
iv) >>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
Answer:
{('c', 2), ('a', 0), ('b', 1)} – list of tuples
v) for index, element in enumerate('abc'):
print( index, element)
Answer:
def Name(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def GetEmployee(self):
return self.Name() + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
print(x.Name())
print(y.GetEmployee())
class Parent(object):
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1
c=Child()
print(c.get_value())
Output:
6
ii) Which methods of Python are used to determine the type of instance and inheritance?
Answer:
Two built-in functions isinstance() and issubclass() are used to check inheritances.
Function isinstance() returns True if the object is an instance of the class or other classes derived
from it. Each and every class in Python inherits from the base class object.
d. Name and explain the magic methods of Python that are used in the initialization and deletion
of class objects with the help of a code snippet.
i) The method used for initialization is called __init__ , which is a special method.
When we call the class object, a new instance of the class is created, and
the __init__ method on this new object is immediately executed with all the
parameters that we passed to the class object. The purpose of this method is thus to
set up a new object using data that we have provided. self is the first parameter, and
we use this variable inside the method bodies – but we don’t appear to pass this
parameter in. This is because whenever we call a method on an object, the object
itself is automatically passed in as the first parameter. This gives us a way to access
the object’s properties from inside the object’s methods.
ii) For deleting objects:
class FooType(object):
def __init__(self, id):
self.id = id
print (self.id, 'born')
def __del__(self):
print( self.id, 'died')
def make_foo():
print ('Making...')
ft = FooType(1)
print ('Returning...')
return ft
print ('Calling...')
ft = make_foo()
print( 'End...')
Output:
Calling...
Making...
1 born
Returning...
End...
1 died
e. Name the methods in Python Multithreaded Programming. Also mention the module necessary
for each of the method.
i) A method to spawn another thread – thread.start_new_thread()
ii) A method to return the number of thread objects that are active – threading.activeCount()
iii) A method that waits for threads to terminate – join()
iv) A method that returns the name of the thread – getName()
v) A method that checks whether a thread is still executing. – isAlive()
Answer:
b. Write a Python code to show the following types of message boxes:
Answer:
c. Write a Python code to create the following menu bar :
Answer:
Answer:
Output:
Output: