《计算机科学家思维方式(Python)》中的练习7.9:测量字符串中字符的出现次数

1 投票
4 回答
650 浏览
提问于 2025-04-16 10:04

这个问题是关于如何写一个程序,用来计算一个字符在字符串中出现了多少次,并且这个方法要能通用,适用于Python。

我写的代码是:

def countLetters(str, ch):
   count=0
   index=0
   for ch in str:
     if ch==str[index]:
       count=count+1
     index=index+1
   print count

但是当我使用这个函数时,它测量的是字符串的长度,而不是字符在字符串中出现的次数。我哪里出错了?正确的写法应该是什么样的?

4 个回答

0

你的循环写错了。

这样写应该可以正常工作:

  for s in str:
     if ch == s:
       ...

这样的话,index 这个变量就不需要用了,你可以把它删掉。如果你想用 index,那么可以把 for 改成:

for index in range(len(str)):
   ... (rest is OK but ...)
   ... (do not increase index in loop body)

你也可以用 += 操作符来增加变量的值,比如:

cnt += 1

所以最终的代码看起来会是:

def countLetters(str, ch):
   count = 0
   for s in str:
     if ch == s:
       count += 1
   print count
2

想想你运行代码时会发生什么:因为循环中的测试在第一次运行时就成功了,所以每次运行都会成功!你只是在检查Python中的循环是否正常工作。

正确的写法是

def count(s, input):
    count = 0
    for c in s:
        if c == input:
            count += 1

或者,换一种说法,

def count(input):
    return sum(c == input for c in s)

但你也可以这样做:

s.count(c)
5

你在覆盖你的'ch'变量:

def countLetters(str, ch):
#                      ^ the character you are looking for
    count=0
    index=0
    for ch in str:
#        ^ the string character you are trying to check
        if ch==str[index]:  # ???
            count=count+1
        index=index+1
    print count

(另外,通常返回值比仅仅打印出来更有用)。

内置的方法是str.count:

"aaabb".count("a")  -> 3

你可以这样重写你的代码:

def countLetters(search_in, search_for):
    count = 0
    for s in search_in:    # iterate by string char, not by index
        if s==search_for:
            count += 1
    return count

还有一个快速的Python风格替代方案:

def countLetters(search_in, search_for):
    return sum(1 for s in search_in if s==search_for)

撰写回答