+ 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)

12th Mar 2021, 7:31 AM
Solomon David
Solomon David - avatar
9 Respuestas
+ 1
So what do you want?
12th Mar 2021, 7:36 AM
K.S.S. Karunarathne
K.S.S. Karunarathne - avatar
+ 1
You test it yourself. Thats a huge part of programming. Have fun!
12th Mar 2021, 8:12 AM
Slick
Slick - avatar
+ 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)
12th Mar 2021, 8:35 AM
visph
visph - avatar
+ 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)
12th Mar 2021, 9:36 AM
visph
visph - avatar
+ 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 ^^
12th Mar 2021, 2:33 PM
visph
visph - avatar
0
Rigorous testing
12th Mar 2021, 7:54 AM
Solomon David
Solomon David - avatar
0
What about this visph word = input ("") dictionary = {} for letter in word: dictionary.__setitem__(letter , word.count(letter) ) print( dictionary )
12th Mar 2021, 9:32 AM
K.S.S. Karunarathne
K.S.S. Karunarathne - avatar
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.
12th Mar 2021, 10:37 AM
iTech
iTech - avatar
- 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
14th Mar 2021, 7:18 AM
rajshekhar y dodamani
rajshekhar y dodamani - avatar