[pyar] String.count - WTF?

Terry Reedy tjreedy en udel.edu
Mie Jun 20 18:22:39 ART 2012


On 5/31/2012 9:31 PM, Claudio Freire wrote:
> On Thu, May 31, 2012 at 10:19 PM, Martin Cerdeira
> <martincerdeira en gmail.com> wrote:
>>>>> "hola".count("")
>> 5
>>
>> Como, seguramente hay una explicación que vuelva lo "antinatural" en
>> un "ahhh!! era por eso!!!", pregunto: ma per que??
>
> La corta: es un bug.

No es un bug.

> La larga:
>
> count(...)
>      S.count(sub[, start[, end]]) -> int
>
>      Return the number of non-overlapping occurrences of substring sub in
>      string S[start:end].  Optional arguments start and end are interpreted
>      as in slice notation.

'occurrence': S[i:j] == sub

> Así que, técnicamente hablando, hay 4 posiciones claras donde ""
> ocurre: 0, 1, 2, 3

y 4: 'hola'[4:4] == ''

non-overlapping: S[i:j] == S[k:l] == sub y i<k and j<=k
(necessita i<k cuando sub == '' y i==j and k==l)

def count(string, sub):
     k = len(sub)
     inc = k if k else 1  # para evitar 'infinite loop' cuando sub == ''
     n = 0
     i = 0
     end = len(string) - k
     while i <= end:
         if string[i:i+k] == sub:
             n += 1
             i += inc
         else:
             i += 1
     return n

string = 'hola'
for sub in ('', 'h', 'ol', 'a', 'x'):
     if count(string, sub) != string.count(sub):
         print('bad', string, sub, string.count(sub), count(string, sub))
# nada

string = 'aaaaa'
for sub in ('', 'a', 'aa', 'aaa', 'aaaaa'):
     if count(string, sub) != string.count(sub):
         print('bad', string, sub, string.count(sub), count(string, sub))
# nada

string = ''
for sub in ('', 'h'):
     if count(string, sub) != string.count(sub):
         print('bad', string, sub, string.count(sub), count(string, sub))
# nada

-- 
Terry Jan Reedy







More information about the pyar mailing list