'Sharing regional variables when using recursive functions in Python
I'm studying algorithms with Python. While working on the recursive function, we try to pop the 0th part of the array whenever the for statement proceeds in the following situation. However, [arrangement] is shared within the recursive called part, so it doesn't work out as I thought.
The regional variable is used within the recursive function, but the regional variable continues to be shared in each recursive function, resulting in incorrect results.
In the code below, each recursive call should not involve each other in regional variables. Tell me how to do it.
def jong(case, a, b, sumX, sumY, n, min):
n = int(n)
if len(case) == n:
print(case)
result = (a-2*sumX)*(a-2*sumX) + (b-2*sumY)*(b-2*sumY)
if min == -1:
min = result
return min
if min > result:
min = result
return min
for i in range(0, len(case)):
sumX = sumX + int(case[0][0])
sumY = sumY + int(case[0][1])
popArr = case.copy()
popArr.pop(0)
min = jong(popArr, a, b, sumX, sumY, n, min)
sumX = sumX - int(case[0][0])
sumY = sumY - int(case[0][1])
case.pop(0)
return min
In the above code, I should not let each recursive function share the "case.pop(0)" part.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
