jason jason - 2 months ago 12
Python Question

Program is repeating itself -can't figure out why

This is my program so far...it takes a message (input from user) and tells the user how many A's are in the program, how many B's, etc. Except when I input a message such as "Dad", it'll tell me how many D's there are twice instead of just saying everything once.
It says:

D ... 2

A ... 1

D ... 2

I want it to say:

A ... 1

D ... 2

How do I fix this without using zip, and without importing anything?

message=input("what is your message?").upper()
for i in message:
if i in alphabet:

for i in message:
print (i,"...",count[alphabet.index(i)])

(Thanks to Uriel Eli for helping me get the program this far btw).


I don't agree with your approach here. You have actually over complicated this. The proper way to solve this is to actually use a dictionary to keep track of all the letters in the string and keep a count every time the same character comes up. Note, this also sticks to the rule of not importing anything.

Furthermore, this removes the necessity to have a list of letters to check against as well.

Also, if you need to count upper and lower case characters separtely, do not call upper at the end of your input. Just remove it. If you have to count upper and lower case as the same character, then you can leave it.

message=input("what is your message?").upper()

d = {}

for c in message:
    if c in d:
        d[c] += 1
        d[c] = 1


what is your message?thisisastringofthings
{'H': 1, 'F': 0, 'O': 0, 'R': 0, 'G': 1, 'S': 3, 'T': 2, 'A': 0, 'I': 3, 'N': 1}

To provide an output similar to what you are expecting, you just need to iterate through your final result and print:

for character, count in d.items(): print("{} ... {}".format(character, count))

Finally, just for the sake of showing the best way to do this, is to actually use Counter from collections:

>>> from collections import Counter
>>> Counter("thisisastring")
Counter({'s': 3, 'i': 3, 't': 2, 'h': 1, 'n': 1, 'a': 1, 'r': 1, 'g': 1})