断言python

时间:2015-01-15 11:24:46

标签: python recursion

我在python中有递归的问题。我的代码如下:

counter = 0
result = []
def count_inversion(sequence):
    global result, counter
    """
        Count inversions in a sequence of numbers
    """
    sequence = list(sequence)
    if len(sequence) == 1:
        result.append(sequence[0])
        if result == sorted(result):
            result = []
            return counter
        else:
            sequence = result
            result = []
            return count_inversion(sequence)

    if sequence[0] > sequence[1]:
        result.append(sequence.pop(1))
        counter += 1
        return count_inversion(sequence)
    else:
        result.append(sequence[0])
        return count_inversion(sequence[1:])

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example"
    assert count_inversion((0, 1, 2, 3)) == 0, "Sorted"
    assert count_inversion((99, -99)) == 1, "Two numbers"
    assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"

当我单独运行断言时,它工作正常,但是当我想要一起运行它时,我遇到的问题是变量计数仍然是前一个断言的值(在这种情况下,来自第一个asser的值为3)。我不知道在我的代码中将counter = 0放在哪里才能正常工作。感谢。

3 个答案:

答案 0 :(得分:0)

两个选项:

选项1:在方法中初始化:

def count_inversion(sequence):
    counter = 0
    result = []
    # Your code

选项2:正如Rawing建议您可以使用参数:

def count_inversion(sequence, counter, result):
    #your code

你可以称之为:

count_inversion((1, 2, 5, 3, 4, 7, 6), 0, []):

更清洁的方式是:

def count_inversion(sequence, counter=0, result=[]):
    #your code

这样,如果您希望它们成为其他参数,您只需要对这些参数进行设置:

count_inversion((1,2,5,3,4,7,6),counter = 1):#Counter现在以1开始

答案 1 :(得分:0)

这将解决您的问题,我将计数器作为全局变量删除并每次传递给函数count_inversion ...另一个 NOT RECOMMENDED 的解决方案是设置一个新变量在counter之前= return然后退回counter=0,然后返回新变量

result = []
def count_inversion(sequence, counter):
    global result
    """
       Count inversions in a sequence of numbers
    """
    sequence = list(sequence, counter)
    if len(sequence) == 1:
        result.append(sequence[0])
        if result == sorted(result):
           result = []
           return counter
        else:
           sequence = result
           result = []
           return count_inversion(sequence, counter)

    if sequence[0] > sequence[1]:
        result.append(sequence.pop(1))
        counter += 1
        return count_inversion(sequence, counter)
    else:
        result.append(sequence[0])
        return count_inversion(sequence[1:], counter)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_inversion((1, 2, 5, 3, 4, 7, 6),0) == 3, "Example"
    assert count_inversion((0, 1, 2, 3),0) == 0, "Sorted"
    assert count_inversion((99, -99),0) == 1, "Two numbers"
    assert count_inversion((5, 3, 2, 1, 0),0) == 10, "Reversed"

根据您上面的评论,我添加了将计数器保持为全局的代码:

counter=0
result = []
def count_inversion(sequence):
    global result
    global counter
    """
       Count inversions in a sequence of numbers
    """
    sequence = list(sequence)
    if len(sequence) == 1:
        result.append(sequence[0])
        if result == sorted(result):
           result = []
           return_counter=counter
           counter=0
           return return_counter
        else:
           sequence = result
           result = []
           return count_inversion(sequence)

    if sequence[0] > sequence[1]:
        result.append(sequence.pop(1))
        counter += 1
        return count_inversion(sequence)
    else:
        result.append(sequence[0])
        return count_inversion(sequence[1:])

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example"
    assert count_inversion((0, 1, 2, 3)) == 0, "Sorted"
    assert count_inversion((99, -99)) == 1, "Two numbers"
    assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"

答案 2 :(得分:0)

以下是函数的简化版本,它不会弄乱全局变量:

def count_inversion(sequence, current=(), counter=0):
    """Count inversions in a sequence of numbers."""
    if len(sequence) < 2:
        current += sequence
        if list(current) == sorted(current):
            return counter
        return count_inversion(current, (), counter)
    index = sequence[0] > sequence[1]
    return count_inversion(sequence[:index] + sequence[index+1:],
                           current + sequence[index:index+1],
                           counter + index)

主要区别是:

  • 它使用默认参数来跟踪currentcounter
  • 它直接使用元组,因此不需要列表转换
  • 它通过使用索引(01)从
  • 中弹出元素来推断递归调用

输出:

>>> count_inversion((1, 2, 5, 3, 4, 7, 6))
3
>>> count_inversion((0, 1, 2, 3))
0
>>> count_inversion((99, -99))
1
>>> count_inversion((5, 3, 2, 1, 0))
10