Can anybody tell me why my code below does not work?
class NumArray(object): _dp =  def __init__(self, nums): self._dp.append(0) for i in range(0, len(nums) ): self._dp.append( self._dp[-1] + nums[i] ) def sumRange(self, i, j): return self._dp[j+1] - self._dp[i] Input: [-1], sumRange(0,0) Output: [-2] Expected: [-1]
If I move the first line "_dp = [ ]" into the init as " self._dp = [ ]", the code works. Does any member have to be initialized in init and with the "self." prefix? I am newbie of Python, forgive me if the question is too simple.
Thanks in advance!
You're (re)using the same list for all test cases without resetting in between.
You defined a class variable. It's static and shared by all instances.
Read this for more information. Python is quite different than c++ or java.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.