检查Python for循环中的变量是否改变



我这里有这段代码,我正在寻找一种方法来检查min_score和max_score是否改变,并计算它改变了多少次。我似乎找不到做这件事的方法:

games = int(input())
score = list(input().split())
score = [int(x) for x in score]
for y in range(1, len(score) + 1):
min_score = (str(min(score[:y])) + " MIN")
max_score = (str(max(score[:y])) + " MAX")
print(min_score)
print(max_score)

这是一个示例测试用例供参考:

9
10 5 20 20 4 5 2 25 1

第一个数字是数组的大小,在我的代码中我从未使用过,因为我只是从下面的数字字符串创建一个数组(事实上我甚至不知道为什么他们给出大小)。基本上,我需要找到最大值和最小值变化的次数。我还是一个编程初学者,我真的不知道该怎么做。

你可以只记录遇到的最低和最高分数,并检查当前分数是略高于还是略低于。一个简单的脚本可以像这样:

scores = [10,5,20,20,4,5,2,25,1]
countChanges = 0
limitLow  = float("inf")
limitHigh = -float("inf")
for s in scores:
if(s < limitLow):
countChanges += 1
limitLow = s
if(s > limitHigh):
countChanges += 1
limitHigh = s

print("current score: %3d   limits: [%2d .. %2d]   changes:%d" % (s, limitLow, limitHigh, countChanges))
spam = [10, 5, 20, 20, 4, 5, 2, 25, 1]
print(sum(n < min(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
print(sum(n > max(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))

输出
4
2

如果您还想说明初始值-添加1.

看起来像一个hankerrank问题?它们通常给出输入的长度,以便在不知道len()等内置方法的情况下提供解决方案。

,您可以将min和max初始化为数组的第一个元素(如果存在,请检查规范),或者一些适当的大小值(再次检查可能的值)。

然后你可以计算最小值和最大值变化的次数。

应该足够容易适应的情况下,你只是想跟踪任何变化,而不是最小和最大分开。从你的问题看不清楚。

scores = [10, 5, 20, 20, 4, 5, 2, 25, 1]
min_score = scores[0]
max_score = scores[0]
min_score_changes = 0
max_score_changes = 0
for score in scores:
if score < min_score:
min_score = score
min_score_changes += 1
if score > max_score:
max_score = score
max_score_changes += 1

经过一番思考,我是这样解决的:

games = int(input())
score = list(input().split())
score = [int(x) for x in score]
min_score_list, max_score_list = [] , []
for y in range(1, len(score) + 1):
min_score = (min(score[:y]))
max_score = (max(score[:y]))
if min_score not in min_score_list:
min_score_list.append(min_score)
if max_score not in max_score_list:
max_score_list.append(max_score)
print((len(max_score_list) - 1), len(min_score_list) - 1)

我知道这不是完美的代码,但至少我自己做到了:D

最新更新