I'm still a beginner, so I'd be happy if you could give me some advice. Now, let's get into the main subject. Here, we will create an algorithm that uses python to find the maximum value from n numbers. I thought about the algorithm myself as much as possible. Surprisingly, it is hard to make an algorithm to find the maximum value. .. .. Algorithm is difficult! !! !!
Below is the algorithm I made (sorry for the chords!)
max.py
num = int(input("How many pieces do you want to substitute?"))
i = 0
value_list = [] #Prepare an array to store numbers
while i < num:
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
i += 1
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
print(max_value) #Output maximum value
I will explain the flow
num = int(input("How many pieces do you want to substitute?"))
i = 0
value_list = [] #Prepare an array to store numbers
while i < num:
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
i += 1
Here, enter n (the number of numerical values to be compared). I used a list to work with numbers all together. You can now store n values. append () is the default method in python. Now you can add numbers to the array from now on.
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
Here, the numerical values stored in the list are taken out in order and compared, but the maximum value is initialized to 0 first. Then, if a value larger than the maximum value candidate is found by comparing in order, that value is reset to the maximum value candidate. And finally, the maximum value is output and the end.
How was it? Surprisingly, the algorithm for finding the maximum value was difficult for programming beginners. I think the engineers are really amazing. I respect you.
Recommended Posts