我的程序无法以预期格式在文件中写入输出

My program can't write output in a file in the expected format

我正在解决我在这个网站上发现的一些编码问题。据我了解,该网站检查我的程序是否输出预期结果的方法是让我逐行将输出写入新文件,然后将我的文件与包含答案的文件进行比较。我正在尝试提交我的问题解决方案,但不断收到以下错误消息:

  > Run 1: Execution error: Your program did not produce an answer
        that was judged as correct. The program stopped at 0.025 seconds;
        it used 9360 KB of memory. At character number 7, your answer says
        '<Newline>' while the correct answer says ' '. 

        Here are the respective outputs:
        ----- our output ---------
        mitnik_2923
        Poulsen_557
        Tanner_128
        Stallman_-311
        Ritchie_-1777
        Baran_245
        Spafford_-1997
        Farmer_440
        Venema_391
        Linus_-599
        ---- your output ---------
        mitnik
        _2923Poulsen
        _557Tanner
        _128Stallman
        _-311Ritchie
        _-1777Baran
        _245Spafford
        _-1997Farmer
        _440Venema
        _391Linus
        _-599
        --------------------------

我很确定我的程序输出了预期的结果,但格式错误。现在,我以前从未使用 Python 在文件上写过东西,因此不知道我应该更改什么以使我的输出格式正确。有人能帮我吗?这是我的代码:

fin = open ('gift1.in', 'r')
fout = open ('gift1.out', 'w')
NP,d=int(fin.readline()),dict()
for _ in range(NP):
    d[fin.readline()]=0
for _ in range(NP):
    giver=fin.readline()
    amt,ppl=list(map(int,fin.readline().split()))
    if ppl==0 or amt==0:sub=-amt;give=0
    else:sub=amt-(amt%ppl);give=amt//ppl
    d[giver]-=sub
    for per in range(ppl):
        d[fin.readline()]+=give
for i in d: ##I'm doing the outputting in this for loop..
    ans=str(i)+' '+str(d[i])
    fout.write(ans)
fout.close()
  1. find.readline() 返回的行包括结尾的换行符。在将其用作字典键之前,您应该将其删除。这就是为什么您会在所有名称后看到一个换行符。
  2. fout.write() 不会在您编写的字符串后添加换行符,您需要明确添加。这就是为什么号码和下一个名字之间没有换行符的原因。
with open ('gift1.in', 'r') as fin:
    NP = int(fin.readline())
    d = {fin.readline().strip(): 0 for _ in range(NP)}
    for _ in range(NP):
        giver=fin.readline().strip()
        amt, ppl= map(int,fin.readline().split())
        if ppl==0 or amt==0:
            sub=-amt
            give=0
        else:
            sub=amt-(amt%ppl)
            give=amt//ppl
        d[giver]-=sub
        for per in range(ppl):
            d[fin.readline().strip()]+=give

with open ('gift1.out', 'w') as fout:
    for i in d: ##I'm doing the outputting in this for loop..
        ans= i + " " + str(d[i])+'\n'
        fout.write(ans)

其他要点:

  1. 不要不必要地将多个作业塞到同一行。并且无需将 ifelse 全部放在 1 行上。
  2. i是字符串,不用str(i)
  3. 打开文件时使用上下文管理器。