更好的编码python [英] Better Coding python

查看:65
本文介绍了更好的编码python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的这个项目将从文本文件中读取空闲内存段的大小和进程的大小,然后尝试使用最适合、最适合和最差的每个进程分配内存分区-拟合分配算法.下面是我写的代码的第一部分.你觉得我怎样才能把这个安排得更简洁更简短?

This project I'm dealing with will read the size of free memory segments and size of processes from a text file and then will try to allocate a memory partition for each process using the first-fit, best-fit and worst-fit allocation algorithms. Below is the first part of the code I wrote. How do you think I can arrange this in a more neat and short form?

import sys

filename = sys.argv[1]

with open(filename, "r") as file:
        free_memory = file.readline().strip().split(',')
        process_size = list(map(int, file.readline().strip().split(',')))       

file = open("output.txt","w")



    #---------------------------#
#First-Fit Memory Allocation#
#---------------------------#

file.write(f"First-Fit Memory Allocation\n{'-'*60}\n")
file.write(f"start => {' '.join(free_memory)}\n")

memory = list(map(int, free_memory))
memory_str = list(free_memory)
for process in process_size:
        data = f"{process} => "
        allocated = False
        for index in range(len(memory)):
                if not allocated and memory[index] >= process:
                        memory[index] -= process
                        memory_str[index] = memory_str[index][:-1*len(str(process))]
                        memory_str[index] += f"{process}*" 

                        if(memory[index] != 0):
                                memory_str[index] += f" {memory[index]}"
                        allocated = True
                
                data += f"{memory_str[index]} " 

        if(not allocated):
                data = f"{process} => not allocated, must wait"              

        file.write(data+'\n')           

推荐答案

一些建议:

  1. 创建函数
  2. 将您的代码分解成结构,以便他人更好地理解.
  3. 如果需要,您可以添加更多评论以获得更好的文档.

这篇关于更好的编码python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆