105: #line 1325 "mxTools.pak" 106: def _bool(x): 107: if x: return 1 108: else: return 0 109: 110: def count(condition,sequence): 111: x = 0 112: for value in sequence: 113: x = x + _bool(condition(value)) 114: return x 115:
1132: #line 1336 "mxTools.pak" 1133: 1134: Py_C_Function( mxTools_count, 1135: "count(condition,sequence)\n\n" 1136: "Count the number of objects in sequence for which the\n" 1137: "selection function condition returns true and return the\n" 1138: "result as integer.") 1139: { 1140: PyObject *condition; 1141: PyObject *list; 1142: PyObject *argtuple = 0; 1143: register int i; 1144: register int n; 1145: int length; 1146: 1147: Py_Get2Args("OO",condition,list); 1148: 1149: length = PySequence_Length(list); 1150: if (length < 0) 1151: Py_Error(PyExc_TypeError, 1152: "second argument must be a sequence"); 1153: 1154: argtuple = PyTuple_New(1); 1155: if (!argtuple) 1156: goto onError; 1157: 1158: for(i = 0, n = 0; i < length; i++) { 1159: register PyObject *v; 1160: register PyObject *w; 1161: 1162: v = PySequence_GetItem(list,i); 1163: if (!v) 1164: goto onError; 1165: 1166: /* Replace the argtuple entry with the new item */ 1167: Py_XDECREF(PyTuple_GET_ITEM(argtuple,0)); 1168: PyTuple_SET_ITEM(argtuple,0,v); 1169: 1170: /* Let's see what condition thinks about this item */ 1171: w = PyEval_CallObject(condition,argtuple); 1172: if (!w) 1173: goto onError; 1174: if (PyObject_IsTrue(w)) 1175: n++; 1176: Py_DECREF(w); 1177: } 1178: 1179: Py_DECREF(argtuple); 1180: return PyInt_FromLong((long)n); 1181: onError: 1182: Py_XDECREF(argtuple); 1183: return NULL; 1184: } 1185: