Python:在for循环

时间:2016-03-29 04:39:07

标签: python list for-loop recursion itertools

BackGround

我正在开展一个项目,我需要比较一组字符串,并保留uniquedistinct的字符串。 Uniqdistinct表示不应该有两个字符串,
A)回文,例如ABA' , 'BCB'
B) Reverse of each other. e.g.
&#39; ABCD&#39; and ' DCBA&#39; C) Same as each other, e.g.&#39; ABC&#39; and&#39; ABC&#39;`< / p>

如果列表确实包含这些属性,那么程序应该只保留其中一个并删除其他属性。

例如我使用itertoolspermutationscombination模块生成如下列表,
aList= ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA', 'ABC']

通过两个for循环处理它 外循环处理从开始到结束的每个数字,直到End of List -1项被击中 从start + 1项到End of List的内部循环过程。 这样两个循环总是比较两个不同的字符串。

现在,需要使用 Recursions完成此逻辑。

什么有用

我确实编写了以下程序,每次找到属性并删除重复的项目时都会调用递归函数。

什么不起作用

仅当列表中至少有一个项目与属性条件匹配并且被删除时,递归才有效。当saveFound = True时。我使用了另一个变量来跟踪found = True使用from itertools import combinations, permutations """ Process list to generate Unique strings matching given criteria """ def uniqLst(aList): """ Iterate through outer loop to compare each string until End of Loop """ firstItem = 0 lastItem = len(aList) -1 for item1 in aList[firstItem:lastItem:]: saveFound = False print "Starting Next for Loop : Loop Length", len(aList) #Debug Data print "input List=", aList #Debug Data for item2 in aList[firstItem + 1:lastItem + 1:]: #Compare first item with next print "Comparing item1, item2 =", item1 , item2 #Debug Data """ Check if second string is reverse / palindrome or same """ if item1[::-1] == item2 or item1 == item2: found = True saveFound = True print "Removing", item2 #Debug Data aList.remove(item2) # Remove second item matching criteria else: found = False """One iteration cycle is complete""" if saveFound == True: print "Starting Next Iteration" #Debug Data uniqLst(aList) #Force load of new aList #External loop is complete exit Function return aList """ Main Function """ if __name__== "__main__": tmpLst1 = ["".join(x) for x in permutations('ABC', 3)] tmpLst2 = ["".join(x) for x in combinations('ABC', 3)] checkStrLst = tmpLst1 + tmpLst2 finalList = uniqLst(checkStrLst) print "========================" print "finalList", finalList 的部分查找,但是还没有让它工作。

当列表中没有特定项目的匹配属性时,程序将失败。但是,在检查完所有项目之后我们才会完成,而且我们只能查看列表中的最后两项。然后我们退出。

我需要帮助

我已经添加了额外的打印语句(以#debug 结尾)以查看正在替换的项目。 我需要知道如何在程序中使用递归函数来修复当第一项没有重复时的情况。该程序正在进行自我比较并从列表中删除自己。 对于这种情况看起来它没有达到外循环。 任何输入/修复都表示赞赏。

计划:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Starting Next for Loop : Loop Length 7
input List= ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA', 'ABC']
Comparing item1, item2 = ABC ACB
Comparing item1, item2 = ABC BAC
Comparing item1, item2 = ABC BCA
Comparing item1, item2 = ABC CAB
Comparing item1, item2 = ABC CBA
Removing CBA
Comparing item1, item2 = ABC ABC
Removing ABC
Starting Next Iteration
Starting Next for Loop : Loop Length 5
input List= ['ACB', 'BAC', 'BCA', 'CAB', 'ABC']
Comparing item1, item2 = ACB BAC
Comparing item1, item2 = ACB BCA
Removing BCA
Comparing item1, item2 = ACB CAB
Comparing item1, item2 = ACB ABC
Starting Next Iteration
Starting Next for Loop : Loop Length 4
input List= ['ACB', 'BAC', 'CAB', 'ABC']
Comparing item1, item2 = ACB BAC
Comparing item1, item2 = ACB CAB
Comparing item1, item2 = ACB ABC
Starting Next for Loop : Loop Length 4
input List= ['ACB', 'BAC', 'CAB', 'ABC']
Comparing item1, item2 = BAC BAC
Removing BAC
Comparing item1, item2 = BAC CAB
Removing CAB
Comparing item1, item2 = BAC ABC
Starting Next Iteration
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = ACB ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = CAB ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = BAC ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = BCA ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = CAB ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = ACB ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = BAC ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = BCA ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = CAB ABC
Starting Next for Loop : Loop Length 2
input List= ['ACB', 'ABC']
Comparing item1, item2 = CBA ABC
Removing ABC
Starting Next Iteration
========================
finalList ['ACB']
>>> 

OutPut

node.js

1 个答案:

答案 0 :(得分:1)

好的,所以我尝试让代码工作,同时尽可能少地进行更改。最重要的是,我不认为您可以在不更改aList的情况下逃脱,因为您必须以某种方式在每个递归步骤中跟踪您的状态。

from itertools import combinations, permutations

""" Process list to generate Unique strings matching given criteria """
def uniqLst(aList, finalList):

    """ Iterate through outer loop to compare each string until End of Loop """

    # Terminate if length is 0
    if(len(aList) == 0):
        return

    # Initialize local values
    found = False
    item1 = aList[0];

    # Go through list and compare with first item
    for item2 in aList[1:len(aList)]:

        """ Check if second string is reverse / palindrome or same """
        if item1[::-1] == item2 or item1 == item2:
            found = True
            print "Removing", item2 #Debug Data
            aList.remove(item2) # Remove second item matching criteria

    # If no item matches, add first item to final list
    if found != True:
        temp = aList.pop(0)
        finalList.append(temp)

        # Recursively call this function with updated aList
    uniqLst(aList, finalList)

    return


""" Main Function """
if __name__== "__main__":

    tmpLst1 = ["".join(x) for x in permutations('ABC', 3)]
    tmpLst2 = ["".join(x) for x in combinations('ABC', 3)]

    checkStrLst = tmpLst1 + tmpLst2

    finalList = []
    uniqLst(checkStrLst, finalList)
    print "========================"
    print "finalList", finalList

我添加了评论,以帮助您了解我为每一步做了些什么。 如果这不符合您的要求,请告诉我们!