Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Here's my pythonic approach to the LeetCode 3Sum problem. It passes and actually beats 93% in time! However, the code is unwieldy, and the approach seems much overly complicated. I am looking to clean up the twoSum
function, and overall approach, but I'm not sure how.
def threeSum(self, nums: List[int]) -> List[List[int]]:
def twoSum(i,target):
ans = []
for j in range(i+1,len(nums)):
#avoid dupes
if j > i+1 and nums[j] == nums[j-1]:
continue
if nums[j] > target//2:
break
# when target is even, two dupes may add to make it
if nums[j] == target/2 and j+1 < len(nums):
if nums[j+1] == target // 2:
ans.append([nums[i],nums[j],nums[j+1]])
break
#traditional two sum variation
elif -(-target + nums[j]) in values and -(-target + nums[j]) != nums[j]:
ans.append([nums[i],nums[j],-(-target + nums[j])])
return ans
values = set(nums)
nums.sort()
answer = []
for i,num in enumerate(nums):
if i > 0 and nums[i-1] == nums[i]:
continue
values.remove(num)
answer.extend(twoSum(i,-num))
return answer
Even if you aren't able to follow my code, I would really appreciate general pythonic tips.
-
4\$\begingroup\$ Providing the problem statement and/or sample in- and output will help contributors point you towards a better or more straightforward solution. As it is now, it's hard to understand what's (supposed to be) going on. \$\endgroup\$riskypenguin– riskypenguin2021年04月23日 23:28:46 +00:00Commented Apr 23, 2021 at 23:28
-
\$\begingroup\$ It doesn't address Python-specific questions, but the Wikipedia pseudocode for 3sum is intuitive and has a nice visualization to accompany it. Seems like a simpler algorithmic approach than the one you've taken, so it might be worth a look. \$\endgroup\$FMc– FMc2021年04月24日 23:38:59 +00:00Commented Apr 24, 2021 at 23:38
1 Answer 1
Assumption
To avoid a syntax error, I had to add this line:
from typing import List
Perhaps LeetCode does that behind the scenes.
Naming
The PEP 8 style guide recommends snake_case for function and variable names.
For example, twoSum
would be two_sum
.
The variable named answer
is a bit vague. I think it would be more meaningful
as triplets
. ans
should also have a more meaningful name.
Documentation
PEP-8 recommends adding docstrings for functions. It would summarize the purpose of the code, like in the text of the question.
The comments in the code are helpful.
Layout
There is some inconsistent whitespace surrounding operators. The black program can be used to automatically format the code for consistency.
Explore related questions
See similar questions with these tags.