You need to enable JavaScript to run this app. 将C++进程调度代码转换为Python出现IndexError列表索引越界问题
优惠活动
大模型
产品
解决方案
定价
更多

将C++进程调度代码转换为Python出现IndexError列表索引越界问题

C++转Python触发IndexError的错误定位与修正

你的代码转换过程存在多处与原C++逻辑不匹配的实现错误,这是触发IndexError: list index out of range的核心原因,具体错误点如下:

  • 越界索引问题:Python列表采用0基动态索引,当你尝试访问process_arrival[n]、process_burst[n]这类元素时,由于列表实际长度只有n,最大合法索引为n-1,直接越界。原C++代码是固定申请了长度为10的静态数组,所有索引0-9都可合法访问,和Python动态列表的特性完全不匹配。
  • 逻辑混淆导致的哨兵值错位:原C++代码将固定数组的第9位(b[9])设置为9999作为短作业查找的临时哨兵,你在Python实现中每次读取进程输入时都把process_burst[i]赋值为9999,完全覆盖了刚读入的进程突发时间值;同时当你初始化smallest=9时,如果输入的进程数n<9,对应长度的Python列表根本不存在索引9的元素,访问时必然触发越界。
  • 代码结构错位:原C++的主循环是按时间递推、直到所有进程执行完成才退出,你把主逻辑循环嵌到了进程参数读取的for循环内部,导致循环执行时机完全不符合原逻辑。
  • 无意义的类型转换绕路:你原本可以直接存储数值到列表中,却额外给每个列表元素嵌套空列表、再通过字符串拼接转整数,不仅大幅降低执行效率,还提高了索引错位的概率。
  • 变量引用与操作符失效:条件判断中使用了从未定义的int_proc_val;process_burst[smallest] - 1仅做减法计算,没有把结果赋值回列表元素,完全达不到原C++中b[smallest]--的剩余时间减1的效果;结果类列表(completion、waiting、turnaround)初始化时为空列表,后续直接通过索引赋值时,只要索引超出当前列表长度就会触发越界。
  • 循环变量误用:原C++主循环的时间变量是独立递增的,你在实现中用for time in range(n)作为主循环,时间遍历范围仅覆盖进程数,远达不到所有进程执行完成需要的总时长。

对齐原C++逻辑的可运行Python版本

# 初始化固定长度列表,匹配原C++的静态数组哨兵逻辑
n = int(input('Enter the total no of processes: '))
process_arrival = [0] * 10
process_burst = [0] * 10
process_holder = [0] * 10
completion = [0] * 10
waiting = [0] * 10
turnaround = [0] * 10
process_queue = []

count = 0
time = 0
smallest = 9

# 读取进程参数
for i in range(n):
    p_name = input('Enter name: ')
    process_queue.append(p_name)
    process_arrival[i] = int(input('Enter arrival: '))
    process_burst[i] = int(input('Enter burst: '))
    process_holder[i] = process_burst[i]

# 设置查找哨兵值
process_burst[9] = 9999

# 模拟时间推进,直到所有进程执行完成
while count != n:
    smallest = 9
    for i in range(n):
        # 匹配原C++的查找逻辑:已到达、剩余burst更短、burst未耗尽
        if process_arrival[i] <= time and process_burst[i] < process_burst[smallest] and process_burst[i] > 0:
            smallest = i
    # 选中进程的剩余执行时间减1
    process_burst[smallest] -= 1
    # 进程执行完成时计算各项指标
    if process_burst[smallest] == 0:
        count += 1
        end = time + 1
        completion[smallest] = end
        waiting[smallest] = end - process_arrival[smallest] - process_holder[smallest]
        turnaround[smallest] = end - process_arrival[smallest]
    time += 1

# 输出执行结果
print("\nProcess Execution Metrics:")
for i in range(n):
    print(f"Process {process_queue[i]} | Completion: {completion[i]} | Waiting: {waiting[i]} | Turnaround: {turnaround[i]}")
avg_wait = sum(waiting[:n]) / n
avg_turnaround = sum(turnaround[:n]) / n
print(f"Average Waiting Time: {avg_wait:.2f}")
print(f"Average Turnaround Time: {avg_turnaround:.2f}")

内容的提问来源于stack exchange,提问作者Key2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.31 18:15:03