4
0
SystemsProgrammingAndOperat.../Codes/Group B/Assignment - 5/mem.py

80 lines
2.2 KiB
Python

blocks = [100,500,200,400, 300]
processes = [110,50,410]
def firstfit():
block1= blocks.copy()
for p in processes:
for b in block1:
if b>=p:
print(f"P {p} allocated to B {b}")
block1.pop(block1.index(b))
break
else: print(f"P {p} not allocated")
print(f"Blocks empty: ", block1)
print(blocks,"\n",processes)
print("\n\n FF:")
firstfit()
def bestfit():
block1= sorted(blocks)
for p in processes:
for b in block1:
if b>=p:
print(f"P {p} allocated to B {b}")
block1.pop(block1.index(b))
break
else: print(f"P {p} not allocated")
print(f"Blocks empty: ", block1)
print("\n\n BF:")
bestfit()
'''
Common External Q: why tha fuck was worst fit even invented?
->coz in bestfit, we have small spaces left in all the blocks.unuseable.
But in worstfit, we have one large space in the biggest block. so we can put in one more process if extra.
This is called External Fragmentation...
so, Worstfit is better than Bestfit
Answer by Afan Shaikh'''
def worstfit():
block1= sorted(blocks, reverse=True)
for p in processes:
for b in block1:
if b>=p:
print(f"P {p} allocated to B {b}")
block1.pop(block1.index(b))
break
else: print(f"P {p} not allocated")
print(f"Blocks empty: ", block1)
print("\n\n WF:")
worstfit()
'''
NF:
You need to know working of NF, before understanding it's code.
start is the starting index for current iteration. at end, we do start++
the ind= i%n wraps the index around, like a circle.
After allocation, I make block=0 to mark allocated. Who tf is gonna cross check?
'''
def nextfit():
start = 0
n = len(blocks)
for p in processes:
for i in range(start, start +n):
ind = i % n
if blocks[ind] >= p:
print(f"P {p} allocated to B {blocks[ind]}")
blocks[ind] = 0
start = (ind +1 ) % n
break
else: print(f'P {p} not allocated')
a=[x for x in blocks if x>0]
print("Blocks empty: ", a)
print("\n\n NF:")
nextfit()