Python变量表现得很奇怪

时间:2017-01-02 09:18:44

标签: python algorithm

我正在制作模式识别器,我遇到了一个非常奇怪的错误。如果识别出模式,则打印出["x", "x", "2"]并将变量设置为t。但是当我在最后一行打印出来时,它打印出["x", "x", "x"]

(参见标有#_____________的代码部分重要__________#)

    import random

    def check_pattern(pattern, rule):
        for i, RULE in enumerate(pattern):
            if RULE != "x":
                if rule[i] != RULE:
                    return False
        return True

    if __name__ == "__main__":
        numbers = [002,212,212,432,132,142,322,992,972,692,942,472]

        #numbers = [a.replace("\n", "") for a in numbers]

        print("Finding pattern in {}".format(numbers))

        patterns = []
        possible = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "x"]

        found = False
        pattern = ["x", "x", "x"]
        working = []
        worked = []
        for i, rule in enumerate(pattern):
            for attemptRule in possible:
                testRule = pattern
                testRule[i] = str(attemptRule)
                works = True

                for num in numbers:
                    numList = [a for a in str(num)]
                    if check_pattern(testRule, numList):
                        pass
                        #print("Pattern {} works with {}".format(t, numList))
                    else:
                        works = False
                        #print("Pattern {} doesnt work with {}".format(t, numList))
                if works:
                    # ____________________ IMPORTANT ______________________ #
                    if testRule != ['x', 'x', 'x']:
                        print(testRule)                    
                        worked = testRule
                    # ____________________ IMPORTANT ______________________ #
                    working.append(testRule)
        #print("Pattern {} works".format(working))
    print(worked)

感谢。

1 个答案:

答案 0 :(得分:0)

我找到了我的衣服。问题是我没有克隆列表而是覆盖了它。感谢polku我理解。谢谢大家。