Random truth table with pythontex

Added by Paco Riviere over 3 years ago

With the command building any 2 variable truth table (https://project.auto-multiple-choice.net/boards/2/topics/11192?page=1&r=11222):

\begin{pythontexcustomcode}{py}
def taulaveritat2(hd):
    print(r"\begin{tabular}{c c|c}")
    print(r"$A$ & $B$ &  %s \\ \hline" % hd)
    for a in range(0, 2):
        for b in range(0, 2):
            print(r"%d & %d & %d \\" % (a, b, lofu(a,b)))
    print(r"\end{tabular}")
\end{pythontexcustomcode}

The idea is:
1 We build two Python lists, one with all the operators and another with their names.
2. We choose a random i in the lists range
3. We build the table with element i from the first list
4. We ask the name of the table. The answer is the element i in the second list.
5. We need some incorrect choices

The code I am testing is:

\begin{pycode}
# step 1
operador = ["a or b", "a and b", "not (a or b)", "not (a and b)", "a ^ b", "not(a^b)"]
nom = ["O", "I", "NO-O", "NO-I", "XOR", "XNOR"]

# step 2
import numpy as np
np.random.seed(12345)
i=np.random.randint(0,5)
# just for testing:
print (i, operador[i], nom[i])
\end{pycode}
% Also a test:
\pys{!{operador[i]}}

% step 3
Question: What is the function of the following truth table?
\begin{pycode}
def lofu(a,b):
    return a or b ### This fails with 'return operador[i]' ###
\end{pycode}
We asking \pyc{print(operador[i])}

\pyc{taulaveritat2("F")}

% step 4
The correct answer is
\pyc{print(nom[i])}\\

% step 5
Wrong values % Cannot use +5 here as there would be two righr answers
\pyc{print(nom[(i+1)%5])}, 
\pyc{print(nom[(i+3)%5])},
\pyc{print(nom[(i+4)%5])}\\

It works as expected, except the return statement. As if we use:
return a or be it works
but with
return operador[i] Which is what we need, it fails.

Using pysub also fails:
<\pre>
\begin{pysub}
def lofu(a,b):
return !{operador[i]}
\end{pysub}

What is wrong with the return statement?