简体   繁体   English

使用递归函数python的区别

[英]difference using recursive functions python

I have lists which consist of random letters.. 我有包含随机字母的列表。

def similarity(out_list):

    i=0
    count=0
    while i<len(out_list):
        if out_list[i][-1]==out_list[i+1][-1]:
            count+=1

            return similarity(out_list[i][:-1]) + count
        elif out_list[i][-1]!=out_list[i+1][-1]:

            return similarity(out_list[i][:-1])
        i+=2

out_list=["ABABA","ACA","AGAGA","AAVA","XBX","ARAA","AADA","AAA","BABAB","ABA"]
similarity(out_list)

In my code I'm trying to find difference between list elements which are first and second, third and forth etc.. 在我的代码中,我试图找出第一和第二,第三和第四等列表元素之间的区别。

However since my function is recursive, the value of i is always 0 and I can't control other elements and I can't find the difference.. 但是,由于我的函数是递归的,所以i的值始终为0,并且我无法控制其他元素,也找不到差异。

for ABABA and ACA the difference is 3 because first A and third A are the common in both words at same indexes.. so difference 5-2=3 对于ABABA和ACA,差异为3,因为第一个A和第三个A在相同索引的两个词中都是相同的。因此,差异5-2 = 3

what changes do my code require? 我的代码需要进行哪些更改? Thank you. 谢谢。

Consider passing i as a parameter into your recursive function instead of setting it as 0 at the very start of the function. 考虑将i作为参数传递给递归函数,而不是在函数开始时将其设置为0。 It's likely you would want to do something similar to count too. 您可能也想做一些类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM