在python调试中计算单词中的字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4563552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:20:33  来源:igfitidea点击:

Count letters in a word in python debug

pythoncountletter

提问by Johnny

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

我正在尝试计算 'e' 在一个单词中出现的次数。

def has_no_e(word):     #counts 'e's 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 when the word ends with an 'e'. It will count that 'e' twice. I have no idea why. Any help?

除非单词以“e”结尾,否则它似乎工作正常。它会计算 'e' 两次。我不知道为什么。有什么帮助吗?

I know my code may be sloppy, I'm a beginner! I'm just trying to figure out the logic behind what's happening.

我知道我的代码可能很草率,我是初学者!我只是想弄清楚正在发生的事情背后的逻辑。

采纳答案by moinudin

As others mention, you can implement the test with a simple word.count('e'). Unless you're doing this as a simple exercise, this is far better than trying to reinvent the wheel.

正如其他人提到的,您可以使用简单的word.count('e'). 除非您将其作为一个简单的练习来进行,否则这比尝试重新发明轮子要好得多。

The problem with your code is that it counts the last character twice because you are testing index -1at the end, which in Python returns the last character in the string. Fix it by changing while letters >= 0to while letters > 0.

您的代码的问题在于它对最后一个字符进行了两次计数,因为您在最后测试索引-1,在 Python 中它返回字符串中的最后一个字符。通过更改while letters >= 0为 来修复它while letters > 0

There are other ways you can tidy up your code (assuming this is an exercise in learning):

还有其他方法可以整理代码(假设这是一个学习练习):

  • Python provides a nice way of iterating over a string using a forloop. This is far more concise and easier to read than using a whileloop and maintaining your own counter variable. As you've already seen here, adding complexity results in bugs. Keep it simple.
  • Most languages provide a +=operator, which for integers adds the amount to a variable. It's more concise than count = count + 1.
  • Use a parameter to define which character you're counting to make it more flexible. Define a default argument for using char='e'in the parameter list when you have an obvious default.
  • Choose a more appropriate name for the function. The name has_no_e()makes the reader think the code checks to see if the code has no e, but what it actually does is counts the occurrences of e.
  • Python 提供了一种使用for循环遍历字符串的好方法。这比使用while循环和维护自己的计数器变量更简洁、更易于阅读。正如您已经在这里看到的,增加复杂性会导致错误。把事情简单化。
  • 大多数语言都提供了一个+=运算符,用于将整数添加到变量中。它比count = count + 1.
  • 使用参数来定义您要计算的字符以使其更灵活。char='e'当您有明显的默认值时,定义一个默认参数以在参数列表中使用。
  • 为函数选择一个更合适的名称。这个名字has_no_e()让读者认为代码会检查代码是否没有 e,但它实际上做的是计算 e 的出现次数。

Putting this all together we get:

把这一切放在一起,我们得到:

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

Some tests:

一些测试:

>>> count_letter('tee')
2
>>> count_letter('tee', 't')
1
>>> count_letter('tee', 'f')
0
>>> count_letter('wh' + 'e'*100)
100

回答by Tim Pietzcker

Why not simply

为什么不简单

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

回答by Nope

You don't have to use a while-loop. Strings can be used for-loops in Python.

您不必使用 while 循环。字符串可用于 Python 中的 for 循环。

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

or something simpler:

或者更简单的东西:

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

回答by user225312

>>> word = 'eeeooooohoooooeee'
>>> word.count('e')
6

Why not this?

为什么不是这个?

回答by Yonatan

The problem is that the last value of 'letters' in your iteration is '0', and when this happens you look at:

问题是迭代中“字母”的最后一个值是“0”,当发生这种情况时,您可以查看:

  word[letters-1]

meaning, you look at word[-1], which in python means "last letter of the word".
so you're actually counting correctly, and adding a "bonus" one if the last letter is 'e'.

意思是,你看 word[-1],它在 python 中的意思是“单词的最后一个字母”。
所以你实际上计算正确,如果最后一个字母是“e”,则添加一个“奖励”。

回答by Klaus Byskov Pedersen

It will count it twice when ending with an e because you decrement lettersone time too many (because you loop while letters >= 0and you should be looping while letters > 0). When lettersreaches zero you check word[letters-1]== word[-1]which corresponds to the last character in the word.

当以 e 结尾时,它会计算两次,因为你减少letters了一次太多(因为你循环 whileletters >= 0并且你应该循环 while letters > 0)。当letters达到零时,您检查word[letters-1]==word[-1]对应于单词中的最后一个字符。

回答by sjberry

Many of these suggested solutions will work fine.

许多这些建议的解决方案都可以正常工作。

Know that, in Python, list[-1] will return the last element of the list.

要知道,在 Python 中,list[-1] 将返回列表的最后一个元素。

So, in your original code, when you were referencing word[letters-1] in a while loop constrained by letters >= 0, you would count the 'e' on the end of the word twice (once when letters was the length-1 and a second time when letters was 0).

因此,在您的原始代码中,当您在受字母 >= 0 约束的 while 循环中引用 word[letters-1] 时,您会计算单词末尾的 'e' 两次(一次当字母是长度时- 1 和第二次当字母为 0 时)。

For example, if my word was "Pete" your code trace would look like this (if you printed out word[letter] each loop.

例如,如果我的单词是“Pete”,您的代码跟踪将如下所示(如果您在每个循环中打印出 word[letter] 。

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

e (for word[3]) t (for word[2]) e (for word[1]) p (for word[0]) e (for word[-1])

Hope this helps to clear things up and to reveal an interesting little quirk about Python.

希望这有助于澄清问题并揭示有关 Python 的一个有趣的小怪癖。

回答by Hugh Bothwell

@marcog makes some excellent points;

@marcog 提出了一些很好的观点;

in the meantime, you can do simple debugging by inserting print statements -

同时,您可以通过插入打印语句来进行简单的调试 -

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

then

然后

has_no_e('tease')

returns

回报

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

from which you can see that

从中你可以看到

  1. you are going through the string in reverse order
  2. it is correctly recognizing e's
  3. you are 'wrapping around' to the end of the string - hence the extra e if your string ends in one
  1. 你正在以相反的顺序浏览字符串
  2. 它正确识别e
  3. 您正在“环绕”到字符串的末尾 - 因此,如果您的字符串以一个结尾,则额外的 e

回答by aid

If what you really want is 'has_no_e' then the following may be more appropriate than counting 'e's and then later checking for zero,

如果您真正想要的是“has_no_e”,那么以下内容可能比计算“e”然后检查零更合适,

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 there are no 'E's either,

如果你想检查也没有“E”,

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

>>> has_no_e('NYSE')
False