int main() { // Trie *trie = trie_init("phones/letters.txt"); // trie_add_word(trie, "o n e", "W AX N"); // trie_add_word(trie, "t w o", "T UW"); // trie_add_word(trie, "t h r e e", "TH R IY"); // trie_add_word(trie, "f o u r", "F OW R"); // char *target_word = "f o u r"; Trie *trie = trie_init("phones/phones.txt"); trie_add_word(trie, "W AX N", "one"); trie_add_word(trie, "T UW", "two"); trie_add_word(trie, "TH R IY", "three"); trie_add_word(trie, "F OW R", "four"); char *target_word = "F OW R"; char *result = trie_find_word(trie, target_word); if (result == NULL) { fprintf(stderr, "Not found\n"); } else { fprintf(stderr, "%s\n", result); } }
static PyObject* automaton_add_word(PyObject* self, PyObject* args) { #define automaton ((Automaton*)self) // argument PyObject* py_word = NULL; PyObject* py_value = NULL; TRIE_LETTER_TYPE* word = NULL; ssize_t wordlen = 0; int integer = 0; py_word = pymod_get_string_from_tuple(args, 0, &word, &wordlen); if (not py_word) return NULL; switch (automaton->store) { case STORE_ANY: py_value = PyTuple_GetItem(args, 1); if (not py_value) { PyErr_SetString(PyExc_ValueError, "second argument required"); return NULL; } break; case STORE_INTS: py_value = PyTuple_GetItem(args, 1); if (py_value) { if (PyNumber_Check(py_value)) { integer = (int)PyNumber_AsSsize_t(py_value, PyExc_ValueError); if (integer == -1 and PyErr_Occurred()) return NULL; } else { PyErr_SetString(PyExc_TypeError, "number required"); return NULL; } } else { // default PyErr_Clear(); integer = automaton->count + 1; } break; case STORE_LENGTH: integer = wordlen; break; default: PyErr_SetString(PyExc_SystemError, "invalid store value"); return NULL; } if (wordlen > 0) { bool new_word = false; TrieNode* node; node = trie_add_word(automaton, word, wordlen, &new_word); Py_DECREF(py_word); if (node) { switch (automaton->store) { case STORE_ANY: if (not new_word and node->eow) // replace Py_DECREF(node->output.object); Py_INCREF(py_value); node->output.object = py_value; break; default: node->output.integer = integer; } // switch if (new_word) { automaton->version += 1; // change version only when new word appeared if (wordlen > automaton->longest_word) automaton->longest_word = wordlen; Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } else return NULL; } Py_DECREF(py_word); Py_RETURN_FALSE; }