我写了一个递归函数来找到no.父字符串中子字符串的实例.我保持计数的方式是将计数声明/初始化为函数范围之外的全局变量.问题是,它只会在第一次运行函数时给我正确的结果,因为在那之后!= 0开始.如果我在函数内部,它比每次递归调用它,它将被设置为0.
count=0
def countSubStringMatchRecursive(target,key):
index=find(target,key)
global count
targetstring=target
if index>=0:
count=count+1
target=target[index+len(key):]
countSubStringMatchRecursive(target,key)
else :
pass
return "No. of instances of", key, 'in', targetstring, 'is', count
Run Code Online (Sandbox Code Playgroud)
注意:我正在寻找一个recursive特定功能的解决方案,我有一个可以正常工作的迭代函数.
编辑:谢谢大家,这是家庭作业的一部分,所以我只使用字符串模块
问题是找到第1000个素数.我为此编写了以下python代码.问题是,我得到了10号,20号素数的正确答案,但之后每增加10分,我就得到了一个标记.我无法抓住这里的错误:(
count=1 #to keep count of prime numbers
primes=() #tuple to hold primes
candidate=3 #variable to test for primes
while count<20:
for x in range(2,candidate):
if candidate%x==0:
candidate=candidate+2
else : pass
primes=primes+(candidate,)
candidate=candidate+2
count=count+1
print primes
print "20th prime is ", primes[-1]
Run Code Online (Sandbox Code Playgroud)
如果您想知道,count初始化为1,因为我没有测试2作为素数(我从3开始)并且candidate正在增加2,因为只有奇数可以是素数.我知道还有其他解决这个问题的方法,比如素数定理,但我想知道这种方法有什么问题.如果您有任何优化,请建议.
谢谢