简体   繁体   中英

How can I make def function that have same effect with Counter class?

I want to make def function which have same effect with Counter class and It's most_common function. And I success to make def function to find only the mode of a string like this way.

def most_common_char_count(s):
    dict = {}
    for n in s:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict

str1 = 'dajklvkdafjkd;ajfeqipjjfdas;fjkdsal;'
most_commons = most_common_char_count(str1) 
print(most_common_char_count(str1))

But I want to add most_command function to this def function. This is a program like that can print up to the Nth order of frequency. So I made an algorithm for the program, but I don't know how to implement it. The algorithm is as follows.

def most_common_char_count(s, n=None): #it have two parameters
    dictionary = {} #and I made string in dictionary
    for n in s:
        if n == None: #If n==none, returns the entire dictionary as a list of tuples
            dictionary[n] += 1
            return(list(zip(dict.keys(),dict.values())))
        else: #Returns the n most frequent items as a list of tuples.
            
s = 'dajklvkdafjkd;ajfeqipjjfdas;fjkdsal;'
most_commons = most_common_char_count(s, 4) 
print(4, most_commons)
print(most_common_char_count(s))

So if I put print(4, most_commons) , output will be

[('j', 6), ('d', 5), ('a', 5), ('k', 4)]

I don't know what code to write in the else statement. And if there are any additional errors, please let me know.

After you create the dictionary, sort it by the counts and return the first n elements.

from collections import defaultdict

def most_common_char_count(s, n=None):
    counts = defaultdict(lambda: 0)
    for item in s:
        counts[item] += 1

    if n is None:
        return counts
    else:
        return dict(sorted(counts.entries(), key=lambda k, v: v, reverse=True)[:n])

Some other points:

  1. Don't use dict as a variable name, it's the name of a built-in type and function. I changed it to counts .
  2. You can't use n as both the function parameter and the iteration variable in for .
  3. You can use defaultdict instead of explicitly testing if the key is in the dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM