2

Essentially i have to write a program that counts how many time each letter occurs in a string. I got that working but letters duplicate, for example. If the string was hello it would output:

  • h 1
  • e 1
  • l 2
  • l 2
  • o 1

When i need it to output:

  • h 1
  • e 1
  • l 2
  • o 1

The way i've done it so far is without importing anything and my code looks like:

input_text = input('Enter some text: ')
s = input_text.lower()
length_s = len(s)
l = 0
while length_s > 0:
    if s[l].isalpha():
        print(s[l], s.count(s[l]))
        l += 1
        length_s -=1
    else:
        l += 1
        length_s -=1
Nick Adams
  • 31
  • 3
  • 2
    Use [`set()`](http://stackoverflow.com/questions/15181867/understanding-the-set-function)` – Vaulstein Aug 03 '15 at 11:33
  • @Vaulstein but `set` doesn't tell you how many of each there are. – Peter Wood Aug 03 '15 at 11:36
  • what you could do is first create a list of unique alphabets using `s = input_text.lower().split()` and then `s= list(set(s))`. Get the count. Create a dict as the unique elements as the key. Iterate over each alphabet in the input and increment the count as you find that key. P.S. : The code would be smaller than what I wrote. try it. – Vaulstein Aug 03 '15 at 11:52

2 Answers2

5

You can use a collections.Counter for your use case, it is a dict subclass for counting hashable objects (example - characters in a string) . Example -

>>> from collections import Counter
>>> c = Counter('hello')
>>> c
Counter({'l': 2, 'h': 1, 'o': 1, 'e': 1})
>>> for i,x in c.items():
...     print('{} - {}'.format(i,x))
...
l - 2
h - 1
o - 1
e - 1

Without using imports, you can use set() to store the characters that have already been seen. (This is done so that order is also maintained) -

input_text = input('Enter some text: ')
s = input_text.lower()
seen = set()
for c in s:
     if c not in seen:
         print(c, s.count(c))
         seen.add(c)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2

If you don't want to import anything you could do something like this to get a dictionary:

s = input_text.lower()
countDict = {}
for char in s:
    if (char not in countDict):
        countDict[char] = 1
    else:
        countDict[char] += 1
tobifasc
  • 681
  • 5
  • 17