繁体   English   中英

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

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

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

  > 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 在文件上写过东西,因此不知道我应该改变什么才能让我的 output 格式正确。 有人能帮我吗? 这是我的代码:

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. 打开文件时使用上下文管理器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM