0% found this document useful (0 votes)
18 views12 pages

SET B Answerkey

Uploaded by

Aaniya Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views12 pages

SET B Answerkey

Uploaded by

Aaniya Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

Part A

1. Life Cycle of a Thred

1. NEW – a newly created thread that has not yet started the execution
2. RUNNABLE – either running or ready for execution but it’s waiting for resource
allocation

3. BLOCKED – waiting to acquire a monitor lock to enter or re-enter a synchronized


block/method

4. WAITING – waiting for some other thread to perform a particular action without any time
limit

5. TIMED_WAITING – waiting for some other thread to perform a specific action for a
specified period

6. TERMINATED – has completed its execution

2. a.

from sympy import *


from sympy.solvers.solveset import linsolve
x, y = symbols('x, y')
print(linsolve([x + 5 *y - 2, -3*x +6*y], (x, y)))

output

{(4/7, 2/7)}

b.Create two 3*3 matrices and perform matrix multiplication and addition.

X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

mul = [[sum(a * b for a, b in zip(A_row, B_col))


for B_col in zip(*B)]
for A_row in A]
for x in result:
print(r)

3. Code

def change_cases(s):
return str(s).upper(), str(s).lower()
chrars = {'a', 'b', 'E', 'f', 'a', 'i', 'o', 'U', 'a'}
print("Original Characters:\n",chrars)
result = map(change_cases, chrars)
print("\nAfter converting above characters in upper and lower cases\nand eliminating duplicate
letters:")
print(set(result))

Output:

4.

from sympy import *


from sympy.solvers.solveset import linsolve
x, y = symbols('x, y')
print(linsolve([x * 4 - 1, x], (x)))
print(linsolve([x+x * y/x], (x,y)))

5.

6.

7. Output:

def average_tuple(nums):
result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
return result
nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
print ("Original Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n",average_tuple(nums))
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
print ("\nOriginal Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n",average_tuple(nums))

Output:

Part B

8. a(i).

The Model-View-Controller (MVC) software design pattern is a method for separating


concerns within a software application. As the name implies, the MVC pattern has three
layers:

• The Model defines the business layer of the application,


• the Controller manages the flow of the application,

• the View defines the presentation layer of the application.

Model: Handles data and business logic. Represents the business layer of the application

View: Presents the data to the user whenever asked for. Defines the presentation of the application

Controller: Entertains user requests and fetch necessary resources. Manages the flow of the
application

Model
public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View

public class StudentView {


public void printStudentDetails(String studentName, String studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}

Controller
Main program

8a ii

.
8 b ii. characteristics of functional programming

• First-class functions – accept another function as an argument or return a function


• Pure functions - they are functions without side effects

• Recursion - allows writing smaller algorithms and operating by looking only at the inputs to a
function

• Immutable variables - variables that cannot be changed

• Non-strict evaluation - allows having variables that have not yet been computed

• Statements - evaluable pieces of code that have a return value

Pattern matching - allows better type-checking and extracting elements from an object

9.a.i.

9.a.ii

1. Message Passing - the user makes calls to libraries to explicitly share information between
processors.
2. Data Parallel - data partitioning determines parallelism

3. Shared Memory - multiple processes sharing common memory space

4. Remote Memory Operation - set of processes in which a process can access the memory of
another process without its participation

5. Threads - a single process having multiple (concurrent) execution paths

6. Combined Models - composed of two or more of the above.

9.b.i

class Time:
def __init__(self, hours=0, minutes=0):
self.hours = hours
self.minutes = minutes

def addTime(self, other):


new_hours = self.hours + other.hours
new_minutes = self.minutes + other.minutes

if new_minutes >= 60:


new_hours += 1
new_minutes -= 60

return Time(new_hours, new_minutes)

def displayTime(self):
print(f"{self.hours}:{self.minutes}")

def displayMinutes(self):
print(f"{self.hours * 60 + self.minutes} minutes")

if __name__ == "__main__":
time1 = Time(2, 50)
time2 = Time(1, 20)

print("time1")
time1.displayTime()
print("time2")
time2.displayTime()

add = Time.addTime(time1, time2)


print("time1 + time2")
add.displayTime()
print("Total minutes:")
add.displayMinutes()

9.b.ii

Concurrent programming is programming with multiple tasks. The major issues of concurrent
programming are:

• Sharing computational resources between the tasks;


• Interaction of the tasks.

Objects shared by multiple tasks have to be safe for concurrent access. Such objects are called
protected. Tasks accessing such an object interact with each other indirectly through the object.

An access to the protected object can be:

• Lock-free, when the task accessing the object is not blocked for a considerable time;
• Blocking, otherwise.

Blocking objects can be used for task synchronization. To the examples of such objects belong:

• Events;
• Mutexes and semaphores;

• Waitable timers;

• Queues

10. a.i Server Program:

import socket
def server_program():
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024

server_socket = socket.socket() # get instance


# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port
together

# configure how many client the server can listen simultaneously


server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
# receive data stream. it won't accept data packet greater than
1024 bytes
data = conn.recv(1024).decode()
if not data:
# if data is not received break
break
print("from connected user: " + str(data))
data = input(' -> ')
conn.send(data.encode()) # send data to the client

conn.close() # close the connection

if __name__ == '__main__':
server_program()

Client Program:

import socket

def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server

message = input(" -> ") # take input

while message.lower().strip() != 'bye':


client_socket.send(message.encode()) # send message
data = client_socket.recv(1024).decode() # receive response

print('Received from server: ' + data) # show in terminal

message = input(" -> ") # again take input

client_socket.close() # close the connection

if __name__ == '__main__':
client_program()

a.ii.

10. b. i.
from automata.fa.dfa import DFA
# DFA which matches all and in ‘bb’
dfa = DFA(
states={'q0', 'q1', 'q2'},
input_symbols={'a', 'b'},
transitions={
'q0': {'a': 'q0', 'b': 'q1'},
'q1': {'a': 'q0', 'b': 'q2'},
'q2': {'a': 'q0', 'b': 'q2'}
},
initial_state='q0',
final_states={'q1'}
)
dfa.read_input('abb') # answer is 'q1‘
dfa.read_input('ab') # answer is error
print(dfa.read_input_stepwise('ab'))
if dfa.accepts_input('abb'):
print('accepted')
else:
print('rejected')

b.ii. Diffrence between NFA and DFA

You might also like