Count letters in a word in python debugging

I am trying to count the number of times “e” appears in a word.

def has_no_e(word):     #counts 'e in a word
    letters = len(word)
    count = 0
    while letters >= 0:
        if word[letters-1] == 'e':
            count = count + 1
        letters = letters - 1
    print count

It seems to work fine, except that the word ends with "e". He will count this "e" twice. I have no idea why. Any help?

I know that my code may be messy, I'm a beginner! I'm just trying to understand the logic of what is happening.

+3
source share
9 answers

As already mentioned, you can implement the test with a simple one word.count('e'). If you do not do this as a simple exercise, it is much better than trying to invent a wheel.

, , -1 , Python . , while letters >= 0 while letters > 0.

, ( ):

  • Python for. , while . , . .
  • +=, . , count = count + 1.
  • , , , . char='e' , .
  • . has_no_e() , , e, , , e.

, :

def count_letter(word, char='e'):
    count = 0
    for c in word:
        if c == char:
            count += 1
    return count

:

>>> count_letter('tee')
2
>>> count_letter('tee', 't')
1
>>> count_letter('tee', 'f')
0
>>> count_letter('wh' + 'e'*100)
100
+9
>>> word = 'eeeooooohoooooeee'
>>> word.count('e')
6

?

+9

def has_no_e(word):
    return sum(1 for letter in word if letter=="e")
+1

while. Python.

def has_no_e(word):
    count = 0
    for letter in word:
        if letter == "e":
            count += 1
    print count

- :

def has_no_e(word):
    return sum(1 for letter in word if letter=="e")
+1

, "" "0", , :

  word[letters-1]

, [-1], python " ".
"", "e".

+1

, e, letters ( while letters >= 0, , letters > 0). letters , word[letters-1] == word[-1], .

+1

.

, Python [-1] .

, , [-1] while, >= 0, "e" ( , -1 , 0).

, "", ( [] .

e ( [3]) t ( [2]) e ( [1]) P ( [0]) e ( [-1])

, Python.

+1

@marcog ;

, -

def has_no_e(word):
    letters = len(word)
    count = 0
    while letters >= 0:
        ch = word[letters-1]         # what is it looking at?
        if ch == 'e':
            count = count + 1
            print('{0} <-'.format(ch))
        else:
            print('{0}'.format(ch))
        letters = letters - 1
    print count

has_no_e('tease')

e <-
s
a
e <-
t
e <-
3

,

  • e
  • you "wrap" to the end of the line - therefore, an extra e if your line ends on one
+1
source

If you really need "has_no_e", then the following might be more appropriate than counting "e" and then checking for zero,

def has_no_e(word):
  return 'e' not in word

>>> has_no_e('Adrian')
True
>>> has_no_e('test')
False
>>> has_no_e('NYSE')
True

If you want to check if there is an "E",

def has_no_e(word):
  return 'e' not in word.lower()

>>> has_no_e('NYSE')
False
+1
source

Source: https://habr.com/ru/post/1782785/


All Articles