这是我的任务:
编写一个程序,从键盘读取文本,直到找到感叹号('!')。
使用由字母“A”到“Z”下标的整数数组,计算每个字母出现的次数。在单独的计数器中,还计算“其他”字符的总数。
打印出找到最多的字母。(请注意,可能有多个字母附有最大计数。)另外,打印出找到最少次数的字母(或字母),但确保排除根本没有找到的字母。
这是我的代码:
msg = input("What is your message? ")
print ()
num_alpha = 26
int_array = [0] * num_alpha
vowel = [0] * 10000
consanant = [0] * 10000
for alpha in range(num_alpha):
int_array[alpha] = chr(alpha + 65)
if int_array[alpha] == 'A' or int_array[alpha] == 'E' or int_array[alpha] == 'I' or int_array[alpha] == 'O' or int_array[alpha] == 'U':
vowel[alpha] = int_array[alpha]
else:
consanant[alpha] = int_array[alpha]
print()
lett = 0
otherch = 0
num_vowels = 0
num_consonants = 0
count_character = [0] * 100000
length = len(msg)
for character in msg.upper():
if character == "!":
otherch = otherch + 1
count_character[ord(character)] = count_character[ord(character)] + 1
break
elif character < "A" or character > "Z":
otherch = otherch + 1
count_character[ord(character)] = count_character[ord(character)] + 1
else:
lett = lett + 1
count_character[ord(character)] = count_character[ord(character)] + 1
alpha = ord(character) - ord('A')
if vowel[(alpha)] == (character):
num_vowels = num_vowels + 1
else:
num_consonants = num_consonants + 1
print()
print("Number of Letters =", lett)
print("Number of Other Characters = ", otherch)
print("Number of Vowels = ", num_vowels)
print("Number of Consanants = ", num_consonants)
print()
for character in msg.upper():
print("Character", character, "appeared" , count_character[ord(character)] , "time(s).")
if character == "!":
break
print()
max_letter = -999999999999
min_letter = 999999999999
count_hi = 0
count_low = 0
for character in msg.upper():
if count_character[ord(character)] > max_letter:
max_letter = count_character[ord(character)]
count_hi = count_hi + 1
print("Character" , msg[count_hi + 1] , "appeared the most. It appeared", max_letter, "times.")
print(count_hi)
for character in msg.upper():
if count_character[ord(character)] < min_letter:
min_letter = count_character[ord(character)]
count_low = count_low + 1
print("Character" , msg[count_low + 1] , "appeared the least. It appeared", min_letter, "times.")
print(count_low)
我知道计数器完全错误,但我似乎无法弄清楚。有任何想法吗?
编辑:
如果我输入字符串:“AAAAAAAAAAAAAAAAAAAaaaaaaaaaaaHHHHHh!”
它打印出来:
人物A出现最多。它出现了 29 次。1 字符 A 出现最少。出现了1次。3
显然第一个字符串是正确的,但第二个应该说字符 h 出现最少。