代码之家  ›  专栏  ›  技术社区  ›  Pouya Ataei

打印字典中最大和第二大元素

  •  1
  • Pouya Ataei  · 技术社区  · 6 年前

    我已经编写了一个函数,它将字符串作为输入,并将一个字典交给用户,该字典指示最常出现的元素/字符。

    def mostoccur(arr):
    
       n = len(arr)
       dict={}
    
       # filling the dictionary with itesm and their frequency using dict.get()
    
       for i in range(n):
           dict[arr[i]] = dict.get(arr[i],0) + 1
    
    
       return dict
    
    
    string = "aabbccdddddddd"
    
    # turning the string into a list, so it's iterable
    
    ls = list(string)
    ans = mostoccur(ls)
    print("The dictionary of all the characters and their frequency: \n",ans)
    
    maximum = max(ans)
    print("\nThe most occuring character is:",maximum)
    

    但后来我变得更好奇了,我想把字典里出现次数最多和出现次数次之的元素打印出来。因此,我写了这样的东西:

    第2部分-好了,现在让我们找出第二个最常出现的字符

    # defining a dictionary to store the most and second most occurring element
    
    biggest = {'most-occuring':0, 'second-most-occuring':0}
    
    # nested loops to go through all values in the dictionary
    
    for a in ans.items():                                  # O(N)
       for b in ans.items():                               # O(N)
           if a < b:                                       
               a,b = b,a
               biggest['most-occuring'] = a
               biggest['second-most-occuring']= b
    
                                                           # Total = O(N^2)
    
    print(biggest)
    

    大O

    你愿意告诉我更好的写作方法吗?

    请记住,我不是在寻找一种利用

    2 回复  |  直到 6 年前
        1
  •  2
  •   TallChuck Sheetal    6 年前

    下面是一个简单的算法 O(n) :

    string = "aabbbccdddddddd"
    
    def get_frequency(string):
        chars = {}
        for char in string:
            chars[char] = chars.get(char, 0) + 1 
    
        biggest = [None, 0]
        second = [None, 0]
    
        for entry in chars.items():
            char, count = entry
            if count > biggest[1]:
                second = biggest
                biggest = entry
            elif count > second[1]:
                second = entry
    
        return {
            "most-occurring": biggest[0],
            "second-most-occurring": second[0]
        }
    
    print(get_frequency(string))
    

    {'second-most-occurring': 'b', 'most-occurring': 'd'}

    注意,我在 string 为了让它成为第二个最频繁的字母

        2
  •  0
  •   T Burgis    6 年前

    使用heapq.nlargest,如下所示:

    from collections import Counter
    import heapq
    string = "aabbccdddddddd"
    counts = Counter(string)
    heapq.nlargest(2, counts, key=lambda k: counts[k])
    

    并且不使用库,假设函数返回与Counter相同的内容:

    keys = list(counts.keys())
    keys.sort(key=lambda x: counts[x],reverse=True)
    top_two = keys[:2] # just the keys
    { k : counts[k] for k in keys[:2] } # dict of top two