Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 45e0411

Browse files
authored
Simplify negativity checks in math.comb and math.perm. (GH-13870)
1 parent 5529515 commit 45e0411

1 file changed

Lines changed: 16 additions & 10 deletions

File tree

Modules/mathmodule.c

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3056,6 +3056,12 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
30563056
"n must be a non-negative integer");
30573057
goto error;
30583058
}
3059+
if (Py_SIZE(k) < 0) {
3060+
PyErr_SetString(PyExc_ValueError,
3061+
"k must be a non-negative integer");
3062+
goto error;
3063+
}
3064+
30593065
cmp = PyObject_RichCompareBool(n, k, Py_LT);
30603066
if (cmp != 0) {
30613067
if (cmp > 0) {
@@ -3072,11 +3078,8 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
30723078
LLONG_MAX);
30733079
goto error;
30743080
}
3075-
else if (overflow < 0 || factors < 0) {
3076-
if (!PyErr_Occurred()) {
3077-
PyErr_SetString(PyExc_ValueError,
3078-
"k must be a non-negative integer");
3079-
}
3081+
else if (factors == -1) {
3082+
/* k is nonnegative, so a return value of -1 can only indicate error */
30803083
goto error;
30813084
}
30823085

@@ -3176,6 +3179,12 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
31763179
"n must be a non-negative integer");
31773180
goto error;
31783181
}
3182+
if (Py_SIZE(k) < 0) {
3183+
PyErr_SetString(PyExc_ValueError,
3184+
"k must be a non-negative integer");
3185+
goto error;
3186+
}
3187+
31793188
/* k = min(k, n - k) */
31803189
temp = PyNumber_Subtract(n, k);
31813190
if (temp == NULL) {
@@ -3204,11 +3213,8 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
32043213
LLONG_MAX);
32053214
goto error;
32063215
}
3207-
else if (overflow < 0 || factors < 0) {
3208-
if (!PyErr_Occurred()) {
3209-
PyErr_SetString(PyExc_ValueError,
3210-
"k must be a non-negative integer");
3211-
}
3216+
if (factors == -1) {
3217+
/* k is nonnegative, so a return value of -1 can only indicate error */
32123218
goto error;
32133219
}
32143220

0 commit comments

Comments
 (0)