I'm trying to count the occurrences of each character in the sentence. I used the code below:
printed = False
sentence = "the quick brown fox jumps over the lazy dog"
chars = list(sentence)
count = 0
for char in chars:
if char == ' ':
chars.remove(char)
if printed == False:
count = chars.count(char)
print "char count: ", char, count
else:
printed = False
The problem is, that the first letter of each word, except for the first word is not printed and the count is incorrect (every time a new word starts, the count decrements by 1, starting from 7):
['t', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k', ' ', 'b', 'r', 'o', 'w', 'n', ' ', 'f', 'o', 'x', ' ', 'j', 'u', 'm', 'p', 's', ' ', 'o', 'v', 'e', 'r', ' ', 't', 'h', 'e', ' ', 'l', 'a', 'z', 'y', ' ', 'd', 'o', 'g']
char count: t 2
char count: h 2
char count: e 3
char count: 7
char count: u 2
char count: i 1
char count: c 1
char count: k 1
char count: 6
char count: r 2
char count: o 4
char count: w 1
char count: n 1
char count: 5
char count: o 4
char count: x 1
char count: 4
char count: u 2
char count: m 1
char count: p 1
char count: s 1
char count: 3
char count: v 1
char count: e 3
char count: r 2
char count: 2
char count: h 2
char count: e 3
char count: 1
char count: a 1
char count: z 1
char count: y 1
char count: 0
char count: o 4
char count: g 1
When I create 2 for-loops, instead of 1, it works better:
sentence = "the quick brown fox jumps over the lazy dog"
chars = list(sentence)
count = 0
for char in chars:
if char == ' ':
chars.remove(char)
print chars
printed = False
for char in chars:
if printed == False:
count = chars.count(char)
print "char count: ", char, count
printed = True
else:
printed = False
And here's the output:
['t', 'h', 'e', 'q', 'u', 'i', 'c', 'k', 'b', 'r', 'o', 'w', 'n', 'f', 'o', 'x', 'j', 'u', 'm', 'p', 's', 'o', 'v', 'e', 'r', 't', 'h', 'e', 'l', 'a', 'z', 'y', 'd', 'o', 'g']
char count: t 2
char count: e 3
char count: u 2
char count: c 1
char count: b 1
char count: o 4
char count: n 1
char count: o 4
char count: j 1
char count: m 1
char count: s 1
char count: v 1
char count: r 2
char count: h 2
char count: l 1
char count: z 1
char count: d 1
char count: g 1
The only thing is, the 'o' character appears in the output twice... Why is that? Also, why won't 1 loop work?