[Python] Create a program that takes a string as input and output a dictionary representing the letter count
17 Answers
New AnswerIt's the end of module project of the intermediate python course. My code passed the first two tests but fails the last two and I don't know why. If anyone can help, here's my code: text = input() dict = {} letter_list = [] text=text.lower() for x in text: if x not in letter_list: letter_list.append(x) count=0 counts=[] for x in text: for y in text: if x == y: count+=1 text=text.replace(x,"") counts.append(count) count=0 for x in counts: if x ==0: counts.remove(x) for i in range(len(letter_list)): if letter_list[i] not in [" ","-","'","!","?"]: dict[letter_list[i]]=counts[i] print(dict)
3/3/2021 10:03:31 AM
Bassel17 Answers
New AnswerFrogged , Paul K Sadler , Vitaly Sokol comparison of execution times of the different code snippets: https://code.sololearn.com/cHAuW8ZHsNsJ/?ref=app
Use dictionary comprehension # read input <text> text = input() # collect unique characters in a set unique_chars = set( text ) # build a dictionary with the character as key # and frequency of the character as value stat = { c : text.count( c ) for c in unique_chars } # print dictionary print( stat )
Bassel Selim Alamir Hanna In that case, need to import collections module and use OrderedDict https://code.sololearn.com/cnHJSGBD2W87/?ref=app
text = input() dict = {} for l in text: if l in dict: dict[l]+=1 else: dict[l]=1 print(dict) But I like Frogged and Jan Markus [PRO_crastinator] solutions better
Paul K Sadler I always love posts with many ways to solve a tiny challenge. Would not like to miss yours.
for letter in text: dict[letter] = dict.get(letter, 0) + 1 This for loop will loop through the letters in your string and if the letter has not been added to the dictionary yet, it will add it and change the count to 1, otherwise it will increment the count. I think this is what youre trying to do correct?
Ipang I forgot to specify that that the letters in the dictionary need to be in the order of appearance in the string.
text = input() v=[b for b in text] dict={} for i in v: if i in dict: dict[i]+=1 else: dict[i]=1 print(dict)
Jan Markus [PRO_crastinator] Counter looks like it orders the dictionary by count of occurrences, instead of by order of occurrence. Very handy, but not what Bassel Selim Alamir Hanna asked for
SoloLearn Inc.
4 Embarcadero Center, Suite 1455Send us a message