统计最大的数在Array中重复了多少次

问题描述 投票:0回答:1

我想出了这种方法来查找最高数字重复了多少次。 我想知道我是否正确检查了它,以及您是否可以在不使用函数的情况下给出类似的示例。 目标是显示最高的数字和重复的次数。

#we store elements in array
values = [11, 44, 9, 18, 44]

#we store first position
max = values[0]

# variable to count
count = 0

for x in values:
    if x > max:
        max=x

#check if max value is repited
for x in values:
    if max==x:
        count+=1

#we print value
print(max)

#we print repeated times 
print(count)

python arrays count max
1个回答
0
投票

这段代码没有问题。 无论如何,解决这个问题的更有效方法是仅迭代数组一次,如下所示:

for x in values:
    if x > max:
        max = x
        count = 1
    elif x  == max:
        count = count+1
© www.soinside.com 2019 - 2024. All rights reserved.