N. B.: (1) All questions are compulsory suitable assumptions...

22
(2½ hours) Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Make suitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written together. (4) Numbers to the right indicate marks. (5) Draw neat labeled diagrams wherever necessary. (6) Use of Non-programmable calculators is allowed. 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.

Transcript of N. B.: (1) All questions are compulsory suitable assumptions...

Page 1: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

(2½ hours)

Total Marks: 75

N. B.: (1) All questions are compulsory.

(2) Make suitable assumptions wherever necessary and state the assumptions made.

(3) Answers to the same question must be written together.

(4) Numbers to the right indicate marks.

(5) Draw neat labeled diagrams wherever necessary.

(6) Use of Non-programmable calculators is allowed.

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.

Page 2: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

c. The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a

numerical approximation of 1/π:

1

𝜋=

2√2

9801∑

(4𝑘)! (1103 + 26390𝑘)

(𝑘!)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:

d. Write the output for the following:

i) >>> print('a' , 'b' , 'c' , sep = ', ', end=' ')

ii) >>> 4 * '-'

iii) >>> 'GC' * 0 #This is ‘GC’ * zero

iv) >>> x = 3

>>> 1 < x <= 5

v) >>> 3 < 5 != False

vi) >>> 'abc' < 'abcd'

vii) >>> 'Jan' in '01 Jan 1838'

Page 3: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

viii) >>> ' ' in 'abc'

ix) >>> ' ' in ' '

x) >>> len(' \' ')

>>> len(' it\'s ')

Answer:

e. A triple of numbers (a,b,c) is called a Pythagorean triple if a * a + b * b = c * c.

In this question, you will be given three numbers. You have to output 1 if the three numbers

form a Pythagorean triple. Otherwise, you have to output 0.

Note that the inputs may not be given in order: you may have to try all possible orderings of the

three numbers to determine whether they form a Pythagorean triple.

Answer:

Output:

Page 4: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

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

2. Attempt any three of the following: 15

Page 5: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

a. i) Name the following code and explain the same:

def recurse():

recurse()

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)

What will happen if we call this function as seen below?

>>> countdown(3)

Output:

3

2

1

Blastoff!

iii) Fermat’s Last Theorem says that there are no positive integers a, b, and c such that an +bn =

cn for any values of n greater than 2.

Write a function named check_fermat that takes four parameters—a, b, c and n—and that

checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that

an +bn = cn the program should print, “Holy smokes, Fermat was wrong!” Otherwise the

program should print, “Fermat’s Theorem holds.”

Write a function that prompts the user to input values for a, b, c and n, converts them to

integers, and uses check_fermat to check whether they violate Fermat’s theorem.

Answer:

Output:

Page 6: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

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:

Page 7: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

c. i) Write the output for the following if the variable fruit = 'banana' :

>>> fruit[:3]

>>> fruit[3:]

>>> fruit[3:3]

>>> fruit[:]

Output:

ii) What is the reason for the error seen here?

>>> greeting = 'Hello, world!'

>>> greeting[0] = 'J'

TypeError: 'str' object does not support item assignment

Answer:

The reason for the error is that strings are immutable, which means you can’t change an

existing string.

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

Page 8: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

e

s

Answer:

Output:

ii)Write a function is_reverse(string1, string2) to return true if string1 is

reverse of string2:

>>> is_reverse('pots', 'stop')

True

Answer:

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:

Page 9: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

Output:

f. The Ackermann function, A(m,n), is defined:

Write a recursive function named ackermann that evaluates Ackermann’s function.

Answer:

Output:

3. Attempt any three of the following: 15

a. i) Write the output for the following:

1) >>> a = [1, 2, 3]

>>> b = [4, 5, 6]

>>> c = a + b

>>> print c

Answer:

2) >>> [1, 2, 3] * 3

Page 10: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

Answer:

3) >>> t = ['a', 'b', 'c', 'd', 'e', 'f']

>>> t[1:3] = ['x', 'y']

>>> print t

Answer:

ii) Explain any 2 methods under lists in Python with examples.

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 :

Page 11: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

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

But if you scatter the tuple, it works:

>>> divmod(*t)

(2, 1)

ii) Replace the following set of statements with a tuple assignment.

>>> temp = a

>>> a = b

>>> b = temp

Answer:

a, b = b, a

iii) Explain any 3 methods associated with files in Python.

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

c. i) What is the significant difference between list and dictionary?

Answer:

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a

dictionary they can be (almost) any type.

ii) Write a Python code to get the following dictionary as output :

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Answer:

Output:

Page 12: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

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:

d. List and explain any five exceptions in Python.

Answer:

NameError: You are trying to use a variable that doesn’t exist in the current environment.

Remember that local variables are local. You cannot refer to them from outside the function

where they are defined.

TypeError: There are several possible causes:

• You are trying to use a value improperly. Example: indexing a string, list, or tuple with

something other than an integer.

• There is a mismatch between the items in a format string and the items passed for conversion.

This can happen if either the number of items does not match or an invalid conversion is

called for.

• You are passing the wrong number of arguments to a function or method. For methods, look

at the method definition and check that the first parameter is self. Then look at the method

invocation; make sure you are invoking the method on an object with the right type and

providing the other arguments correctly.

KeyError: You are trying to access an element of a dictionary using a key that the dictionary

does not contain.

AttributeError: You are trying to access an attribute or method that does not exist. If an

AttributeError indicates that an object has NoneType, that means that it is None. One common

cause is forgetting to return a value from a function; if you get to the end of a function without

hitting a return statement, it returns None. Another common cause is using the result from a list

method, like sort, that returns None.

IndexError: The index you are using to access a list, string, or tuple is greater than its length

minus one.

e. Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]. This

operation is called a lookup.

But what if you have v and you want to find k? What is this operation called? Explain the same

by writing a Python code.

Answer:

Reverse Lookup

Page 13: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

Output

Successful reverse lookup:

Unsuccessful reverse lookup:

f. Explain the following statements:

Note: Explanation is necessary for each sub question

i) >>> a, b = 1, 2, 3

Answer:

ValueError: too many values to unpack

ii) >>> addr = '[email protected]'

>>> uname, domain = addr.split('@')

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)

Page 14: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

Answer:

4. Attempt any three of the following: 15

a. Explain the role of the Regular Expressions in the following snippets:

i) >>> p = re.compile('\d+')

>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')

ii) >>> p = re.compile('ca+t')

>>> p.findall('ct cat caaat caaaaaat caaat ctttt cccttt')

iii) >>> p = re.compile('ca*t')

>>> p.findall('ct cat caaat caaaaaat caaat ctttt cccttt')

iv) >>> p = re.compile('a/{1,3}b')

>>> p.findall('a/b a//b a///b a/////b ab')

v) >>> result=re.findall(r'\w*','AV is largest Analytics community of India')

>>> print (result)

Answer:

b. Explain Class inheritance in Python with an example.

Note : Explanation of the concept along with a sample code is a must.

class Person:

def __init__(self, first, last):

self.firstname = first

self.lastname = last

def Name(self):

return self.firstname + " " + self.lastname

class Employee(Person):

def __init__(self, first, last, staffnum):

Person.__init__(self,first, last)

self.staffnumber = staffnum

def GetEmployee(self):

Page 15: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

return self.Name() + ", " + self.staffnumber

x = Person("Marge", "Simpson")

y = Employee("Homer", "Simpson", "1007")

print(x.Name())

print(y.GetEmployee())

c. i) How is method overriding implemented in Python?

Note : Explanation of the concept along with a sample code is a must.

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

Page 16: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

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

List and explain the methods used under synchronization of threads.

The threading module provided with Python includes a simple-to-implement locking

mechanism that allows you to synchronize threads. A new lock is created by calling

the Lock() method, which returns the new lock.

The acquire(blocking) method of the new lock object is used to force threads to run

synchronously. The optional blocking parameter enables you to control whether the thread

waits to acquire the lock.

If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be

acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and

wait for the lock to be released.

The release() method of the new lock object is used to release the lock when it is no longer

required.

f. Create a module armprime that has two functions, one to check whether the given number is

an Armstrong number and the other to check whether the given number is a prime number.

Import the above created module in a .py file and show the use of the two functions.

Answer:

Page 17: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

Output:

5. Attempt any three of the following: 15

a. Write a Python code to create the following GUI:

Answer:

Page 18: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

b. Write a Python code to show the following types of message boxes:

Answer:

Page 19: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

c. Write a Python code to create the following menu bar :

Answer:

d. Explain the Scrolled text widget in Python.

Answer:

Note : Explanation for each command is necessary.

e. Write a Python code to do the following:

i) Create a table STUDENT with columns Id (integer, not null, primary key), RollNo (integer,

not null), Name (not null, varchar), Class (not null, varchar) and Grade (not null, varchar)

in MySQL and insert 4 rows of data.

ii) Retrieve the rows where Grade = ‘O’

Answer:

Page 20: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

Output:

f. Write a Python code to do the following:

Page 21: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.

i) Create a table EMPLOYEE with columns Id (integer, not null, primary key), AdhaarNo

(integer, not null), Empname (not null, varchar), Empdept (not null, varchar) and Empage

(not null, integer) in MySQL and insert 5 rows of data.

ii) Update the respective rows to Empdept = ‘ERP’ where Empage is >=40.

Answer

Output:

Page 22: N. B.: (1) All questions are compulsory suitable assumptions …muresults.net/itacademic/SYBScIT/Sem3/March18/20932PP.pdf · The acronym PEMDAS is an useful way to remember the rules.