find minimum frequency of occurrence of a character in a string in only one traverse

Viewed 54

I have this simple code, that gets the frequency of occurrences of characters in a string:

sally = "sally sells sea shells by the sea shore"
characters = {}
best_char=''
maxx_num=0
for ch in sally:
    if characters.get(ch) is None:
        characters[ch] = 0
    characters[ch] = characters[ch]+1
    if characters[ch] > maxx_num:
        maxx_num = characters[ch]
        best_char = ch

now I want to get the worst_char (i.e. the least occuring character in the string) the same way I got the best_char (maximum occurence)

It's obvious I can simply make this via another for loop to check on all characters in the dictionary again then print the one with minimum occurence, my question is: can I make it in the same loop as maximum one without needing to create another loop, this is more of an algorithm question than a coding one.

1 Answers
sally = "sally sells sea shells by the sea shore"
characters = {}


best_char = wrost_char = sally[0]

for ch in sally:
    if ch in characters:
        characters[ch]+=1
    else:
        characters[ch]=1
    if characters[best_char] < characters[ch]:
        best_char = ch
    if characters[wrost_char] > characters[ch]:
        wrost_char = ch

print(best_char)
print(wrost_char)

There will be many good letters, and there will not be one So you will need an extra loop:

sally = "sally sells sea shells by the sea shore"
characters = {}
for ch in sally:
    if ch in characters:
        characters[ch]+=1
    else:
        characters[ch]=1


values = characters.values()
worst = min(values)
best = max(values)
best_chars=[]
worst_chars = []

for k,v in characters.items():
    if worst == v:
        worst_chars.append(k)
    if  best == v:
        best_chars.append(k)

print(worst_chars) print(best_chars)

Related