Using two for nested is unnecessary and very inefficient, with only one% of% we do the same but with fewer resources and more 'pythonic':
texto=raw_input("ingrese un texto: ")
letra=raw_input("ingrese una letra: ")
contador = 0
for palabra in texto.split():
if letra in palabra:
contador += 1
print contador
Another solution that is somewhat more efficient and has less code is to use a generator and the preconstructed function in
:
texto=raw_input("ingrese un texto: ")
letra=raw_input("ingrese una letra: ")
print(sum(letra in palabra for palabra in texto.split()))
The comparison using a text of 80000000 words (in my particular case and under Python 2.7):
2 cycles for equality: 49.6679999828 seconds.
sum and generator: 16,3229999542 seconds.
1 cycle for and in: 13.4120001793 seconds.
P.D: Your code fails by the order of evaluation of your sum
sentence, your line is:
if letra in caracter==True:
It might seem that what this does is evaluate if
(which returns letra in caracter
or False
) and then see if the result is True
. But the problem is that this is not what happens, first evaluate the equality ( True
and then the ==
). Let's imagine the following:
if 'a' in 'a' == True:
print 'Si'
If we execute it, it does not print anything, the problem is that it is first done:
'a' == True
This logically is in
, the rest no longer makes sense so the False
returns if
. To fix it we can add a parenthesis to evaluate in the order we want:
if ('a' in 'a') == True:
print 'Si'
In your case it would be:
if (letra in caracter) == True:
contador=contador+1
But this is redundancy, in Python it would be enough:
if letra in caracter:
contador=contador+1
But remember that this would count all the letters equal to the one introduced in the sentence and not the words that contain the letter, the solution is to eliminate the second False
as I mentioned earlier.