开发者

Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string

The question is how to write a program that measures how many times a character appears in a string in a generalizable way in python.

The code that I wrote:

def countLetters(str, ch):
   count=0
开发者_Python百科   index=0
   for ch in str:
     if ch==str[index]:
       count=count+1
     index=index+1
   print count

when I use this function, it measures the length of the string instead of how many times the character occurs in the string. What did I do wrong? What is the right way to write this code?


You are over-writing your 'ch' variable:

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

(also, it is usually more useful to return the value than to just print it).

The built-in method is str.count:

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

How you could rewrite your code:

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

and a quick pythonic replacement:

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


Think logically about what happens when you run your code: since the test in the loop succeeds on the first iteration, it is guaranteed to succeed every time! You are simply checking that iteration in Python works.

The correct formulation is

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

Or, equivalently,

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

But you could just as well do:

s.count(c)


Your loop is wrong.

This should work:

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

this way index variable will not be used and you can remove it. If you want to use index then change for into:

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

You can also increment variable by += operator like:

cnt += 1

So finished code will look like:

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


Completely untested:

def count_letters(s, c):
    return sum(1 for x in s if x == c)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜