Write a program that takes sentence as input from the user and computes the frequency of each letter. Use a variable of dictionary type to maintain and show the frequency of each letter
st = input("Enter the string: ") d = dict() for c in st: if c in d: d[c] = d[c] + 1 else: d[c] = 1 print(d)
Output:
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
The provided Python code counts the frequency of each character in a given string and stores the counts in a dictionary. Here’s a detailed explanation of how the code works:
Explanation
- Prompt for Input:
st = input("Enter the string: ")
- This line prompts the user to enter a string and stores it in the variable
st
.
- Initialize an Empty Dictionary:
d = dict()
- An empty dictionary
d
is created. This dictionary will store characters as keys and their counts as values.
- Iterate Over Each Character in the String:
for c in st:
- A
for
loop iterates over each characterc
in the input stringst
.
- Update Character Counts:
if c in d: d[c] = d[c] + 1 else: d[c] = 1
- Inside the loop, an
if-else
statement checks if the characterc
is already a key in the dictionaryd
.- If
c
is in the dictionary, its count is incremented by 1 (d[c] = d[c] + 1
). - If
c
is not in the dictionary, it is added as a key with a count of 1 (d[c] = 1
).
- If
- Print the Result:
print(d)
- After the loop completes, the dictionary
d
, which now contains the frequency of each character, is printed.
Example
Let’s go through an example where the user inputs a string. Suppose the user inputs the following string:
Enter the string: hello
The code execution will be as follows:
- Input String:
st = "hello"
- Initialize Dictionary:
d = {}
- Iterate and Update Counts:
- For
c = 'h'
:d
becomes{'h': 1}
- For
c = 'e'
:d
becomes{'h': 1, 'e': 1}
- For
c = 'l'
:d
becomes{'h': 1, 'e': 1, 'l': 1}
- For
c = 'l'
:d
becomes{'h': 1, 'e': 1, 'l': 2}
- For
c = 'o'
:d
becomes{'h': 1, 'e': 1, 'l': 2, 'o': 1}
- Resulting Dictionary:
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
Full Code
Here is the complete code for reference:
st = input("Enter the string: ") d = dict() for c in st: if c in d: d[c] = d[c] + 1 else: d[c] = 1 print(d)
Output
For the input "hello"
, the output will be:
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
Summary
This code effectively counts the frequency of each character in a given string and stores the results in a dictionary, which is then printed. Each character from the string is either added to the dictionary with a count of 1 if it is encountered for the first time or has its count incremented by 1 if it is already present in the dictionary.