How to return most duplicate letters in python?

I made several copies and most of the arrays used, but our class is not that far, and we will use it mainly for loops to return the most repeated letter in a function.

Here is my code so far, but I could only return the first letter count.

def most_repeated_letters(word_1):
  x = 0
  z = 0
  for letter in word_1:
    y = word_1.count(letter[0:])
    if y > z:
      z = y
    x += 1
    return z

print most_repeated_letters('jackaby')
+4
source share
5 answers

Use collections.Counter

from collections import Counter
c = Counter('jackaby').most_common(1)
print(c)
# [('a', 2)]
+2
source

There are several problems in your code:

  • you calculate the count of the most common letter, but not the letter itself
  • you are returninside the loop and thus after the very first letter
  • you never use x, and slicing is letternot needed

, :

, :

def most_repeated_letters(word_1):
    most_common_count = 0
    most_common_letter = None
    for letter in word_1:
        count = word_1.count(letter)
        if count > most_common_count:
            most_common_count = count
            most_common_letter = letter
    return most_common_letter

Python, . , , max, word_1.count key .

def most_repeated_letters(word_1):
    return max(word_1, key=word_1.count)

, , count , O (n²). dict O (n).

def most_repeated_letters(word_1):
    counts = {}
    for letter in word_1:
        if letter not in counts:
            counts[letter] = 1
        else:
            counts[letter] += 1
    return max(counts, key=counts.get)

, collections.Counter, .

+1

:

def mostRepeatedLetter(text):
  counter = {}
  for letter in text:
    if letter in counter: 
      counter[letter]+=1
    else: 
      counter[letter]=1
  max = { letter: 0, quantity: 0 } 
  for key, value in counter.items(): 
    if value > max.quantity: 
      max.letter, max.quantity = key, value
  return max
0

:

def most_repeated_letters(word_1):
    lettersCount = {}
    for ch in word_1:
        if ch not in lettersCount:
            lettersCount[ch] = 1
        else:
            lettersCount[ch] += 1

    return max(lettersCount, key=lettersCount.get)


print(most_repeated_letters('jackabybb'))
0

, :

def most_repeated_letters(word_1):

    d = {}

    for letter in word_1:      
        if not d.get(letter):
            d[letter] = 0
        d[letter] = d.get(letter) + 1

    ret = {}

    for k,v in d.iteritems():
        if d[k] == max(d.values()):
            ret[k] = v

    return ret

most_repeated_letters('jackaby')
0
source

Source: https://habr.com/ru/post/1687167/


All Articles