0
Need explanation please !?
Given a string as input, you need to output how many times each letter appears in the string. You decide to store the data in a dictionary, with the letters as the keys, and the corresponding counts as the values. Create a program to take a string as input and output a dictionary, which represents the letter count. Sample Input hello Sample Output {'h': 1, 'e': 1, 'l': 2, 'o': 1} Text = input () dict = {} for x in text : if x not in dict : print (dict) #output : {} {} {} {} {} {} {} {} Help !
6 ответов
+ 1
ola Scar
Since there is no key:value in dictionary and we are checking 1st character not exist in dictionary so we will add first character in string with count 1.
Next time if we check another character and if that character is exist then we will increase counter by 1 which is in else part
+ 2
ola Scar
Do this if character not exist in dict. If exist then increment 1
if x not in dict:
dict[x] = 1
else:
dict[x] += 1
+ 1
Nicest, thks
+ 1
a=input()
print({i:a.count(i) for i in a})
0
Thanks, explain me this line dict[x] = 1
0
You used the count () function inside the dictionary, it reduces the code. Interesting !!