Greg Shepherd Greg Shepherd - 1 year ago 70
Python Question

Most Frequent Character - User Submitted String without Dictionaries or Counters

Currently, I am in the midst of writing a program that calculates all of the non white space characters in a user submitted string and then returns the most frequently used character. I cannot use collections, a counter, or the dictionary. Here is what I want to do:

Split the string so that white space is removed. Then count each character and return a value. I would have something to post here but everything I have attempted thus far has been met with critical failure. The closest I came was this program here:

strin=input('Enter a string: ')
for ch in strin:
while i<len(strin):
if ch.lower()==strin[i].lower():
if j>nfc and ch!=' ':
print('The most frequent character in string is: ', fc )

If you can fix this code or tell me a better way of doing it that meets the required criteria that would be helpful. And, before you say this has been done a hundred times on this forum please note I created an account specifically to ask this question. Yes there are a ton of questions like this but some that are reading from a text file or an existing string within the program. And an overwhelmingly large amount of these contain either a dictionary, counter, or collection which I cannot presently use in this chapter.

Answer Source

Just do it "the old way". Create a list (okay it's a collection, but a very basic one so shouldn't be a problem) of 26 zeroes and increase according to position. Compute max index at the same time.

strin="lazy cat dog whatever"

for c in strin.lower():
    pos = ord(c)-ord('a')
    if 0<=pos<=25:
        if l[pos]>maxvalue:
            maxvalue = l[pos]

print("max count {} for letter {}".format(maxvalue,chr(maxindex+ord('a'))))


max count 3 for letter a
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download