UNIT II Question Bank With Answer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

lOMoARcPSD|23351831

UNIT II question bank with answer

Advanced Programming Practice (SRM Institute of Science and Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sudharsanan Radhakrishnan ([email protected])
lOMoARcPSD|23351831

UNIT II
PART B (4 Marks)
1 How is KeyListener used to handle keypress event?
• We will be using the pynput module to listen to keyboard events. To install this
module execute pip install pynput in cmd.
• In python pynput (python module to detecting any key press) . “pynput.keyboard”
contains classes for controlling and monitoring the keyboard.
• It Calls pynput.keyboard.Listener. stop from anywhere, or return False from a
callback to stop the listener. This library allows you to control and monitor input
devices.
Approach:
• Import key, Listener from pynput.keyboard
• Create a with Statement: The with statement is used to wrap the execution of a block
with methods defined by a context manager.
Example 1:
from pynput.keyboard import Key, Listener
from pynput.keyboard import Key, Listener
def show(key):
print('\nYou Entered {0}'.format( key))
if key == Key.delete:
# Stop listener
return False
# Collect all event until released
with Listener(on_press = show) as listener:
listener.join()
2
List and define the three participants in an event

Event Handlers: Event handlers is a type of function or method that run a specific action
when a specific event is triggered. For example, it could be a button that when user click it,
it will display a message, and it will close the message when user click the button again, this
is an event handler.
Trigger Functions: Trigger functions in event-driven programming are a function that
decide what code to run when there are a specific event occurs, which are used to select
which event handler to use for the event when there is specific event occurred.
Events: Events include mouse, keyboard and user interface, which events need to be
triggered in the program in order to happen, that mean user have to interacts with an object
in the program, for example, click a button by a mouse, use keyboard to select a button and
etc.

3
List the declarative statements in declarative programming with examples.

Declarative Statements:

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

SQL Commands
The SQL commands help in creating and managing the database. The most common SQL
commands which are highly used are mentioned below:
1. CREATE command: used to create the new database, new table, table view, and
other objects of the database.
2. UPDATE command: used to update or change the stored data in the database.
3. DELETE command : used to remove the saved records from the database tables. It
erases single or multiple tuples from the tables of the database.
4. SELECT command : used to access the single or multiple rows from one or multiple
tables of the database. We can also use this command with the WHERE clause.
5. DROP command :used to delete the entire table, table view, and other objects from
the database
6. INSERT command : used to insert the data or records into the database tables.

4
Write a Python program that creates a Timer that will explode in 2 seconds using
TURTLE module.
import time
import turtle

window = turtle.Screen()
window.tracer(0)

player = turtle.Turtle()
timer_text = turtle.Turtle()

start = time.time()
while time.time() - start < 3:
player.forward(1)
player.left(1)
timer_text.clear()
timer_text.write(int(time.time() - start), font=("Courier", 30))

window.update()

turtle.done()

5
Illustrate the invoking of a descriptor using _ _getattribute()_ _ method.

Python descriptors are created to manage the attributes of different classes which use the
object as reference. In descriptors we used three different methods that are __getters__(),
__setters__(), and __delete__(). If any of those methods are defined for an object, it can
be termed as a descriptor.

# Python program showing

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

# how to invoke descriptor

def __getattribute__(self, key):


v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v

• Descriptors are invoked by the __getattribute__() method.


• Overriding __getattribute__() prevents automatic descriptor calls.
• object.__getattribute__() and type.__getattribute__() make different calls to
__get__().
• Data descriptors always override instance dictionaries.
• Non-data descriptors may be overridden by instance dictionaries.

6 Bring out the differences between Lists and Tuples in Python using examples.
Lists and Tuples store one or more objects or values in a specific order. The objects stored
in a list or tuple can be of any type including the nothing type defined by the None
Keyword.
1. The literal syntax of tuples is shown by parentheses () whereas the literal syntax
of lists is shown by square brackets [] .
2. Lists has variable length, tuple has fixed length.
3. List has mutable nature, tuple has immutable nature.
4. List has more functionality than the tuple.
Syntax
Syntax of list and tuple is slightly different. Lists are surrounded by square brackets []
and Tuples are surrounded by parenthesis ().
Example
list_num = [1,2,3,4]
tup_num = (1,2,3,4)
print(list_num)
print(tup_num)

Mutable List vs Immutable Tuples


List has mutable nature i.e., list can be changed or modified after its creation according
to needs whereas tuple has immutable nature i.e., tuple can’t be changed or modified after
its creation.
Example:

list_num[2] = 5
print(list_num)

tup_num[2] = 5

Output :

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

[1,2,5,4]
Traceback (most recent call last):
File "python", line 6, in <module>
TypeError: 'tuple' object does not support item assignment

7
Using Turtle, Write a Python program to demonstrate Keypress Events. the turtle on the
screen must move according to the arrow keys (Up,Left,Right and Back) pressed.

import turtle as tim


import random

def up():
tim.setheading(90)
tim.forward(100)

def down():
tim.setheading(270)
tim.forward(100)

def left():
tim.set_heading(180)
tim.forward(100)

def right():
tim.setheading(0)
tim.forward(100)

tim.listen()

tim.onkey(up, "Up") # This will call the up function if the "Left" arrow key is pressed
tim.onkey(down, "Down")
tim.onkey(left, "Left")
tim.onkey(right, "Right")

tim.mainloop() # This will make sure the program continues to run

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

8
Compare and contrast imperative programming and declarative programming.
Imperative Programming
1. In this, programs specify how it is to be done.
2. It simply describes the control flow of computation.
3. Its main goal is to describe how to get it or accomplish it.
4. Its advantages include ease to learn and read, the notional model is simple to
understand, etc.
5. Its type includes procedural programming, object-oriented programming, parallel
processing approach.
6. In this, the user is allowed to make decisions and commands to the compiler.
7. It has many side effects and includes mutable variables as compared to declarative
programming.
8. It gives full control to developers that are very important in low-level
programming.

Declarative Programming
1. In this, programs specify what is to be done.
2. It simply expresses the logic of computation.
3. Its main goal is to describe the desired result without direct dictation on how to
get it.
4. Its advantages include effective code, which can be applied by using ways, easy
extension, high level of abstraction, etc.
5. Its type includes logic programming and functional programming.
6. In this, a compiler is allowed to make decisions.
7. It has no side effects and does not include any mutable variables as compared to
imperative programming.
8. It may automate repetitive flow along with simplifying code structure.

PART C (12 Marks)

1
Discuss about an Event object and steps to handle an event

• Event-driven programming is a programming paradigm in which the flow of program


execution is determined by events - for example a user action such as a mouse click,
key press, or a message from the operating system or another program.
• An event-driven application is designed to detect events as they occur, and then deal
with them using an appropriate event-handling procedure.
• In a typical modern event-driven program, there is no discernible flow of control. The
main routine is an event-loop that waits for an event to occur, and then invokes the
appropriate event-handling routine.
• Event call-back is a function that is invoked when something significant happens like
when click event is performed by user or the result of database query is available.
Event Handlers: Event handlers is a type of function or method that run a specific action
when a specific event is triggered. For example, it could be a button that when user click it, it

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

will display a message, and it will close the message when user click the button again, this is
an event handler.
Trigger Functions: Trigger functions in event-driven programming are a function that decide
what code to run when there are a specific event occurs, which are used to select which event
handler to use for the event when there is specific event occurred.
Events: Events include mouse, keyboard and user interface, which events need to be triggered
in the program in order to happen, that mean user have to interacts with an object in the
program, for example, click a button by a mouse, use keyboard to select a button and etc.
Tkinter is a Python library which is used to create GUI-based application. Tkinter comes with
many inbuilt features and extensions which can be used to optimize the application
performance and behaviour. Tkinter Events are generally used to provide an interface that
works as a bridge between the User and the application logic. We can use Events in any
Tkinter application to make it operable and functional.
Fundamental structure of tkinter program
1. Import tkinter package and all of its modules.
2. Create a root window. Give the root window a title (using title ()) and dimension
(using geometry ()). All other widgets will be inside the root window.
3. Use mainloop() to call the endless loop of the window. If you forget to call this
nothing will appear to the user. The window will wait for any user interaction till we
close it.

2
Design the Students information system with student details, qualification details and mark
details and add insert, delete and update button. Write an event handler to send the marks
to their parents, immediately after the mark has been updated.

3
Elaborate on the features of declarative programming and list the set of declarative
statements.

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

4
Write a Python program to create three states Solid, Liquid and Gas. Create transitions
Melt, Evaporate, Sublimate and Ionize with an exit callback printing the transition name.

5
Compare imperative programming with declarative programming.

PART B (4 Marks)

1 Differentiate parallel programming with functional programming

2 Explain about Multithreading

3 Explain about Multiprocessing.

4 Demonstrate Multiprocessing module in Python

5 Describe about Process class.

6 Design a Pool class in Python

7 State Concurrent programming paradigm.

8 Compare multiprocessing and multitasking.


PART C (12 Marks)

1 Write a python program to implement the producer consumer problem.

Program:

from threading import Thread, Condition


import time
import random

queue = []
MAX_NUM = 10
condition = Condition()

class ProducerThread(Thread):
def run(self):
nums = range(5)
global queue
while True:
condition.acquire()
if len(queue) == MAX_NUM:
print "Queue full, producer is waiting"
condition.wait()
print "Space in queue, Consumer notified the producer"

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

num = random.choice(nums)
queue.append(num)
print "Produced", num
condition.notify()
condition.release()
time.sleep(random.random())

class ConsumerThread(Thread):
def run(self):
global queue
while True:
condition.acquire()
if not queue:
print "Nothing in queue, consumer is waiting"
condition.wait()
print "Producer added something to queue and notified the consumer"
num = queue.pop(0)
print "Consumed", num
condition.notify()
condition.release()
time.sleep(random.random())

ProducerThread().start()
ConsumerThread().start()

OUTPUT:
Produced 0
Consumed 0
Produced 0
Produced 4
Consumed 0
Consumed 4
Nothing in queue, consumer is waiting
Produced 4
Producer added something to queue and notified the consumer
Consumed 4
Produced 3
Produced 2
Consumed 3
2 Implement the concept “Pool class” by importing a package pool
3 Write a python program to implement the dining philosopher problem.
Program
import time
import threading

class Philosopher(threading.Thread):
def __init__(self, pid, sticks, stomachCapacity=3):
threading.Thread.__init__(self)
self.pid = pid

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

self.sticks = sticks
self.amount = 0
self.stomachCapacity = stomachCapacity

def run(self):
if self.pid%2 == 0:
self.run_even()
else:
self.run_odd()

if self.amount < self.stomachCapacity:


time.sleep(0.1)
self.run()

def run_even(self):
# Even philosophers are greedy and always wait for the next chopstick and
# never put down a chopstick until they have eaten.
i1 = pid
i2 = (pid + 1)%len(sticks)
print "Philosopher " + str(self.pid) + " is waiting for the first stick"
self.sticks[i1].acquire()
print "Philosopher " + str(self.pid) + " gets the left stick"
print "Philosopher " + str(self.pid) + " waits for the second stick"
self.sticks[i2].acquire()
print "Philosopher " + str(self.pid) + " has acquired the right stick"
self.amount += 1
print "Philosopher " + str(self.pid) + " eats"
self.sticks[i2].release()
print "Philosopher " + str(self.pid) + " has released the right stick"
self.sticks[i1].release()
print "Philosopher " + str(self.pid) + " has released the left stick"

def run_odd(self):
# Odd numbered philosophes are generous. If they cannot get the second stick
# they will put down the first and wait to try again.
i1 = self.pid
i2 = (self.pid + 1)%len(self.sticks)
# setting the argument to False makes it so that the thread is not locked and instead
# the acquire method returns a boolean for whether that thrread got the lock or not.
print "Philosopher " + str(self.pid) + " is trying to pick up the left stick."
if self.sticks[i1].acquire(False):
print "Philosopher " + str(self.pid) + " has picked up the left stick."
print "Philosopehr " + str(self.pid) + " is trying to pick up the right stick"
if self.sticks[i2].acquire(False):
print "Philosopher " + str(self.pid) + " picked up the right stick"
self.amount += 1
print "Philosopher " + str(self.pid) + " has eaten"
self.sticks[i2].release()
print "Philosopher " + str(self.pid) + " has released the right stick"
self.sticks[i1].release()
print "Philosopher " + str(self.pid) + " has released the left stick"
else:

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

print "Philosopher " + str(self.pid) + " has failed to get the second stick and released the left stick"
print "Philosopher " + str(self.pid) + " is waiting to try again."
self.sticks[i1].release()
time.sleep(0.1)
self.run()
else:
print "Philosopher " + str(self.pid) + " has failed to get the first stick and waits to try again."
time.sleep(0.1)
self.run()

numPhilosophers = 5
sticks = []
philosophers = []
for i in xrange(numPhilosophers):
sticks.append(threading.Lock())
amounts.append(0)

for pid in xrange(numPhilosophers):


philosophers.append(Philosopher(pid, sticks, 2))

for philosopher in philosophers:


philosopher.start()

for philosopher in philosophers:


philosopher.join()

for philosopher in philosophers:


print philosopher.amount

print "Finished!"

Output
Philosopher 0 is waiting for the first stickPhilosopher 1 is trying to pick up the left stick.

Philosopher 3 is trying to pick up the left stick.Philosopher 0 gets the left stickPhilosopher 2 is
waiting for the first stickPhilosopher 1 has picked up the left stick.

Philosopher 0 waits for the second stick

Philosopher 0 has acquired the right stickPhilosopehr 1 is trying to pick up the right stick
Philosopher 0 eats

Philosopher 0 has released the right stickPhilosopher 1 picked up the right stick
Philosopher 0 has released the left stick

Philosopher 1 has eatenPhilosopher 2 gets the left stickPhilosopher 3 has picked up the left stick.

Philosopher 2 waits for the second stickPhilosopher 1 has released the right stick

Philosopher 1 has released the left stickPhilosopher 2 has acquired the right stickPhilosopher 4 is
waiting for the first stickPhilosopehr 3 is trying to pick up the right stick

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

Philosopher 2 eatsPhilosopher 3 has failed to get the second stick and released the left stick

Philosopher 2 has released the right stickPhilosopher 3 is waiting to try again.

Philosopher 2 has released the left stick


Philosopher 4 gets the left stick
Philosopher 4 waits for the second stick
Philosopher 4 has acquired the right stick
Philosopher 4 eats
Philosopher 4 has released the right stick
Philosopher 4 has released the left stick
Philosopher 0 is waiting for the first stick
Philosopher 0 gets the left stick
Philosopher 0 waits for the second stick
Philosopher 0 has acquired the right stick
Philosopher 0 eats
Philosopher 0 has released the right stick
Philosopher 0 has released the left stick
Philosopher 1 is trying to pick up the left stick.
Philosopher 1 has picked up the left stick.
Philosopehr 1 is trying to pick up the right stick
Philosopher 1 picked up the right stick
Philosopher 1 has eaten
Philosopher 1 has released the right stick
Philosopher 1 has released the left stick
Philosopher 3 is trying to pick up the left stick.
Philosopher 3 has picked up the left stick.
Philosopehr 3 is trying to pick up the right stick
Philosopher 3 picked up the right stick
Philosopher 3 has eaten
Philosopher 3 has released the right stick
Philosopher 3 has released the left stick
Philosopher 4 is waiting for the first stick
Philosopher 4 gets the left stick
Philosopher 4 waits for the second stick
Philosopher 4 has acquired the right stick
Philosopher 4 eats
Philosopher 4 has released the right stick
Philosopher 4 has released the left stick
Philosopher 2 is waiting for the first stick
Philosopher 2 gets the left stick
Philosopher 2 waits for the second stick
Philosopher 2 has acquired the right stick
Philosopher 2 eats
Philosopher 2 has released the right stick
Philosopher 2 has released the left stick
Philosopher 3 is trying to pick up the left stick.
Philosopher 3 has picked up the left stick.
Philosopehr 3 is trying to pick up the right stick
Philosopher 3 picked up the right stick
Philosopher 3 has eaten
Philosopher 3 has released the right stick

Downloaded by Sudharsanan Radhakrishnan ([email protected])


lOMoARcPSD|23351831

Philosopher 3 has released the left stick


2
2
2
2
2
Finished!

4 Explain the differences between multithreading and multiprocessing with an example?


5 Compare Concurrent programming paradigm and functional programming paradigm with
example program.

Downloaded by Sudharsanan Radhakrishnan ([email protected])

You might also like