簡體   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