Нахождение наиболее часто встречающегося символа в строке - PullRequest
9 голосов
/ 09 ноября 2010

Я обнаружил эту проблему программирования, глядя на публикацию работы на SO.Я думал, что это было довольно интересно, и, как начинающий программист на Python, я пытался заняться этим.Однако я чувствую, что мое решение довольно ... грязное ... Кто-нибудь может предложить какие-либо предложения по его оптимизации или сделать его чище?Я знаю, что это довольно тривиально, но мне было весело писать это.Примечание: Python 2.6

Проблема:

Напишите псевдокод (или реальный код) для функции, которая принимает строку и возвращает букву, которая выглядит наиболеев этой строке.

Моя попытка:

import string

def find_max_letter_count(word):

    alphabet = string.ascii_lowercase
    dictionary = {}

    for letters in alphabet:
        dictionary[letters] = 0

    for letters in word:
        dictionary[letters] += 1

    dictionary = sorted(dictionary.items(), 
                        reverse=True, 
                        key=lambda x: x[1])

    for position in range(0, 26):
        print dictionary[position]
        if position != len(dictionary) - 1:
            if dictionary[position + 1][1] < dictionary[position][1]:
                break

find_max_letter_count("helloworld")

Вывод:

>>> 
('l', 3)

Обновленный пример:

find_max_letter_count("balloon") 
>>>
('l', 2)
('o', 2)

Ответы [ 9 ]

21 голосов
/ 09 ноября 2010

Есть много способов сделать это короче.Например, вы можете использовать класс Counter (в Python 2.7 или более поздней):

import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])

Если у вас его нет, вы можете выполнить подсчет вручную (2,5или позже имеет defaultdict):

d = collections.defaultdict(int)
for c in s:
    d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])

Сказав это, в вашей реализации нет ничего слишком плохого.

4 голосов
/ 09 ноября 2010

Если вы используете Python 2.7, вы можете быстро сделать это с помощью модуля коллекций.Коллекции - это модуль структур данных высокой производительности.Узнайте больше на http://docs.python.org/library/collections.html#counter-objects

>>> from collections import Counter
>>> x = Counter("balloon")
>>> x
Counter({'o': 2, 'a': 1, 'b': 1, 'l': 2, 'n': 1})
>>> x['o']
2
2 голосов
/ 17 ноября 2013

Вот способ найти наиболее распространенный символ, используя словарь

message = "hello world"
d = {}
letters = set(message)
for l in letters:
    d[message.count(l)] = l

print d[d.keys()[-1]], d.keys()[-1]
1 голос
/ 16 июня 2018

Вопрос: Самый частый символ в строке Максимальный встречающийся символ во входной строке

Метод 1:

a = "GiniGinaProtijayi"

d ={}
chh = ''
max = 0 
for ch in a : d[ch] = d.get(ch,0) +1 
for val in sorted(d.items(),reverse=True , key = lambda ch : ch[1]):
    chh = ch
    max  = d.get(ch)


print(chh)  
print(max)  

Метод 2:

a = "GiniGinaProtijayi"

max = 0 
chh = ''
count = [0] * 256 
for ch in a : count[ord(ch)] += 1
for ch in a :
    if(count[ord(ch)] > max):
        max = count[ord(ch)] 
        chh = ch

print(chh)        

Метод 3:

import collections

a = "GiniGinaProtijayi"

aa = collections.Counter(a).most_common(1)[0]
print(aa)
1 голос
/ 09 ноября 2010

Если вы хотите иметь всех символов с максимальным количеством отсчетов, то вы можете сделать вариацию на одну из двух предложенных идей:

import heapq  # Helps finding the n largest counts
import collections

def find_max_counts(sequence):
    """
    Returns an iterator that produces the (element, count)s with the
    highest number of occurrences in the given sequence.

    In addition, the elements are sorted.
    """

    if len(sequence) == 0:
        raise StopIteration

    counter = collections.defaultdict(int)
    for elmt in sequence:
        counter[elmt] += 1

    counts_heap = [
        (-count, elmt)  # The largest elmt counts are the smallest elmts
        for (elmt, count) in counter.iteritems()]

    heapq.heapify(counts_heap)

    highest_count = counts_heap[0][0]

    while True:

        try:
            (opp_count, elmt) = heapq.heappop(counts_heap)
        except IndexError:
            raise StopIteration

        if opp_count != highest_count:
            raise StopIteration

        yield (elmt, -opp_count)

for (letter, count) in find_max_counts('balloon'):
    print (letter, count)

for (word, count) in find_max_counts(['he', 'lkj', 'he', 'll', 'll']):
    print (word, count)

ЭтоВыход, например:

lebigot@weinberg /tmp % python count.py
('l', 2)
('o', 2)
('he', 2)
('ll', 2)

Это работает с любой последовательностью: слова, но также ['привет', 'привет', 'добрый день], например.

heapq структура очень эффективна при поиске мельчайших элементов последовательности без ее полной сортировки.С другой стороны, поскольку в алфавите не так много букв, вы, вероятно, также можете пробежаться по отсортированному списку отсчетов до тех пор, пока максимальный отсчет больше не будет найден, без каких-либо серьезных потерь в скорости.

0 голосов
/ 23 декабря 2018

Я заметил, что большинство ответов возвращаются только с одним элементом, даже если наиболее часто используется одинаковое количество символов. Например "iii 444 yyy 999". Есть равное количество пробелов, я, 4, у и 9. Решение должно прийти со всем, а не только буквой я:

sentence = "iii 444 yyy 999"

# Returns the first items value in the list of tuples (i.e) the largest number
# from Counter().most_common()
largest_count: int = Counter(sentence).most_common()[0][1]

# If the tuples value is equal to the largest value, append it to the list
most_common_list: list = [(x, y)
                         for x, y in Counter(sentence).items() if y == largest_count]

print(most_common_count)

# RETURNS
[('i', 3), (' ', 3), ('4', 3), ('y', 3), ('9', 3)]
0 голосов
/ 12 октября 2017
#file:filename
#quant:no of frequent words you want

def frequent_letters(file,quant):
    file = open(file)
    file = file.read()
    cnt = Counter
    op = cnt(file).most_common(quant)
    return op   
0 голосов
/ 19 ноября 2013
def most_frequent(text):
    frequencies = [(c, text.count(c)) for c in set(text)]
    return max(frequencies, key=lambda x: x[1])[0]

s = 'ABBCCCDDDD'
print(most_frequent(s))

frequencies - это список кортежей, которые считают символы как (character, count).Мы применяем max к кортежам, используя count, и возвращаем кортежи character.В случае ничьей, это решение выберет только один.

0 голосов
/ 09 ноября 2010

Вот несколько вещей, которые я бы сделал:

  • Используйте collections.defaultdict вместо dict, который вы инициализируете вручную.
  • Используйте встроенную сортировку и функции max, такие как max, вместо того, чтобы работать самостоятельно - это проще.

Вот мой окончательный результат:

from collections import defaultdict

def find_max_letter_count(word):
    matches = defaultdict(int)  # makes the default value 0

    for char in word:
        matches[char] += 1

    return max(matches.iteritems(), key=lambda x: x[1])

find_max_letter_count('helloworld') == ('l', 3)
...