Worst Fit Program In Python

Worst Fit algorithm in OS

Worst Fit Program in Python

The operating system is responsible to allocate memory to the different processes under execution. The empty memory is allocated to these processes at dynamic time on the basis of different memory management schemes. The most common schemes among them are the best fit, worst fit, and the first fit.

The operating system is responsible to allocate memory to the different processes under execution. The empty memory is allocated to these processes at dynamic time on the basis of different memory management schemes. The most common schemes among them are the best fit, worst fit, and the first fit.

In the case of worst fit memory allocation method, the CPU searches for the empty memory block which is equal or greater than the memory size demanded by the process. The empty memory block is allocated to the process as soon as it is found. The allocation scheme is said to be the worst fit method as it sometimes causes maximum wastage of valuable memory space. An aerating system allocates this memory based using an algorithm also known as the scheduling algorithm.

Program code for Worst Fit Memory Management Scheme using Python:

# Method to assign empty memory to processes using the worst fit algorithm 
    
def worstfit(b_size, m, p_size, n): 

      
#code to store the memory block id during the allocation process   
# No code is allocated at the initial stage
      
 allocate = [-1] * n 

      
#select each process and search for an empty memory block as per its memory demand
    
    for i in range(n): 

# Find an empty memory block for the current process 
    
        wstIdx = -1
        for j in range(m): 
            if b_size[j] >= p_size[i]: 
                if wstIdx == -1:  
                    wstIdx = j  
                elif b_size[wstIdx] < b_size[j]:  
                    wstIdx = j 
   
#code to find an empty block for the current process        
    
 if wstIdx != -1: 
              
            # allocating empty memory space j to p[i] process  
            allocate[i] = wstIdx  

  
            # Reduce available memory in this block. 
     
            b_size[wstIdx] -= p_size[i] 
  
    
    print    ("Process Number Process Size Block Number") 
    for i in range(n): 
    
        print
    
(i + 1, "       ",  
              p_size[i], end = "    ")  
        if allocate[i] != -1: 
            print(allocate[i] + 1)  
        else:
     
            print
    
("Not Allocated") 

 
     
# Driver code  
if __name__ == '__main__': 
    b_size = [100, 500, 200, 300, 600]  
    p_size = [212, 417, 112, 426]  
    m = len(b_size)  
    n = len(p_size)  
  
    worstfit(b_size, m, p_size, n)

Output

[table id=679 /]