0

Trying to solve leetcode 217 using python:

from typing import List

nums = [1,2,3,1]

def containsDuplicate(self, nums: List[int]) -> bool:
    hashset = set()

    for n in nums:
        if n in hashset:
            return True
        hashset.add(n)
    return False

I supposed to get "False" or "True" from the output window, anything wrong with my code?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 4
    Are you calling the function? – Barmar Sep 09 '22 at 02:42
  • You can simply do `return len(nums) > len(set(nums))` – Barmar Sep 09 '22 at 02:43
  • Good question, if I put containsDuplicate at the end, and run it again, still no output, I might be too stupid – rainland666 Sep 09 '22 at 02:43
  • A function whose parameters begin with `self` should be a class method. Shouldn't this be inside `class Solution:`? – Barmar Sep 09 '22 at 02:44
  • Then you'll need to use `print(Solution().containsDuplicate(nums))` – Barmar Sep 09 '22 at 02:44
  • @Barmar, I guess I can do that, but from sample point of view, I want to make my code work first and will try you method very soon. – rainland666 Sep 09 '22 at 02:45
  • If it's not in a class, you need to remove `self`. Then call `print(containsDuplicate(nums))` – Barmar Sep 09 '22 at 02:46
  • Does this answer your question? [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement-how-is-it-different-from-printing) – Mechanic Pig Sep 09 '22 at 02:47
  • @Barmar, I had removed the class:Solution and self, now I can see the output after call the function:from typing import List nums = [1,2,3,1] def containsDuplicate(nums) -> bool: hashset = set() for n in nums: if n in hashset: return True hashset.add(n) return False print(containsDuplicate(nums)) – rainland666 Sep 09 '22 at 02:50

0 Answers0