如何统计单词中各字母出现次数?(禁止使用字典方法)
Hey there! Let's get your program working correctly. The main issue with your current code is that the nested loops are conflicting with each other, leading to incorrect counting and output. Right now, your inner for loop runs through the entire word every time, and the break makes it only print once—so it's not actually counting individual letter occurrences like you need.
What Your Original Code Does Wrong:
- The
whileloop starts at index 0, but then the innerfor letter in worditerates through every character, incrementingindexto the end of the word in one go. countends up being the total length of the word, not the count of the current letter.- The
breakafterprintstops the loop immediately, so you only get one output line instead of all letters and their counts.
Corrected Code (Counts Total Occurrences per Unique Letter)
Since you can't use dictionaries, we can track which letters we've already counted using a list, then iterate through the word to count each unique letter's total occurrences:
def compressed(word): # Keep track of letters we've already processed to avoid duplicates processed = [] for letter in word: if letter not in processed: count = 0 # Loop through the entire word to count this letter's occurrences for char in word: if char == letter: count += 1 # Print the letter and its count, staying on the same line print(letter, count, end=" ") # Add this letter to our processed list so we don't count it again processed.append(letter) # Print a newline at the end for clean formatting print() print("Enter a word:") word = input() compressed(word)
How This Works:
- We use a
processedlist to remember which letters we've already counted, so we don't repeat them in the output. - For each letter in the input word, we first check if it's already in
processed. If not:- We initialize a
countto 0. - We loop through the entire word again, incrementing
countevery time we find the current letter. - We print the letter and its count, then add the letter to
processed.
- We initialize a
- When you input
"aaaarggh", this will outputa 4 r 1 g 2 h 1exactly like you want.
Alternative: Count Consecutive Letters (Run-Length Encoding)
If you ever wanted to count consecutive letters instead of total occurrences (e.g., "ababa" would become a 1 b 1 a 1 b 1 a 1), here's how you could adjust the code:
def compressed(word): if not word: # Handle empty input case return index = 0 while index < len(word): current = word[index] count = 1 # Keep moving index while the next character is the same as current while index + 1 < len(word) and word[index + 1] == current: count += 1 index += 1 print(current, count, end=" ") index += 1 print() print("Enter a word:") word = input() compressed(word)
This version uses nested while loops to track consecutive characters, which is efficient if you only care about runs of the same letter.
内容的提问来源于stack exchange,提问作者Zahraa

