mardi 6 novembre 2018

Check the most frequent letter(s) in a word. Python

My task is:

To write a function that gets a string as an argument and returns the letter(s) with the maximum appearance in it.

Example 1:

s = 'Astana'

Output:

a

Example 2:

s = 'Kaskelen'

Output:

ke

So far, I've got this code(click to run):

a = input()


def most_used(w):

    a = list(w)
    indexes = []
    g_count_max = a.count(a[0])

    for letter in a:
        count = 0
        i = int()
        for index in range(len(a)):
            if letter == a[index] or letter == a[index].upper():
                count += 1
                i = index
        if g_count_max <= count:       //here is the problem.
            g_count_max = count
            if i not in indexes:
                indexes.append(i)


    letters = str()

    for i in indexes:
        letters = letters + a[i].lower()

    return letters

print(most_used(a))

The problem is that it automatically adds first letter to the array because the sum of appearance of the first element is actually equal to the starter point of appearance(which is basically the first element).

Example 1:

s = 'hheee'

Output:

he

Example 2:

s = 'malaysia'

Output:

ma

Aucun commentaire:

Enregistrer un commentaire