python 一个函数调用另外一个函数_python – 通过另一个函数调用函数时的双输出...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值