什么原因导致我在三角形解的求和中出现NZEC(非零退出码)错误?

2024-05-13 20:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做codechef的this practice problem。我已经solved this in C,并试图在Python2.7中做同样的事情。我得到了NZEC错误的codechef判断,这是“非零退出代码”。我不明白为什么会这样。这个程序在我的电脑上运行得很好。什么样的情况会导致这个问题?在

import sys
from itertools import islice

def p(): 
    cases = int(sys.stdin.readline())
    for case in xrange(cases):
        height = int(sys.stdin.readline())
        triangle = [map(int, i.split()) for i in islice(sys.stdin,height)]

        prev_row = triangle[0]
        for i in xrange(1, height):
            cur_row = triangle[i]

            cur_row[0] += prev_row[0]
            cur_row[len(cur_row) - 1] += prev_row[len(prev_row) - 1]

            for j in xrange(1, len(cur_row) - 1):
                if(prev_row[j - 1] > prev_row[j]):
                    cur_row[j] += prev_row[j - 1]
                else:
                    cur_row[j] += prev_row[j]

            prev_row = cur_row

        print max(prev_row)

p()

Tags: inimportforlenstdinsysthisint
3条回答

请查看Codechef常见问题解答:

http://www.codechef.com/wiki/faq#Why_do_I_get_an_NZEC

更改此行:

triangle = [map(int, i.split()) for i in islice(sys.stdin,height)]

为此:

^{pr2}$

docs

As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

#so.py
import sys
from itertools import islice
print list(islice(sys.stdin,3))
print sys.stdin.readline()

演示:

$ python so.py <abc
['2\n', '3\n', '1\n']
Traceback (most recent call last):
  File "so.py", line 4, in <module>
    print sys.stdin.readline()
ValueError: Mixing iteration and read methods would lose data

不要混合使用file对象作为迭代器,并在对象上调用.readline()

通过在sys.stdin上使用islice(),您将对象视为迭代器,在幕后调用file.next()。从^{} documentation

In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

解决方案是不使用.readline()不将file对象用作迭代器。在本例中,使用next(sys.stdin)而不是sys.stdin.readline()来一致地将对象用作迭代器。这在任何情况下都比使用.readline()更有效:

def p(): 
    cases = int(next(sys.stdin))
    for case in xrange(cases):
        height = int(next(sys.stdin))
        triangle = [map(int, i.split()) for i in islice(sys.stdin, height)]

甚至:

^{pr2}$

相关问题 更多 >