Reputation: 51
What I am trying to do is count how many times each letter appear in a string. The I want to store the details in a dictionary.
The following is my attempt to do so:
def scan(string):
list_string = []
for letter in string:
list_string.append(letter)
list_string.sort()
scanned = {}
for k in range(0,len(list_string)):
count = 0
for kk in range(k,len(list_string)):
if list_string[k] == list_string[kk]:
count += 1
scanned.update({list_string[k]:count})
return scanned
However every key is having the value 1 even though there are times when a letter appears more than one time.
It works fine when I try this
print("Letter '{}': \t {}.format(list_string[k],count))
Can anyone help?
Upvotes: 2
Views: 141
Reputation: 476503
You can simply count with the Counter
:
from collection import Counter
ctr = Counter(list_string)
Now ctr
is a Counter
: a special sort of dictionary. It maps the elements that were in the list onto numbers (the amount of time it is in the list). An element that has not been seen, is mapped on 0.
That's because you overwrite it each time you recount that value.
Say the list is:
['a','b','a','a']
Now you first set the k
-cursor (^
) to the first element, and the kk
-cursor (v
) to the same:
#v
['a','b','a','a']
#^
Now we count the number of a
s and obtain 3. Next we advance, the k
-counter and count the number of b
s (1). Now the cursor is moved again, to the second a
:
# v
['a','b','a','a']
# ^
Now we count the number of 'a'
s again, but now we obtain 2: because the kk
-cursor ignores the first one. Finally we move the cursor to the last 'a'
, and count the number of 'a'
s, and guess what? We obtain 1. So we rewrite it to 1.
# v
['a','b','a','a']
# ^
Regardless of the number of times an element occurs in the list, we will always count it a last time, and then the count will obviously always be 1.
Upvotes: 7
Reputation: 402253
letter_count = { x : list(mystring).count(x) for x in set(mystring)}
As rightly pointed out, a pretty pythonic one liner with bad asymptotic complexity if your elements are hashable, in which case using count(...) will become a linear operation.
Upvotes: 1
Reputation: 56624
from collections import Counter
letter_count = Counter(mystring)
Upvotes: 7