【问题标题】:Python Recursive calls not updating global variablePython递归调用不更新全局变量
【发布时间】:2021-04-09 21:46:16
【问题描述】:

我正在尝试在 python 中为Leetcode Beautiful Arrangements 实现部分蛮力方法。在递归调用期间,我正在努力更新我的“counter”变量。

我尝试了多种使用全局变量并将其作为函数参数传递的方法,无论我做了什么,即使 if L == len( numbers) 条件满足。

class Solution:
    
    def countArrangement(self, n: int) -> int:

      def count_beautiful_arranges(N: int, counter):
            numbers = [0]*N

            # start index at 1
            # loop creates the array of 1 to N for initial list
            for i in range(1, N+1):
                numbers[(i-1)] = i
            
            # call recursive permutation function
            permutation(numbers, 0, counter)

            return counter
        
        def permutation(numbers: list, L: int, counter):
            
            # check each recursive call
            #print(L)
            #print(len(numbers))
            
            if L == len(numbers):
                counter = counter + 1
            
            for j in range(L, len(numbers)):

                swap(numbers, j, L)
                if numbers[L] % (L+1) == 0 or (L+1) % numbers[L] == 0:
                    permutation(numbers, L+1, counter)
                swap(numbers, j, L)
            
        
        def swap(numbers: list, x: int, y: int):
            
            #pythonic code
            numbers[x], numbers[y] = numbers[y], numbers[x]
            
        
        count_beautiful_arranges(n, 0) 

【问题讨论】:

  • 对于这个问题,使用permutations方法会导致Time Exceed,它只是需要很长时间。
  • 这是一个部分置换蛮力,它会通过测试,因为一旦违反其中一个条件它就会停止生成置换。

标签: python-3.x function recursion global


【解决方案1】:

我通过使用 Python 将变量附加到函数的能力来修复它。和 。方法我能够附加一个计数器并在递归堆栈中递增它。

我在调用递归函数之前声明了 permutation.countser,然后在调用完成后返回值。

这个StackOverflow answer帮助了我。

        def count_beautiful_arranges(N: int, counter):
            numbers = [0]*N

            # start index at 1
            # loop creates the array of 1 to N for initial list
            for i in range(1, N+1):
                numbers[(i-1)] = i
            
            permutation(numbers, 0)

            
        def permutation(numbers: list, L: int):

            if L == len(numbers):
                permutation.countser += 1
            
            for j in range(L, len(numbers)):

                swap(numbers, j, L)
                if numbers[L] % (L+1) == 0 or (L+1) % numbers[L] == 0:
                    permutation(numbers, L+1)
                swap(numbers, j, L)
                

        
        def swap(numbers: list, x: int, y: int):
            
            #pythonic code
            numbers[x], numbers[y] = numbers[y], numbers[x]
            
        
        permutation.countser = 0
        count_beautiful_arranges(n, 0)
        return permutation.countser

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 2021-07-12
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多