Given string S consisting of only lowercase letters (a-z). Print to the screen all the letters that appear more than once in the string S and their number in lexicographical order.
a = input()
for i in range(len(a)):
if a.count(a[i])!=1:
print(a[i], a.count(a[i]))
the problem here is it does print the frequency, but doesn't sort in alphabetical order, and some letter and their frequencies it print out more than 1
example input
thequickbrownfoxjumpsoverthelazydog
example output
e 3
h 2
o 4
r 2
t 2
u 2
How do I do this pls help
CodePudding user response:
Make a mapping of letters to counts. One quick way with a dictionary would be:
word = input()
letters = {}
for letter in word:
if letter not in letters:
letters[letter] = 0
letters[letter] = 1
You can simplify this using a defaultdict
:
from collections import defaultdict
word = input()
letters = defaultdict(int)
for letter in word:
letters[letter] = 1
Or even simpler with a counter:
from collections import Counter
word = input()
letters = Counter(word)
Now that you have your letter counts, you just need to sort and print the items:
for letter, count in sorted(letters.items()):
if count > 1:
print(letter, count)
CodePudding user response:
import collections
s = "thequickbrownfoxjumpsoverthelazydog"
d = {}
for c in s:
if c in d:
d[c] = 1
else:
d[c] = 1
od = collections.OrderedDict(sorted(d.items()))
for k, v in od.items():
if v > 1:
print(k, v)
store the letters and their appearance in a dictionary, sort it and print the key and value if the value is greater than 1.