热线电话:13121318867

登录
2019-01-28 阅读量: 753
为什么我在这个递归代码中得到“达到最大深度递归”?

我对编码和东西都很陌生。我试图在python中实现以下代码以进行情感分析任务。但是,我的文档很大,当它试图通过函数循环文档时,我得到一个错误,表明达到了Max深度递归。我通过博客阅读后得知,代码在return语句中调用自己,这导致了问题。因此,寻找一些指导或帮助你们从任何类型的伪代码重写代码。找到以下代码:

def sentence_score(sentence_tokens, previous_token, acum_score):

if not sentence_tokens:

return acum_score

else:

current_token = sentence_tokens[0]

tags = current_token[2]

token_score = sum([value_of(tag) for tag in tags])

if previous_token is not None:

previous_tags = previous_token[2]

if 'inc' in previous_tags:

token_score *= 2.0

elif 'dec' in previous_tags:

token_score /= 2.0

elif 'inv' in previous_tags:

token_score *= -1.0

return sentence_score(sentence_tokens[1:], current_token, acum_score + token_score)

解决办法

Python没有尾递归,只需使用循环:

def sentence_score(sentence_tokens):

score = 0

previous_token = None

for current_token in sentence_tokens:

tags = current_token[2]

token_score = sum([value_of(tag) for tag in tags])

if previous_token is not None:

previous_tags = previous_token[2]

if 'inc' in previous_tags:

token_score *= 2.0

elif 'dec' in previous_tags:

token_score /= 2.0

elif 'inv' in previous_tags:

token_score *= -1.0

score += token_score

previous_token = current_token

return score

0.0000
8
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子