2015-11-02 118 views
5

count调用函数find以查看在给定索引处开始的单词中可以找到多少个字母(请参阅下面的“代码”)。通过另一个函数调用函数时的双输出

混乱的部分: 通过使用函数“计数”,我得到下面的程序输出: program output

如可以看到的那样,一些输出是重复的(标记为红色)。 如何避免没有从查找中删除打印?是否有可能或我是否被迫将其删除(打印)? 我明白这两个函数可以做成更简单的函数,但我想了解如何使用另一个函数调用函数。

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

代码:

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) 
+0

这是缩进精确地说你拥有它的方式? –

+0

我对此表示怀疑_chuckle_ –

+1

您在while循环内调用了2次“find”函数。每次调用它时都会打印出一条消息。限制1次使用该功能,问题将得到解决。 – Vadim

回答

5

有每次迭代2个find()电话在while循环:

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

每次打印时:

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

你应该“memoize的“通过computin G和存储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." 
+0

ty的答复。帮了很多忙。 –

+0

如果解决了你的问题,你能接受答案吗? –

0

更新您的计数功能是这样的:

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

ty的答复。我现在明白了:) –

相关问题