此函数应将1加到以列表形式给出的数字中。如果列表为[1, 2, 3]
,则此函数应返回[1, 2, 4]
,因为123 + 1 == 124
。
下面是所讨论的功能:
def plusOne(self, A):
val = 1;
for i in range(len(A)-1,0,-1):
val = val + A[i]
borrow = int(val/10)
if borrow == 0:
A[i] = val
break;
else:
A[i] = val%10
val = borrow
A = [borrow] + A
while A[0]==0:
del A[0]
return A
错误消息是:
Traceback (most recent call last):
File "main.py", line 225, in
Z = obj.plusOne(A)
File "/tmp/judge/solution.py", line 8, in plusOne
A = [borrow] + A
UnboundLocalError: local variable 'borrow' referenced before assignment
令人惊讶的是,下面的代码运行无误:
class Solution:
# @param A : list of integers
# @return a list of integers
def plusOne(self, A):
val = 1;
for i in range(len(A),0,-1):
val = val + A[i-1]
borrow = int(val/10)
if borrow == 0:
A[i-1] = val
break;
else:
A[i-1] = val%10
val = borrow
A = [borrow] + A
while A[0]==0:
del A[0]
return A
我仍然不明白,如果直接在循环内部初始化借位变量会导致错误,那么上面的代码片段也应该抛出该错误,对吧?
借用在for
循环中被声明/初始化。
for i in range(len(A)-1,0,-1):
如果len(A)为1,那么将没有任何范围可以循环,并且借入将永远不会进入范围,因此会出现错误。
您面临的问题是scoping的经典问题。
borrow
循环之前未定义变量for
,并且代码尝试在循环之后访问它。
如果使用len(A) > 1
,您的代码将正常运行,因为在这种情况下,borrow
在循环中定义,并且正在执行循环。
但是,在这种情况下,如果代码为len(A) <= 1
,则代码将直接尝试访问从未定义的变量borrow
。
在这种情况下,最佳实践是使用默认值定义变量。在这种情况下,如果您在borrow = 0
循环之前定义for
,它将是正确的值。
我希望这会有所帮助:)
您的代码几乎没有问题。在大多数情况下,它确实可以按预期工作。请允许我提出一些改进意见,并指出问题所在。
首先,您的代码中有两个分号,Python中不需要它们。(line 2) val = 1;
和(line 8) break;
第二,当列表发送到方法和函数时,它们作为参考发送,因此,这些方法内部的更改将应用于原始列表。
第三,循环中的中断通常表示错误的选择和计划。
[第四,如果plusOne
不是类的一部分,则不需要self
作为其参数(如果它是类的一部分,则将其留在那里并在调用时使用self.plusOne(..)
进行调用。
从不同的角度来看,我会这样做的:
def plusOne(self, lst):
if len(lst) > 0:
# Initial value to increase by
val = 1
# Initialization of list index to last element.
i = -1
# Calculate the number after addition, calculate the borrow and replace in the list.
num = val + lst[i]
borrow = num // 10
lst[i] = num % 10
# While there is any borrow and the list didn't read the first element.
while borrow != 0 and i > len(lst)*-1:
# Update the borrow to new value.
val = borrow
# Decrease the index.
i -= 1
# Calculate the number after addition, calculate the borrow and replace in the list.
num = val + lst[i]
borrow = num // 10
lst[i] = num % 10
# Check if borrow remaining after index out of range.
if borrow != 0:
# Insert borrow before the first element.
lst.insert(0, borrow)
# Remove leading zeros.
while lst[0] == 0:
del lst[0]
def main():
lst = [1, 2, 9]
plusOne('', lst)
print(lst)
if __name__ == '__main__':
main()