【发布时间】:2021-03-26 16:32:10
【问题描述】:
我编写了这段代码,但我正在努力替换使用 break,因为它在作业中说我们不允许在循环中使用 continue/break 语句。
代码的目标是:
查找输入参数字符串中出现频率最高的字符并返回。例如,如果字符串是“Canada day”,则函数返回字符串“a”
如果有两个或更多字符频率相同,则函数应返回多个频率相同的值中的第一个。
def find_frequent(s):
"""
-------------------------------------------------------
description
Use:
-------------------------------------------------------
Parameters:
name - description (type)
Returns:
name - description (type)
------------------------------------------------------
"""
L = []
count = 0
char = 0
i = 0
words = True
while i < 1 and words:
x = s[i]
for j in range(len(L)):
if x == L[j]:
words = False
L[j + 1] = L[j + 1] + 1
else:
L.append(x)
L.append(1)
for i in range(1, len(L), 2):
if L[i] > count:
count = L[i]
char = L[i - 1]
return char
the output should look like this
`Enter a string: Hello Hi`
output should be
`Most frequent characters: H`
I'm getting this output
Enter a string: canada
Most frequent character: c
【问题讨论】:
-
避免使用
break的解决方法是在while condition:中更改for循环,而不是breaking,而是将condition设置为false,循环结束。
标签: python