I am trying to create a program that asks a user to input a string and then displays the most frequently occurring characters in the string. I cannot use built in features such as dictionary. I think my problem now is that I have an infinite loop. How can I fix this? Here is my code:
string = input('Enter a string:')
#space for most popular character
pop_char = ''
#initialize number of times character appears
num = 0
#initialize index
index = 0
# pick one character at a time
for ch in string:
#initialize character counter
cc=0
#go through entire string and compare the character to the string characters
while index < len(string):
#if they are the same (converted to lower case), tally one to cc
if ch.lower() == string[index].lower():
cc = cc + 1
index = index + 1
#if count is greater than or equal to previous count, use this for
#popular character
if cc >= num:
num = cc
pop_char = ch
else:
index = index + 1
print('The most frequently occuring letter(s):', pop_char)
if cc >= num:
should beif cc > num:
On your first iteration, the first letter will equal the first letter of the string (obviously) and you will enter
if ch.lower() == string[index].lower():
. This will setcc
to1
which will, in turn, setnum
to1
as well.As they are both equal, as long as the second letter is not the same as the first, you will have an infinite loop that only enters the
if cc >= num
section and never updateindex
past1
.