通过另一个

时间:2015-11-02 15:50:29

标签: python python-2.7

count调用函数find,以查看在给定索引处开始的单词中可以找到多少次字母(请参阅"代码"下面)。

令人困惑的部分: 通过使用函数" count",我得到以下程序输出: program output

可以看出,有些输出是重复的(用红色标记)。 如何在没有从find中删除打印的情况下避免这种情况?有可能还是我被迫删除它(打印)? 我知道这两个函数可以变成一个更简单的函数,但我想了解如何使用另一个函数调用函数。

我还必须提到变量计数的值是正确的。唯一的问题是重复的输出。

代码:

def find(word, letter, index):
    start_ind = index
    while index < (len(word)):
        if word[index] == letter:
            print "%s found at index %s" % (letter, index)
            return index

        index += 1

    else:
        print "%s is not found in string '%s' when starting from index %s" % (letter, word, start_ind)
        return -1


def count(word, letter, index):
    count = 0
    while index < len(word):
        if find(word, letter, index) != -1:
            count += 1
            index = find(word, letter, index) + 1

    print "%s is shown %s times in '%s'" % (letter, count, word)

    count("banana", "a", 0)

2 个答案:

答案 0 :(得分:5)

find()循环中每次迭代有两次while次调用:

 if  find(word, letter, index)!= -1:
        count += 1
        index = find(word, letter, index) + 1

每次打印时:

print "%s found at index %s" % (letter,index)

您应该&#34;通过计算和存储find() 的值来记忆&#34;

 found = find(word, letter, index)
 if  found != -1:
        count += 1
        index = found + 1

这是一个更优雅的问题解决方案:

word = 'banana'
letter = 'a'
occurences = [(index, value) for index, value in enumerate(word) if value == letter]
for occurence in occurences:
    print "Letter ",letter," has been found at index ",index
print "Letter ", letter, " has been found a total of ", len(occurences), " times."

答案 1 :(得分:0)

更新您的计数功能,如下所示:

def count(word,letter,index):
    count = 0
    while index < len(word):
        index = find(word,letter,index) + 1
        if  index != 0:
            count+=1