Why is this throwing an invalid syntax error?
Question:
I have been trying to solve 3sum on leetcode. The line ‘lower +=1’ (below the first triplets.append) is throwing an invalid syntax error but I have no idea why.
class Solution(object):
def threeSum(self, nums):
if len(nums) < 3:
return([])
triplets = []
nums = sorted(nums)
for i in range(0, len(nums)-2):
lower = i + 1
upper = len(nums) - 1
while lower < upper:
s = nums[i] + nums[lower] + nums[upper]
if s == 0:
triplets.append((nums[i], nums[lower], nums[upper])
lower += 1
elif s < 0:
lower += 1
else:
upper -= 1
return(list(set(triplets))
Answers:
The line
triplets.append((nums[i], nums[lower], nums[upper])
is missing a trailing ‘)’
This code runs without issue – I commented the two places that needed extra parentheses to close unopen (
.
I also indented the entire def
but I wasn’t sure if that was just a product of your original copy-and-paste.
class Solution(object):
def threeSum(self, nums):
if len(nums) < 3:
return([])
triplets = []
nums = sorted(nums)
for i in range(0, len(nums)-2):
lower = i + 1
upper = len(nums) - 1
while lower < upper:
s = nums[i] + nums[lower] + nums[upper]
if s == 0:
# this needed a closing paren
triplets.append((nums[i], nums[lower], nums[upper]))
lower += 1
elif s < 0:
lower += 1
else:
upper -= 1
# and this also needed a closing paren
return(list(set(triplets)))
# don't mind this - just adding something for local running
if __name__ == "__main__":
print(Solution().threeSum([1,2,3]))
I have been trying to solve 3sum on leetcode. The line ‘lower +=1’ (below the first triplets.append) is throwing an invalid syntax error but I have no idea why.
class Solution(object):
def threeSum(self, nums):
if len(nums) < 3:
return([])
triplets = []
nums = sorted(nums)
for i in range(0, len(nums)-2):
lower = i + 1
upper = len(nums) - 1
while lower < upper:
s = nums[i] + nums[lower] + nums[upper]
if s == 0:
triplets.append((nums[i], nums[lower], nums[upper])
lower += 1
elif s < 0:
lower += 1
else:
upper -= 1
return(list(set(triplets))
The line
triplets.append((nums[i], nums[lower], nums[upper])
is missing a trailing ‘)’
This code runs without issue – I commented the two places that needed extra parentheses to close unopen (
.
I also indented the entire def
but I wasn’t sure if that was just a product of your original copy-and-paste.
class Solution(object):
def threeSum(self, nums):
if len(nums) < 3:
return([])
triplets = []
nums = sorted(nums)
for i in range(0, len(nums)-2):
lower = i + 1
upper = len(nums) - 1
while lower < upper:
s = nums[i] + nums[lower] + nums[upper]
if s == 0:
# this needed a closing paren
triplets.append((nums[i], nums[lower], nums[upper]))
lower += 1
elif s < 0:
lower += 1
else:
upper -= 1
# and this also needed a closing paren
return(list(set(triplets)))
# don't mind this - just adding something for local running
if __name__ == "__main__":
print(Solution().threeSum([1,2,3]))