def main():
print("*** High School Diving ***")
num_judges=int(input("How many judges are there? "))
for i in range (num_judges):
scores=int(input("Ender a score: " ))
x=min(scores)
y=max(scores)
print("Min: ", x)
print("Max: ", y)
main()
4 に答える
リストを使用して、入力した各スコアをリストに追加する必要があります。
scores = []
for i in range (num_judges):
scores.append(int(input("Enter a score: " )))
max()
次に、そのリストからそれぞれ最高値とmin()
最低値を選択します。
代わりに、ループするたびに新しい値に置き換えていました。 scores
次に、1つの整数のを見つけてみてくださいmin()
。これは機能しません。
>>> min(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
リストを使用することにより、min()
関数はリストをループ(反復)して最小値を見つけることができます。
>>> min([1, 2, 3])
1
これを行う方法は他にもいくつかあります。
まず、少なくとも2人が、Martijn Pietersの回答による最初の回答とまったく同じものをすでに投稿しています。私は、取り残されたと感じたくないので、次のようにします。
scores = []
for i in range(num_judges):
scores.append(int(input("Enter a score: ")))
x=min(scores)
y=max(scores)
これで、空のリストを作成してループで追加する場合は常に、これはリスト内包表記と同じです。
scores = [int(input("Enter a score: ")) for i in range(num_judges)]
x=min(scores)
y=max(scores)
一方、num_judges
巨大で、最小値と最大値を見つけるためだけにその巨大なリストを作成したくない場合はどうでしょうか。さて、あなたはあなたが進むにつれてそれらを追跡することができます:
x, y = float('inf'), float('-inf')
for i in range(num_judges):
score = int(input("Enter a score: "))
if score < x:
x = score
if score > y:
y = score
最後に、両方の世界を最大限に活用する方法はありますか?通常、これはリスト内包表記の代わりにジェネレータ式を使用することを意味します。min
ただし、ここでは、とmax
スコアの両方が必要です。つまり、リスト(または他の再利用可能なもの)である必要があります。
あなたはこれを回避することができますtee
:
scores= (int(input("Enter a score: ")) for i in range(num_judges))
scores1, scores2 = itertools.tee(scores)
x = min(scores1)
y = max(scores2)
ただし、これは実際には役に立ちません。これは、内部で、tee
すでに作成したものと同じリストが作成されるためです。(tee
2つのイテレータを並行してトラバースする場合に非常に便利ですが、このような場合には役立ちません。)
したがって、前の例のループにmin_and_max
よく似た関数を作成する必要があります。for
def min_and_max(iter):
x, y = float('inf'), float('-inf')
for val in iter:
if val < x:
x = val
if val > y:
y = val
return x, y
そして、すべてを読みやすいワンライナーで行うことができます。
x, y = min_and_max(int(input("Enter a score: ")) for i in range(num_judges))
もちろん、それを機能させるために8行関数を記述しなければならなかったとき、それは実際には1ライナーではありません…ただし、8行関数は将来他の問題で再利用できる可能性があります。
あなたはほとんどそこにいましscores
た.リストを作成してそれに追加するだけで、これはうまくいくはずです:
def main():
print("*** High School Diving ***")
num_judges=int(input("How many judges are there? "))
#define scores as a list of values
scores = []
for i in range (num_judges):
scores.append(int(input("Ender a score: " ))) #append each value to scores[]
x=min(scores)
y=max(scores)
print("Min: ", x)
print("Max: ", y)
main()
のドキュメントを見て、max()
実際min()
にそこに構文が示されている場合、反復可能な型 (空でない文字列、タプル、またはリストなど) が必要であることに注意してください。
for ループ内に変数を作成していますがscores
、これはループ外には表示されません。次に、型ではないため、scores
反復ごとに値を上書きしようとしています。scores
list
scalar
ループの外側とループの内側で、各スコアをリストに型scores
として宣言する必要があります。list
append
scores = []
for i in range (num_judges):
scores.append(int(input("Ender a score: " )))
x=min(scores)
y=max(scores)