An important part of automated document analysis is measuring the frequency at which words and characters appear in the document. Search engines and other tools can use this to try to determine whether two documents are related to each other in a significant way (so that both are returned as search results, etc.) We are going to build up to producing frequency analysis for words in documents, by beginning with frequency counts for characters in a string. The frequency with which a character appears is the count of the number of times the character appears in the string. The relative frequency is the frequency divided by the total number of letters in the string. The file "hw2problem2.py" contains a function called frequency(), which takes two arguments: a single character string named c, and a target string named s. Complete the body of the function to compute the relative frequency with which character c appears in string s by doing the following: 1. First, count the number of times that c appears in s. 2. Second, compute the total number of characters in s. 3. Third, divide the result of the step 1 by the result of step 2. 4. Fourth, multiply the result of step 3 by 100. 5. Fifth, round the result to two decimal places (Study the built-in function round()). Return the final value as the result of the function—the relative frequency with which c appears in s. For example, if I call frequency("i", "Mississippi"). The letter "i" appears 4 times in the string "Mississippi". The total number of characters in "Mississippi" is 11. 4 ÷ 11 = 0. 3636തതതത. 0.3636തതതത × 10 = 36.3636തതതത. Rounded to two decimals the result is 36.36 %.
Need help with the coding on Python
If you have any doubts, please give me comment...
def frequency(c, s):
# 1. First, count the number of times that c appears in s.
c_occ = 0
for ch in s:
if ch==c:
c_occ += 1
# 2. Second, compute the total number of characters in s.
length_s = len(s)
# 3. Third, divide the result of the step 1 by the result of step 2
freq = c_occ/length_s
# 4. Fourth, multiply the result of step 3 by 100.
freq_perc = freq*100
# 5. Fifth, round the result to two decimal places
freq_perc = round(freq_perc, 2)
# Return the final value as the result of the function
return freq_perc
result = frequency("i", "Mississippi")
print("The relative frequency is "+str(result)+"%.")
Get Answers For Free
Most questions answered within 1 hours.