使用find循环和计数

0 投票
6 回答
1558 浏览
提问于 2025-04-17 01:57

我正在努力做一些作业的例子,结果又遇到了一个错误。

原始代码:

    word = 'banana'
    count = 0
    for letter in word:
        if letter == 'a':
            count = count + 1
    print count

看起来很简单。

然后我把这段代码放进了一个叫 count 的函数里,并且把它做得更通用,这样它就可以接受字符串和字母作为参数。

    def count1(str, letter):
        count = 0             
        word = str            
        for specific_letter in word: 
            if specific_letter == letter: 
                count = count + 1 

        print count

但是在这里,我还是不太确定自己哪里出错了。

我需要重写这个函数,让它不再遍历字符串,而是使用前面部分提到的三参数版本的 find。这段代码是:

    def find(word, letter, startat):
        index = startat
        while index <= len(word):
            if word[index] == letter:
                return index
            index = index + 1


        return -1

这是我目前的进展……但是程序并没有按照我想要的方式运行。

    def find(str, letter, startat):
        index = startat
        word = str   
        count = 0
        while index <= len(word):
            if word[index] == letter:
                for specific_letter in word:
                    if specific_letter == letter:
                        count = count + 1

                print count
            index = index + 1

有人能给我指个方向吗?我想理解我在做什么,而不是单纯得到答案。谢谢。

6 个回答

1

如果你想尝试一些有趣的、符合Python风格的做法,可以把原来的 find 改成 yield index,然后去掉最后的 return -1。哦,对了,还要修复 <= 的错误:

def find(word, letter, startat):
    index = startat
    while index < len(word):
        if word[index] == letter:
            yield index
        index = index + 1

print list(find('hello', 'l', 0))

现在 find 会返回 所有 的结果。你可以像我在例子中那样使用它,或者用 for position in find(...): 的方式来使用。你也可以简单地通过结果的长度来写 count

(抱歉,关于你问题中的最终函数没有提示,因为我不太明白你想要做什么。看起来你可能保留了太多原始函数的内容,导致它们的目的混在了一起?)

1

这个想法是用 find 函数来找到你想要的字母的下一个位置。

在你的代码里,你没有使用 find 这个函数。

4

这个练习的目的是使用之前定义的函数 find 来作为基础,去实现一个新的函数 count。所以,你出错的地方在于试图重新定义 find,而实际上你应该是要修改 count 的实现。

不过,这里有个小问题,就是你给出的 find 函数有一点错误,你需要把 <= 改成 <,这样它才能正常工作。因为如果用 <=,当 index 等于 len(word) 时,循环就会进入,这样会导致 IndexError: string index out of range 的错误。

所以先修复 find 函数:

def find(word, letter, startat):
    index = startat
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1

然后再重新实现 count,这次在函数体内使用 find

def count(word, letter):
    result = 0
    startat = 0
    while startat < len(word):
        next_letter_position = find(word, letter, startat)
        if next_letter_position != -1:
            result += 1
            startat = next_letter_position + 1
        else:
            break
    return result

撰写回答