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., ifkey_sizehas 2 elements, you loop twice). But you actually need to loopsum(key_size)times—that's the total number of elements you need to distribute. - Worse, you don't break out of the inner
jloop after adding an element. So in one outer loop iteration, you might add multiple elements to differentf_listsublists, causingposto decrement rapidly. Eventually,poswill go beyond the negative bounds ofl(likepos = -len(l)-1), triggering anIndexErrorand 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 exactlyNelements. If the input line has more or fewer elements thanN, yourlwill be the wrong length, leading to unexpected behavior later. - Similarly, you don't check that
key_sizehas exactlynum_of_keyselements. If the input line for key sizes is too short, accessingkey_size[j]for somejwill throw anIndexError. - If the test case input ends prematurely (missing a line),
raw_input()will throw anEOFError, 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

