-4

my submission is https://leetcode.com/problems/top-k-frequent-elements/submissions/912663494/

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        '''counting keywords and their frequencies into a dict'''
        record = {}
        for num in nums:
            if num not in record:
                record[num] = 1
            else:
                record[num] += 1

        '''sort the dict according to the frequencies with reverse order'''
        topk = list(dict(sorted(record.items(), key=lambda items: items[1], reverse=True)))[:k]

        return topk


if __name__ == "__main__":
    sol = Solution()
    nums = [4,1,-1,2,-1,2,3]
    output = sol.topKFrequent(nums=nums, k=2)

this is what I got when running the code above in pycharm, enter image description here

however, when I submit my answer on leecode, it is judged as a wrong answer, as below: enter image description here

Could someone please tell where the problem is?

missmango
  • 105
  • 2
  • 9
  • 1
    [Please don't post screenshots of text](https://meta.stackoverflow.com/a/285557/354577). They can't be searched or copied, or even consumed by users of adaptive technologies like screen readers. Instead, paste the code as text directly into your question, then select it and click the code block button. – ChrisGPT was on strike Mar 10 '23 at 12:41
  • the code you posted and the link to leetcode you provided doesn't print anything. You just save the result into output but you never print output. – Sembei Norimaki Mar 10 '23 at 12:44
  • 1
    What version of Python does Leetcode use? Your code relies on the assumption that when you do `list(d)` on a dictionary `d`, the items will be output in the same order they were inserted to the dictionary. But that is not guaranteed in Python versions before 3.7. See: https://stackoverflow.com/a/39980744/765091 – slothrop Mar 10 '23 at 13:29
  • You could remove the need for that assumption by just doing `topk = sorted(record.items() ... ` without the conversion to a dict then back to a list. – slothrop Mar 10 '23 at 13:31

1 Answers1

1

Looking at the template code you have used from LeetCode, it looks like you selected "Python" and not "Python 3". The first will run your code on Python 2.7

If you submit your code using the "Python 3" engine, your code will work.

A comment in your code says "sort the dict", and then the code creates a sorted list of key/value pairs which it feeds into a new dict.

However, before Python 3.7, dicts did not maintain (insertion) order, and so on those versions the effect of calling sorted is lost again.

When selecting "Python 3", LeetCode will run your code with a recent version of Python, which at the time of writing is 3.10. Check the version that LeetCode uses on support.leetcode.com.

trincot
  • 317,000
  • 35
  • 244
  • 286