listing17-6.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <Python.h>
  2. static PyObject *is_palindrome(PyObject *self, PyObject *args) {
  3. int i, n;
  4. const char *text;
  5. int result;
  6. /* "s" means a single string: */
  7. if (!PyArg_ParseTuple(args, "s", &text)) {
  8. return NULL;
  9. }
  10. /* The old code, more or less: */
  11. n=strlen(text);
  12. result = 1;
  13. for (i = 0; i <= n/2; ++i) {
  14. if (text[i] != text[n-i-1]) {
  15. result = 0;
  16. break;
  17. }
  18. }
  19. /* "i" means a single integer: */
  20. return Py_BuildValue("i", result);
  21. }
  22. /* A listing of our methods/functions: */
  23. static PyMethodDef PalindromeMethods[] = {
  24. /* name, function, argument type, docstring */
  25. {"is_palindrome", is_palindrome, METH_VARARGS, "Detect palindromes"},
  26. /* An end-of-listing sentinel: */
  27. {NULL, NULL, 0, NULL}
  28. };
  29. static struct PyModuleDef palindrome =
  30. {
  31. PyModuleDef_HEAD_INIT,
  32. "palindrome", /* module name */
  33. "", /* docstring */
  34. -1, /* signals state kept in global variables */
  35. PalindromeMethods
  36. };
  37. /* An initialization function for the module: */
  38. PyMODINIT_FUNC PyInit_palindrome(void)
  39. {
  40. return PyModule_Create(&palindrome);
  41. }