Home > other >  Why does the code output the answer only for the first test?
Why does the code output the answer only for the first test?

Time:11-16

I have the task based on this task. In short, I have some boolean equation that needs to be solved (I don't think it's necessary, but you can read about the task type here). The only difference is that there can be several tests in 1 input (I don't know exactly how many, so I use this function to find out the length of the entire input: sys.stdin.readlines()).

import sys

def dfs(word, some_list):
    if len(word) == n   1:
        sat(word, some_list)
        return
    for a in range(2):
        dfs(word [a], some_list)


def sat(word, some_list):
    for xi, xj in some_list:
        element_1 = word[xi] if xi > 0 else not word[-xi]
        element_2 = word[xj] if xj > 0 else not word[-xj]
        if (element_1 or element_2) == 0:
            return
    for i in range(1, n 1):
        print(word[i], end='')
    exit()


data = sys.stdin.readlines()
id = 0

while id < len(data) - 1:
    n, m = map(int, data[id ].split(" "))
    id  = 1
    some_list = []
    for _ in range(m):
        x, y = map(int, data[id ].split(" "))
        some_list .append([x, y])
        id  = 1)
    dfs([], some_list)

The algorithm itself works correctly for the task (on each specific test), but there is a problem with data entry. If there are more than one tests, it displays only the result for the first one, and ignores the rest.

There is the following input based on 3 tests. First there are 2 numbers n and m. Next in m lines are different x, y.

In:

3 4 #First test
1 -2
-1 3
1 -3
-1 1
3 4 #Second test
-1 2
-2 3
1 3
3 2
1 0 #Third test

Required output:

000 #First test result
001 #Second test result
0   #Third test result

My output:

000 #First test result

However, if you enter the tests separately, then everything works correctly. What could be the solution here?

CodePudding user response:

You're using the exit() function, which basically terminates the execution as soon as the solution for the first test case is found. You'll need to remove that for the execution to continue (your output will still be incorrect though, since you're invoking helper functions multiple times. Finding/storing the answer for each state will be a different task).

You can read more about exit() and other alternatives here.

  • Related