如何纠正 Python-LaTeX 代码中的符号问题?

问题描述 投票:0回答:1

这个Python代码

import random

# Generate random values of k and m between 1 and 5
k = random.randint(1, 5)
m = random.randint(1, 5)

# Calculate necessary variables
m_k = m - k
m_1 = m - 1
m_plus = m + 1
k_1 = k - 1
k_plus = k + 1

# Create  with the correct answer marked
answers = [
    f"\\checkmark \\; \\frac{{(n+{m}) !}}{{{k} ! (n+{m_k}) !}}",  # Correct answer
    f"\\frac{{(n+{m_1}) !}}{{{k_1} ! (n+{m_k}) !}}",  # Wrong answer
    f"\\frac{{(n+{m_plus}) !}}{{{k_plus} ! (n+{m_k}) !}}",  # Wrong answer
    f"\\frac{{(n+{m}) !}}{{{k_plus} ! (n+{m_k}) !}}"  # Wrong answer
]

# Mix the answers
random.shuffle(answers)

# Generate text in LaTeX format
latex_output = f"""
After simplifying the expression
$$\\frac{{(n+{m_1}) !}}{{{k} ! (n+{m-k-1}) !}} + \\frac{{(n+{m_1}) !}}{{{k-1}! (n+{m-k})!}}$$
indicate which of the following results is correct:

\\[
\\square \\; {answers[0]} \\quad\\quad \\square \\; {answers[1]} \\quad\\quad \\square \\; {answers[2]} \\quad\\quad \\square \\; {answers[3]}
\\]
"""

print(latex_output)

该代码生成一个 LaTeX 格式的数学测验,其中包含一个问题和四个多项选择答案,其中一个是正确的。它在 1 到 5 之间随机选择

k
m
的值,计算派生变量,使用阶乘表达式创建答案,然后对它们进行打乱。最后,它打印 LaTeX 格式的文本来呈现问题和答案。

事实上,有时我会得到这样的结果:


After simplifying the expression
$$\frac{(n+0) !}{1 ! (n+-1) !} + \frac{(n+0) !}{0! (n+0)!}$$
indicate which of the following results is correct:

\[
\square \; \frac{(n+2) !}{2 ! (n+0) !} \quad\quad \square \; \checkmark \; \frac{(n+1) !}{1 ! (n+0) !} \quad\quad \square \; \frac{(n+1) !}{2 ! (n+0) !} \quad\quad \square \; \frac{(n+0) !}{0 ! (n+0) !}
\]

我不喜欢的是:像(n+0)这样的表达式!我更喜欢 n!;和 +- 符号应该表示符号乘积的减号,但我无法更改。对此您有什么建议吗?

python string latex
1个回答
0
投票

您可以尝试以下方法:

import random

# Generate random values of k and m between 1 and 5
k = random.randint(1, 5)
m = random.randint(1, 5)

def f(m):
    if m > 0:
        s = f"(n+{m})!"
    elif m < 0:
        s = f"(n{m})!"
    else:
        s = "n!"
    return s


def g(m, k):
    return f"\\frac{{{f(m)}}}{{{k}!{f(m-k)}}}"


# Create  with the correct answer marked
answers = [
    f"\\blacksquare \\; {g(m, k)}",  # Correct answer
    f"\\square \\; {g(m-1, k-1)}",  # Wrong answer
    f"\\square \\; {g(m+1, k+1)}",  # Wrong answer
    f"\\square \\; {g(m, k+1)}"  # Wrong answer
]

# Mix the answers
random.shuffle(answers)
answers = "\\quad\\quad\n".join(answers)

# Generate text in LaTeX format
latex_output = f"""
After simplifying the expression
$$
{g(m-1, k)} + {g(m-1, k-1)}
$$
indicate which of the following results is correct:

$$
{answers} 
$$
"""
© www.soinside.com 2019 - 2024. All rights reserved.