count调用函数find,以查看从给定索引开始的单词中可以找到多少次字母(请参阅下面的“代码”).
令人困惑的部分:
通过使用函数“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)
解决方法:
在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()的值来“memoize”一次:
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."
标签:python,python-2-7
来源: https://codeday.me/bug/20190519/1136404.html