调用另一个函数时,通过一个函数调用会出现双重输出

5

count 调用函数 find 来查看一个字母在词中从给定下标开始出现的次数(请参见下面的“代码”)。

让人困惑的部分: 使用函数“count”,我得到了以下程序输出: program output

可以看到,有些输出是重复的(用红色标记)。如何避免这种情况,而不需要删除find中的print语句?这是否可能,或者我必须删除它(print语句)? 我知道这两个函数可以合并成更简单的函数,但我想了解如何通过另一个函数调用一个函数。

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

代码:

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)

这个缩进是不是完全按照你的要求? - Morgan Thrapp
我怀疑这个,咯咯笑 - Sebastian Wozny
1
在你的 while 循环中,你调用了 "find" 函数两次。每次调用它都会打印出一条消息。将函数的使用限制为一次,问题就会解决。 - Vadim
2个回答

5

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

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

每次打印时:

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

您应该通过计算和存储find()的值一次性来进行"备忘录"

 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."

感谢您的回复。非常有帮助。 - Sorin Soare
如果解决了你的问题,你能接受这个答案吗? - Sebastian Wozny

0

将您的计数函数更新为以下内容:

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

谢谢回复。我现在明白了 :) - Sorin Soare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接