Match beginning of two strings
John Machin
sjmachin at lexicon.net
Mon Aug 4 09:55:23 EDT 2003
On Mon, 04 Aug 2003 11:56:04 GMT, Alex Martelli <aleax at aleax.it>
wrote:
> I'm not sure where I went wrong in
>the Pyrex coding (it doesn't seem to be performing anywhere
>as well as I thought it might) and I'll be happy for real
>Pyrex expert to show me the way.
I don't call myself an expert, but here's my best shot:
If you look at the generated C code, you'll see lots of conversion
between C and Python types. The trick is to get your args into C, stay
in C as much as possible, and ship back a Python return value.
It's made harder with strings as there is not (yet) any way of hinting
to Pyrex to use the "s#" gadget, you have to DIY, see below.
cdef extern from "Python.h":
int PyString_Size(object s)
def exa2(arga, argb):
cdef int la, lb, lmin, i
cdef char *a, *b
a = arga
b = argb
la = PyString_Size(arga)
lb = PyString_Size(argb)
# living dangerously, not testing for error;
# Easy to eyeball for correctness in this case,
# but ...
if la <= lb:
lmin = la
else:
lmin = lb
i = 0
while i < lmin:
if a[i] != b[i]:
return arga[:i]
i = i + 1
if lmin == la:
return arga
else:
return argb
More information about the Python-list
mailing list