gpt4 book ai didi

python - 通过另一个函数调用函数时双输出

转载 作者:太空狗 更新时间:2023-10-30 01:07:04 25 4
gpt4 key购买 nike

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

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

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

我还必须提到变量 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()一次的值:

 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 - 通过另一个函数调用函数时双输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33481579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com