Reputation: 79
I have been trying to find the maximum element in a list using a simple program
print ("Enter the elements of array seperated by spaces : ")
t = str(raw_input())
arr = list()
arr = map(long,t.split(' '))
print arr
print max(arr)
for i in arr:
m=arr[0]
if i>m:
m=i
print ("The largest element in arary is : "+str(m))
The input that I passed in was :
1 2 3 4 5 23682967 4574 433
And the expected answer for the same should be 23682967
which is what I'm able to get using the inbuilt function of python called max()
but not from the code that I've written,
The output that my code gives is : 433
Can someone please guide me in understanding this behavior of python ?
Upvotes: 1
Views: 269
Reputation: 90889
The issue occurs because of the following line inside your for loop -
m=arr[0]
It causes i
to be checked against the first element in the array always causing your loop solution to return the last element that is bigger than the first element in the array which in your case is 433
.
You should have that line before the for loop. Example -
m=arr[0]
for i in arr:
if i>m:
m=i
Upvotes: 4