I am new to python and I was trying to write a program that gives the frequency of each letters in a string from a specific point. Now my code is giving correct output for some inputs like if I give the input "hheelloo", I get the correct output, but if the input is "hheelllloooo", the frequency of h,e and l is printed correct, but the frequency of 'o' comes out as 7 if the starting point is index 0. Can somebody tell me what am i doing wrong.
Write a Python program that counts the occurrence of Character in a String (Do not use built in count function. Modify the above program so that it starts counting from Specified Location.
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i 1,len(str)):
if str[i] == str[j]:
count = 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1
CodePudding user response:
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i 1,len(str)):
if str[i] == str[j]:
count = 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1 // <----- This line should be outside the if block.
The error was because of indentation. I have just properly indented the last line.
Thanks, if it works, kindly upvote.
CodePudding user response:
string
module can be useful and easy to calculate the frequency of letters, numbers and special characters in a string.
import string
a='aahdhdhhhh2236665111...//// '
for i in string.printable:
z=0
for j in a:
if i==j:
z =1
if z!=0:
print(f'{i} occurs in the string a {z} times')
If you want to calculate the frequency of characters from a particular index value, you just have to modify the above code a little as follows:
import string
a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
z=0
for j in a[c:]:
if i==j:
z =1
if z!=0:
print(f'{i} occurs in the string a {z} times')