Skip to content Skip to sidebar Skip to footer

What Causes The Nzec (non Zero Exit Code) Error In My Sums In A Triangle Solution?

I was doing this practice problem on codechef. I have already solved this in C and was trying to do the same in Python 2.7. I am getting NZEC error on codechef judge which is 'Non

Solution 1:

Don't mix using the file object as an iterator, and calling .readline() on the object.

By using islice() on sys.stdin you are treating the object as an iterator, calling file.next() under the hood. From the .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.

The solution is to not use .readline()or not to use the file object as iterator. In this case, use next(sys.stdin) instead of sys.stdin.readline() to consistently use the object as an iterator. That is more efficient than using .readline() in any case:

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)]

or even:

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

Solution 2:

change this line:

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

to this:

triangle = [map(int, sys.stdin.readline().split()) for_ in xrange(height)]

From the docs:

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

#so.pyimport sys
from itertools import islice
printlist(islice(sys.stdin,3))
print sys.stdin.readline()

Demo:

$ 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 andread methods would lose data

Solution 3:

Post a Comment for "What Causes The Nzec (non Zero Exit Code) Error In My Sums In A Triangle Solution?"