0

## Python問題，在刷Leetcode 1239題時遇到

``````class Solution(object):
def maxLength(self, arr):
"""
:type arr: List[str]
:rtype: int
"""

bitArr = [0]*26
self.res = 0

def backtracking(start):
self.res = max(self.res, sum(bitArr))
prevArr = bitArr
for i in range(start, len(arr)):
duplicate = False
for char in arr[i]:
if bitArr[ord(char)-ord('a')] == 1:
duplicate = True
bitArr = prevArr
break
bitArr[ord(char)-ord('a')] = 1
if duplicate:
continue
else:
for char in arr[i]:
bitArr[ord(char)-ord('a')] = 1
backtracking(i+1)
for char in arr[i]:
bitArr[ord(char)-ord('a')] = 0

backtracking(0)

return self.res
``````

https://ithelp.ithome.com.tw/articles/10230680

ffaanngg iT邦新手 5 級 ‧ 2021-02-16 15:23:22 檢舉

### 1 個回答

1

``````a = 0
def func():
a = 1
print(a) #1
func()
print(a) #0
``````

``````var a = 0
function func(){
var a = 1
}
``````

`local variable "bitArr" referenced before assignment`

``````a = 0
def func():
b = a
a = 2
func()
# local variable 'a' referenced before assignment
``````

``````self.res = max(self.res, sum(bitArr))
``````

### 解法

``````def backtracking(start):
nonlocal bitArr
...
``````

ffaanngg iT邦新手 5 級 ‧ 2021-02-16 14:18:59 檢舉

``````a = 0
def func():
b = a
a = 2
func()
``````

• JS 使用關鍵字(var)宣告`區域變數`
• Python 使用關鍵字(nonlocal)宣告`非區域變數`
ffaanngg iT邦新手 5 級 ‧ 2021-02-16 15:27:35 檢舉

``````class Solution(object):
def maxLength(self, arr):
"""
:type arr: List[str]
:rtype: int
"""
bitArr = [0]*26
self.res = 0

def backtracking(start):
global bitArr
print(bitArr)

backtracking(0)

return self.res
``````

`global` 是「全域變數」，`nonlocal` 是「外部變數」，兩者差異如下:

#### # global

``````a = 0 #<-全域
def func1():
a = 1 #<-外部
def func2():
global a   # 這裡的 a 是全域變數
``````

#### # nonlocal

``````a = 0 #<-全域
def func1():
a = 1 #<-外部
def func2():
nonlocal a   # 這裡的 a 是外部變數
``````

bitArr 宣告在函數中不是全域變數，所以出現 `is not defined` 未定義的錯誤。

### 解法

1. 將 bitArr 放到 self 內，這樣就不用宣告 global 了
2. 將 bitArr 放到 class 外，這樣 bitArr 就成為全域變數了
ffaanngg iT邦新手 5 級 ‧ 2021-02-17 01:15:42 檢舉