This is a modified version of "Let's find the maximum value python" that I raised the other day. The bad points and changes of the previous code are as follows.
-When all the elements of the list are negative, the maximum value becomes 0. ・ Processing speed is slow
-Set the initial value of the maximum value candidate to an appropriate element of the list ・ Change from while statement to for statement
I tried refactoring based on two bad points
num = int(input("How many pieces do you want to substitute?"))
value_list = [] #Prepare an array to store numbers
for i in range(num):
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
max_value = value_list[0] #Initialize with list elements
for i in range(num):
if value_list[i] > max_value:
max_value = value_list[i]
print(max_value) #Output maximum value
Substitution(Change before)
while i < num:
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
i += 1
Substitution(After change)
for i in range(num):
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
Comparison(Change before)
max_value = 0 #Initialize maximum value to 0
i = 0
while i < num:
if value_list[i] >= max_value: #Compare the stored numbers in order
max_value = value_list[i]
i += 1
Comparison(After change)
max_value = value_list[0] #Initialize with list elements
for i in range(num):
if value_list[i] > max_value:
max_value = value_list[i]
By setting the initial value to the input element, the maximum value will be output normally even when all the input elements are negative. Furthermore, by changing from a while statement to a for statement, initialization and addition processing are no longer wasted.
I was pointed out in a comment that python has a function to find the maximum value from an object with a given element, so I tried using it immediately.
num = int(input("How many pieces do you want to substitute?"))
value_list = [] #Prepare an array to store numbers
for i in range(num):
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
print(max(value_list))
Output result
How many pieces do you want to substitute? 3
Substitute a number-3
Substitute a number-2
Substitute a number-5
-2
Thank you to everyone who gave us their opinions and suggestions.
Recommended Posts