3
\$\begingroup\$

LeetCode 3Sum problem:

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 thetwoSum 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.

toolic's user avatar
toolic
16.4k6 gold badges29 silver badges221 bronze badges
askedApr 23, 2021 at 22:09
Joseph Gutstadt's user avatar
\$\endgroup\$
2
  • 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\$CommentedApr 23, 2021 at 23:28
  • \$\begingroup\$It doesn't address Python-specific questions, but the Wikipediapseudocode 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\$CommentedApr 24, 2021 at 23:38

1 Answer1

1
\$\begingroup\$

Assumption

To avoid a syntax error, I had to add this line:

from typing import List

Perhaps LeetCode does that behind the scenes.

Naming

ThePEP 8 style guide recommendssnake_case for function and variable names.

For example,twoSum would betwo_sum.

The variable namedanswer is a bit vague. I think it would be more meaningfulastriplets.ans should also have a more meaningful name.

Documentation

PEP-8 recommends adding docstrings for functions. It would summarize thepurpose 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.Theblack program can be used to automaticallyformat the code for consistency.

answeredMar 12 at 12:13
toolic's user avatar
\$\endgroup\$

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.