Dom13
Dom13

Reputation: 43

Same Python code returns different results for same input string

Below code is supposed to return the most common letter in the TEXT string in the format:

Each time I run the code using the same string, e.g. "One" the result cycles through the letters...weirdly though, only from the third try (in this "One" example).

text=input('Insert String: ')
def mwl(text):
    from string import punctuation
    from collections import Counter
    for l in punctuation:
        if l in text:
            text = text.replace(l,'')
    text = text.lower()
    text=''.join(text.split())
    text= sorted(text)
    collist=Counter(text).most_common(1)
    print(collist[0][0])
mwl(text)   

Upvotes: 2

Views: 1739

Answers (3)

Irshad Bhat
Irshad Bhat

Reputation: 8709

You can get the desired output with OrderedDict replacing the below two lines:

text= sorted(text)
collist=Counter(text).most_common(1)

with:

collist = OrderedDict([(i,text.count(i)) for i in text])
collist = sorted(collist.items(), key=lambda x:x[1], reverse=True)

You also need to import OrderedDict for this.

Demo:

>>> from collections import Counter, OrderedDict
>>> text = 'One'
>>> collist = OrderedDict([(i,text.count(i)) for i in text])
>>> print(sorted(collist.items(), key=lambda x:x[1], reverse=True)[0][0])
O  
>>> print(sorted(collist.items(), key=lambda x:x[1], reverse=True)[0][0])
O    # it will always return O
>>> text = 'hello'
>>> collist = OrderedDict([(i,text.count(i)) for i in text])
>>> print(sorted(collist.items(), key=lambda x:x[1], reverse=True)[0][0])
l    # l returned because it is most frequent

Upvotes: 3

xnx
xnx

Reputation: 25508

This can also be done without Counter or OrderedDict:

In [1]: s = 'Find the most common letter in THIS sentence!'
In [2]: letters = [letter.lower() for letter in s if letter.isalpha()]
In [3]: max(set(letters), key=letters.count)
Out[3]: 'e'

Upvotes: 1

fredtantini
fredtantini

Reputation: 16556

Counter uses a dictionary:

>>> Counter('one')
Counter({'e': 1, 'o': 1, 'n': 1})

Dictionaries are not ordered, hence the behavior.

Upvotes: 10

Related Questions