You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7在HackerEarth遇NZEC错误,求排查解决(附代码)

排查Python 2.7在HackerEarth上的NZEC错误

First off, NZEC (Non-Zero Exit Code) in Python usually means your program crashed from an uncaught exception—like an index out of bounds, EOF error, or logical mistake that blows up execution. Let's walk through exactly what's wrong with your code and how to fix it.

1. The Biggest Culprit: Broken Element Allocation Logic

Your loop structure for filling f_list is fundamentally flawed. Right now you're using:

for i in range(len(key_size)):
    for j in range(num_of_keys):
        if len(f_list[j]) < key_size[j]:
            f_list[j].append(l[pos])
            pos = pos -1

Here's the problem:

  • You only loop len(key_size) times (e.g., if key_size has 2 elements, you loop twice). But you actually need to loop sum(key_size) times—that's the total number of elements you need to distribute.
  • Worse, you don't break out of the inner j loop after adding an element. So in one outer loop iteration, you might add multiple elements to different f_list sublists, causing pos to decrement rapidly. Eventually, pos will go beyond the negative bounds of l (like pos = -len(l)-1), triggering an IndexError and crashing the program (which causes NZEC).

2. Shaky Input Handling

  • When you read the initial list with [int(x) for x in(raw_input().split())], you don't enforce that it has exactly N elements. If the input line has more or fewer elements than N, your l will be the wrong length, leading to unexpected behavior later.
  • Similarly, you don't check that key_size has exactly num_of_keys elements. If the input line for key sizes is too short, accessing key_size[j] for some j will throw an IndexError.
  • If the test case input ends prematurely (missing a line), raw_input() will throw an EOFError, which also causes NZEC.

3. No Guardrails for Index Out of Bounds

Even if your loop logic was correct, you don't check if sum(key_size) exceeds the length of l. If you try to pull more elements than exist in l, pos will go out of bounds and crash the program.


Fixing the Code

Let's rewrite the problematic parts step by step:

Step 1: Fix the Allocation Loop

We need to loop exactly sum(key_size) times (capped at the length of l to avoid index issues), and break out of the inner loop once we add an element to a sublist:

total_elements = sum(key_size)
# Don't try to allocate more elements than we have
total_elements = min(total_elements, len(l))

for _ in range(total_elements):
    for j in range(num_of_keys):
        if len(f_list[j]) < key_size[j]:
            f_list[j].append(l[pos])
            pos -= 1
            break  # Move to the next element after filling one slot

Step 2: Hardened Input Reading

Ensure we read exactly the number of elements we need, and handle cases where input lines are shorter than expected:

N = int(raw_input())
# Read exactly N elements, ignore extra ones if present
raw_list = raw_input().split()
l = selsort([int(x) for x in raw_list[:N]])

num_of_keys = int(raw_input())
raw_key_size = raw_input().split()
key_size = [int(x) for x in raw_key_size[:num_of_keys]]
# Fill in zeros if we didn't get enough key sizes (defensive programming)
while len(key_size) < num_of_keys:
    key_size.append(0)

Step 3: Wrap in a Main Function with Error Handling

To catch any unexpected exceptions (and avoid NZEC from uncaught errors), wrap your code in a main function with a try-except block (you can remove the print statement for production, but it's helpful for debugging):

def selsort(l):
    for start in range(len(l)):
        pos = start
        for i in range(start, len(l)):
            if l[i] < l[pos]:
                pos = i
        l[pos], l[start] = l[start], l[pos]
    return l  # Parentheses here are unnecessary but harmless

def main():
    try:
        # All your input and logic here
        N = int(raw_input())
        raw_list = raw_input().split()
        l = selsort([int(x) for x in raw_list[:N]])
        
        num_of_keys = int(raw_input())
        raw_key_size = raw_input().split()
        key_size = [int(x) for x in raw_key_size[:num_of_keys]]
        while len(key_size) < num_of_keys:
            key_size.append(0)
        
        f_list = [[] for _ in range(num_of_keys)]
        pos = -1
        
        total_elements = sum(key_size)
        total_elements = min(total_elements, len(l))
        
        for _ in range(total_elements):
            for j in range(num_of_keys):
                if len(f_list[j]) < key_size[j]:
                    f_list[j].append(l[pos])
                    pos -= 1
                    break
        
        # Add any output logic here (e.g., print the f_list as required by the problem)
        # Example:
        # for sublist in f_list:
        #     print(' '.join(map(str, sublist)))
    except Exception as e:
        print("Debug error:", e)  # Remove this line when submitting to HackerEarth

if __name__ == "__main__":
    main()

Quick Notes

  • Your selection sort implementation is correct—no issues there.
  • The NZEC error was almost certainly triggered by the index out of bounds from the broken loop logic, but fixing the input handling makes your code more robust against edge cases in test cases.

内容的提问来源于stack exchange,提问作者ps3790

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:06:00