0% found this document useful (0 votes)
8 views44 pages

Python I/O and Scheduling Algorithms

Algorithm Design and Paradigms: Divide and Conquer: Karatsuba’s multiplication, Strassen’s algorithm, Greedy Methods: Huffman coding, interval scheduling, set cover approximation, Dynamic Programming: Matrix chain multiplication, FloydWarshall, knapsack variants, Backtracking and Branch-and-Bound, Randomized Algorithms and Probabilistic Analysis. Practical: • Implement Strassen’s algorithm and compare with naive matrix multiplication. • Develop a randomized algorithm for primality testing (Mi

Uploaded by

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

Python I/O and Scheduling Algorithms

Algorithm Design and Paradigms: Divide and Conquer: Karatsuba’s multiplication, Strassen’s algorithm, Greedy Methods: Huffman coding, interval scheduling, set cover approximation, Dynamic Programming: Matrix chain multiplication, FloydWarshall, knapsack variants, Backtracking and Branch-and-Bound, Randomized Algorithms and Probabilistic Analysis. Practical: • Implement Strassen’s algorithm and compare with naive matrix multiplication. • Develop a randomized algorithm for primality testing (Mi

Uploaded by

opspitti.55328
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1(a).

BASIC I/O PROGRAMMING PROCESS CREATION

PROGRAM:

from multiprocessing import Process


import os
def info(title):
print(title)
print("Module Name:", __name__)
print("Parent Process ID:", [Link]())
print("Current Process ID:", [Link]())
def f(name):
info("Inside Child Process")
print("Hello", name)
if __name__ == "__main__":
info("Main Line")
p = Process(target=f, args=("Bob",))
[Link]()
[Link]()
print("Child Process Name:", [Link])
print("Child Process ID:", [Link])
OUTPUT:

Main Line
Module Name: __main__
Parent Process ID: 23384
Current Process ID: 9328
Child Process Name: Process-1
Child Process ID: 10628
1(b). BASIC I/O PROGRAMMING IN FILE CREATION

PROGRAM:

file1=open("[Link]","w")
L=["This is Delhi\n","This is Paris\n","This is London\n"]
[Link]("HELLO\n")
[Link](L)
[Link]()
file1=open("[Link]","r+")
print("Output of read Function is")
print([Link]())
[Link](0)
print("Output of read(9)Functoin is")
print([Link](8))
print()
[Link](0)
print("Output of readline(9)Function is")
print([Link](9))
print("Output of readline Function is")
print([Link](7))
print()
[Link]()
OUTPUT:

Output of read Function is


HELLO
This is Delhi
This is Paris
This is London

Output of read(9)Functoin is
HELLO
Th

Output of readline(9)Function is
HELLO

Output of readline Function is


['This is Delhi\n']
2. SHORTEST JOB FIRST ALGORITHM

PROGRAM:

def findWaitingTime(processes,n,bt,wt):
wt[0]=0
for i in range(1,n):
wt[i]=bt[i-1]+wt[i-1]
def findTurnAroundTime(processes,n,bt,wt,tat):
for i in range(n):
tat[i]=bt[i]+wt[i]
def findavgTime(processes,n,bt):
wt=[0]*n
tat=[0]*n
totalwt=0
totaltat=0
findWaitingTime(processes,n,bt,wt)
findTurnAroundTime(processes,n,bt,wt,tat)
print("processes\tBurstTime\tWaitingTime\tTurnAroundTime")
for i in range(n):
totalwt=totalwt+wt[i]
totaltat=totaltat+tat[i]
print(processes[i],"\t\t",bt[i],"\t\t",wt[i],"\t\t",tat[i])
print("Average Waiting Time=",totalwt/n)
print("Average Turn Around Time=",totaltat/n)
if __name__=="__main__":
process=['p1','p2','p3','p4']
n=len(process)
bursttime=[6,8,7,3]
bursttime,process=zip(*sorted(zip(bursttime,process)))
findavgTime(process,n,bursttime)
OUTPUT:

Processes Burst Time Waiting Time TurnAround Time


p4 3 0 3
p1 6 3 9
p3 7 9 16
p2 8 16 24

Average Waiting Time= 7.0


Average Turn Around Time= 13.0
3. FIRST COME FIRST SERVED ALGORITHM

PROGRAM:

def findwaitingtime(processes, n, bt, wt):


wt[0]=0
for i in range(1, n):
wt[i]=bt[i-1] + wt[i-1]
def findturnaroundtime(processes, n, bt, wt, tat):
for i in range(n):
tat[i] = bt[i] + wt[i]
def findavgtime(processes, n, bt):
wt = [0] * n
tat = [0] * n
findwaitingtime(processes, n, bt, wt)
findwaitingtime(processes, n, bt, wt)
print("Processes Burst time Waiting time Turnaround time")
total_wt = 0
total_tat = 0
for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
print(f" {processes[i]}\t\t{bt[i]}\t\t{wt[i]}\t\t{tat[i]}")
print(f"\nAverage waiting time = {total_wt / n:.2f}")
print(f"Average turnaround time = {total_tat / n:.2f}")
if __name__ == "__main__":
processes = ['p1', 'p2', 'p3']
n = len(processes)
burst_time = [24, 3, 3]
findavgtime(processes, n, burst_time)
OUTPUT:

Processes Burst time Waiting time Turnaround time


p1 24 0 24
p2 3 24 27
p3 3 27 30

Average waiting time = 17.0


Average turnaround time = 27.0
4(a). ROUND ROBIN ALGORITHM

PROGRAM:

def findwaitingtime(processes, n, bt, wt, quantum):


rem_bt = bt[:]
t=0
while True:
done = True
for i in range(n):
if rem_bt[i] > 0:
done = False
if rem_bt[i] > quantum:
t += quantum
rem_bt[i] -= quantum
else:
t += rem_bt[i]
wt[i] = t - bt[i]
rem_bt[i] = 0
if done:
break

def findturnaroundtime(processes, n, bt, wt, tat):


for i in range(n):
tat[i] = bt[i] + wt[i]
def findavgtime(processes, n, bt, quantum):
wt = [0] * n
tat = [0] * n

findwaitingtime(processes, n, bt, wt, quantum)


findturnaroundtime(processes, n, bt, wt, tat)

print("Processes\tBurst time\tWaiting time\tTurnaround time")


total_wt = 0
total_tat = 0
for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
print(f"{processes[i]}\t\t{bt[i]}\t\t{wt[i]}\t\t{tat[i]}")

print(f"\nAverage waiting time = {total_wt / n:.2f}")


print(f"Average turnaround time = {total_tat / n:.2f}")

if __name__ == "__main__":
processes = ['p1', 'p2', 'p3']
n = len(processes)
burst_time = [24, 3, 3]
quantum = 4
findavgtime(processes, n, burst_time, quantum)
OUTPUT:

Processes Burst time Waiting time Turnaround time


p1 24 6 30
p2 3 4 7
p3 3 7 10

Average waiting time = 5.67


Average turnaround time = 15.67
4(b). PRIORITY SCHEDULING ALGORITHM

PROGRAM:

def findwaitingtime(process, n, bt, wt):


wt[0]=0
for i in range(1,n):
wt[i]=bt[i-1]+wt[i-1]
def findturnaroundtime(processes, n, bt, wt, tat):
for i in range(n):
tat[i]=bt[i]+wt[i]
def findavgtime(processes, n, bt, pr):
wt=[0]*n
tat=[0]*n
total_wt=0
total_tat=0
findwaitingtime(processes, n, bt, wt)
findturnaroundtime(processes, n, bt,wt, tat)
print("Processes\t burst time\t Priority\t waiting time\t turnaround time")
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total_tat+tat[i]
print(processes[i],"\t\t",bt[i],"\t",pr[i],"\t\t",wt[i],"\t\t",tat[i])
print("average waiting time=",total_wt/n)
print("average turnaround time=",total_tat/n)
if __name__== "__main__":
process=['p1','p2','p3','p4','p5']
n=len(process)
burst_time=[10,1,2,1,5]
priority=[3,1,4,5,2]

priority,burst_time,process=zip(*sorted(zip(priority,burst_time,process)))
findavgtime(process,n,burst_time,priority)
OUTPUT:

Processes burst time Priority waiting time turnaround


time
p2 1 1 0 1
p5 5 2 1 6
p1 10 3 6 16
p3 2 4 16 18
p4 1 5 18 19

average waiting time= 8.2


average turnaround time= 12.0
[Link] IMPLEMENT READER/WRITER PROBLEM
USING SEMAPHORE

PROGRAM:

import threading as thread


import random
lock=[Link]()
count=0
def reader():
global count
[Link]()
print('Reader acquires the lock')
print('Reader is reading!')
print('Shared data:',count)
[Link]()
print('Reader releases the lock')
def writer():
global count
[Link]()
print('Writer acquires the lock')
print('Writer is writing!')
count+=1
print('Writer releases the lock\n')
[Link]()
if __name__== "__main__":
threads=[]
for i in range(0,12):
randomnumber=[Link](0,100)
if randomnumber>=50:
t=[Link](target=reader)
else:
t=[Link](target=writer)
[Link]()
[Link](t)
for t in threads:
[Link]()
OUTPUT:

Writer acquires the lock


Writer is writing!
Writer releases the lock

Reader acquires the lock


Reader is reading!
Shared data: 1
Reader releases the lockWriter acquires the lock

Writer is writing!
Writer releases the lock

Writer acquires the lock


Writer is writing!
Writer releases the lock

Writer acquires the lock


Writer is writing!
Writer releases the lock
Reader acquires the lock
Reader is reading!
Shared data: 4
Reader acquires the lockReader releases the lock

Reader is reading!
Shared data: 4
Reader releases the lockReader acquires the lock

Reader is reading!
Shared data: 4
Reader releases the lockWriter acquires the lock

Writer is writing!
Writer releases the lock

Writer acquires the lock


Writer is writing!
Writer releases the lock

Reader acquires the lock


Reader is reading!
Shared data: 6
Reader releases the lockWriter acquires the lock

Writer is writing!
Writer releases the lock
6. TO IMPLEMENT BANKER’S ALGORITHM FOR
DEADLOCK AVOIDANCE

PROGRAM:

P=5
R=3
def calculateNeed(need,maxm,allot):
for i in range(P):
for j in range(R):
need[i][j]=maxm[i][j]-allot[i][j]
def isSafe(Processes,avail,maxm,allot):
need=[[0]* R for _ in range(P)]
calculateNeed(need,maxm,allot)
finish=[0]*P
safeSeq=[0]*P
work=avail[:]
count=0
while count<P:
found=False
for p in range(P):
if finish[p]== 0:
if all(need[p][j]<=work[j] for j in range(R)):
for k in range(R):
work[k]+=allot[p][k]
safeSeq[count]=p
count+=1
finish[p]=1
found=True
if not found:
print("System is not in safe state")
return False
print("System is in safe state.")
print("Safe sequence is:",safeSeq)
return True
if __name__=="__main__":
Processes=[0,1,2,3,4]
avail=[3,3,2]
maxm=[[7,5,3],[3,2,2],[9,0,2],[2,2,2],[4,3,3]]
allot=[[0,1,0],[2,0,0],[3,0,2],[2,1,1],[0,0,2]]
isSafe(Processes,avail,maxm,allot)
OUTPUT:

System is in safe state.


Safe sequence is: [1, 3, 4, 0, 2]
7. FIRST IN FIRST OUT ALGORITHM

PROGRAM:

def fifo (pages,capacity):


n=len(pages)
pagefaults=0
victim = -1
frame=[-1] * capacity
print("Reference string:",pages)
print("\nFrame staus:")
for page in pages:
if page not in frame:
pagefaults+=1
victim=(victim+1)% capacity
frame[victim]=page
print(frame)
print("\nTotal Page Faults:",pagefaults)
if __name__ == "__main__":
pages=[7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1]
capacity=3
fifo(pages,capacity)
OUTPUT:

Reference string: [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1]

Frame staus:

[7, -1, -1]


[7, 0, -1]
[7, 0, 1]
[2, 0, 1]
[2, 0, 1]
[2, 3, 1]
[2, 3, 0]
[4, 3, 0]
[4, 2, 0]
[4, 2, 3]
[0, 2, 3]
[0, 2, 3]
[0, 2, 3]
[0, 1, 3]
[0, 1, 2]
[0, 1, 2]
[0, 1, 2]
[7, 1, 2]
[7, 0, 2]
[7, 0, 1]

Total Page Faults: 15


8. LEAST RECENTLY USED ALGORITHM

PROGRAM:

def lru(pages,capacity):
n=len(pages)
frame=[]
page_faults=0
print("Reference string:",pages)
print("\nFrame status:")
for page in pages:
if page not in frame:
if page not in frame:
if len(frame)<capacity:
[Link](page)
else:
[Link](0)
[Link](page)
page_faults+=1
else:
[Link](page)
[Link](page)
print(frame)
print("\nTotal Page Faults:",page_faults)
if __name__ == "__main__":
pages=[7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1]
capacity=3
lru(pages,capacity)
OUTPUT:

Reference string: [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1]

Frame status:

[7]
[7, 0]
[7, 0, 1]
[0, 1, 2]
[1, 2, 0]
[2, 0, 3]
[0, 3, 2]
[3, 2, 4]
[2, 4, 0]
[4, 0, 3]
[0, 3, 2]
[3, 2, 0]
[2, 0, 1]
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
[0, 1, 7]
[1, 7, 0]
[7, 0, 1]
Total Page Faults: 12
9(a). TO IMPLEMENT FIRST FIT ALGORITHM FOR
MEMORY MANAGEMENT

PROGRAM:

def FirstFit(blocksize,blocks,processSize,process):
allocate=[-1]*process
occupied=[0]*blocks
for i in range(process):
for j in range(blocks):
if not occupied[j]and(blockSize[j]>=processSize[i]):
allocate[i]=j
occupied[j]=True
break
print("Process No\t ProcessSize\t Block No")
for i in range(process):
print((i+1),"\t\t",processSize[i],"\t\t",end="")
if allocate[i]!=-1:
print(allocate[i]+1)
else:
print("Not Allocated")
if __name__=="__main__":
blockSize=[100,50,30,120,35]
processSize=[20,60,70,40]
m=len(blockSize)
n=len(processSize)
FirstFit(blockSize,m,processSize,n)
OUTPUT:

Process No Process Size Block No


1 20 1
2 60 4
3 70 Not Allocated
4 40 2
9(b). TO IMPLEMENT BEST FIT ALGORITHM FOR
MEMORY MANAGEMENT

PROGRAM:

def bestfit(blockSize, m, processSize, n):


allocation = [-1] * n

for i in range(n):
bestIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if bestIdx == -1 or blockSize[j] < blockSize[bestIdx]:
bestIdx = j
if bestIdx != -1:
allocation[i] = bestIdx
blockSize[bestIdx] -= processSize[i]

return allocation

blockSize = [100, 500, 200, 300, 600]


processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)
allocation = bestfit(blockSize, m, processSize, n)

print("Process No\tProcess Size\tBlock No")


for i in range(n):
print(f"{i+1}\t\t{processSize[i]}\t\t", end="")
if allocation[i] != -1:
print(f"{allocation[i]+1}")
else:
print("Not allocated")
OUTPUT:

Process No Process Size Block No


1 212 4
2 417 2
3 112 3
4 426 5
9(c). TO IMPLEMENT WORST FIT ALGORITHM FOR
MEMORY MANAGEMENT

PROGRAM:

def worstfit(blockSize, m, processSize, n):


allocation = [-1] * n

for i in range(n):
worstIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if worstIdx == -1 or blockSize[j] > blockSize[worstIdx]:
worstIdx = j

if worstIdx != -1:
allocation[i] = worstIdx
blockSize[worstIdx] -= processSize[i]

print("Process No\tProcess Size\tBlock No")


for i in range(n):
print(f"{i+1}\t\t{processSize[i]}\t\t", end="")
if allocation[i] != -1:
print(allocation[i]+1)
else:
print("Not Allocated")

if __name__ == "__main__":
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)

worstfit(blockSize, m, processSize, n)
OUTPUT:

Process No Process Size Block No


1 212 5
2 417 2
3 112 5
4 426 Not Allocated
10. PROGRAM FOR INTER PROCESS COMMUNICATION

PROGRAM:

import multiprocessing

def sender(conn, messages):


for msg in messages:
[Link](msg)
print("Sent the message:", msg)
[Link]()

def receiver(conn):
while True:
msg = [Link]()
if msg == "END":
break
print("Received the message:", msg)

if __name__ == "__main__":
messages = ["hello", "hey, how are you?", "END"]

parent_conn, child_conn = [Link]()


P1 = [Link](target=sender, args=(parent_conn,
messages))
P2 = [Link](target=receiver, args=(child_conn,))
[Link]()
[Link]()

[Link]()
[Link]()
OUTPUT:

Sent the message: hello


Received the message: hello
Sent the message: hey, how are you?
Received the message: hey, how are you?
Sent the message: END

You might also like