python模拟页面调度LRU算法

所谓LRU算法,是指在发生缺页并且没有空闲主存块时,把最近最少使用的页面换出主存块,腾出地方来调入新页面。

问题描述:一进程获得n个主存块的使用权,对于给定的进程访问页面次序,问当采用LRU算法时,输出发生的缺页次数。

这个题为京东2015年笔试考题,主要考察对LRU算法的理解

代码如下

n = int(input())
def LRU(pages, maxNum):
    temp = []
    times = 0

    for page in lst:
        num = len(temp)
        if num < n:
            times += 1
            temp.append(page)
        elif num == n:                #要访问的新页面已在主存块中
            if page in temp:          #处理“主存块”,把最新访问的页面交换到列表尾部
                pos = temp.index(page)
                temp = temp[:pos] + temp[pos+1:] + [page]
            else:                     #把最早访问的页面踢掉,调入新页面
                temp.pop(0)
                temp.append(page)
                times += 1

    return times


lst = (1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5)
print(LRU(lst, 3))

截图如下

原文地址:https://www.cnblogs.com/liuzhaowei/p/10770783.html