+ 2
Short Python letter counter..pls help me test it efficiency
text = input() dict = {} for x in text: dict[x] = text.count(x) print(dict)
9 Answers
+ 1
So what do you want?
+ 1
You test it yourself. Thats a huge part of programming. Have fun!
+ 1
no, your code is not as efficient as it could be, because .count() method iterate over each char of source text, so you basically do nested for loops...
best way is probably to use built-in Counter from collections module:
from collections import Counter
text = input()
count = Counter(text)
print(count)
+ 1
K.S.S. Karunarathne (Active Challenger) that's quite the same as OP code: you iterate over each char, and at each iteration, you call .count() method wich do each time a char iteration... (unless .count provide some memoization, and so count all char at once the first time, then return only partial result)
+ 1
@Shadoff your solution reduce the obvious loop iterations, but you do many implicit loops: list, set, again list, join (each do full iteration over items argument), and finally number of symbols * .count...
I guess that your solution is the worst ;P
appart of collection.Counter, if you want to implement equivalent, you could do:
text = input()
dict = {}
for char in text:
if char in dict: dict[char] += 1
else: dict[char] = 1
print(dict)
with this one, you count all char occurences with only one loop and few code lines ^^
0
Rigorous testing
0
What about this visph
word = input ("")
dictionary = {}
for letter in word:
dictionary.__setitem__(letter , word.count(letter) )
print( dictionary )
0
This is the shortest letters frequency count code. Your next step is to adapt it on reading a file. Try to count words, letters, lines of a file. Than do the same for the first 5 lines for example. This would jump you to the next level. enjoy practicing.
- 1
https://code.sololearn.com/cSP1ywsW4mMn/?ref=app
Check this one out... It is better than yours as your code iterates over the whole string multiple times due to count which is not necessary as one time iteration is enough