writing code to find out highest number in list
import sys
print ("Enter number of elements \n")
i = int(sys.stdin.read())
print ("Enter numbers \n")
input = sys.stdin.read()
numbers = input.split()
print ("Number of elements in list",len(numbers))
if (len(numbers)<=i):
print ("Valid Inputs \n", len(numbers))
max_index1=-1
for x in range(len(numbers)):
if ((max_index1==-1)or(numbers[x] >= numbers[max_index1])):
max_index1=x
print ("max index is",max_index1)
print ("Highest input number is", numbers[max_index1])
while executing this code I am getting correct output as below:
Enter number of elements
5
Enter numbers
10 45 32 23 21
Number of elements in list 5
Valid Inputs
5
max index is 0
max index is 1
Highest input number is 45
but sometimes the output is totally wrong:
Enter number of elements
5
Enter numbers
10 45 32 6 21
Number of elements in list 5
Valid Inputs
5
max index is 0
max index is 1
max index is 3
Highest input number is 6
can someone please help me to fix this code?
4 Answers 4
What you want to do is use the max function. You can call max on an array of numbers and it will return the largest number.
num_array = [5, 3, 6, 12, 3, 5]
largest = max(num_array)
print("Max num: {}".format(largest))
Comments
you should use int function in your code.
int(numbers[x]) >= int(numbers[max_index1]))
If you shouldn't, Python compare numbers[x] string and numbers[max_index1]
In dictionary order, "45" is behind "6"
2 Comments
The items in your list are strings, so they are being ordered lexicographically:
>>> '6' > '45'
True
>>> 6 > 45
False
You should convert the items in the list to integer type to do a numerical ordering by replacing:
input = sys.stdin.read()
numbers = input.split()
With:
numbers = [int(i) for i in input().strip().split()] # use 'raw_input' for Python 2
That reads the items in using the builtin input function, strips leading and trailing whitespaces, splits the string into a list and converts each item in the list to integer using a list comprehension.
Note that using input as a name is not a good idea as it shadows the builtin input function which you should probably be using in place of sys.stdin.read.
Comments
Currently your list numbers is a list of strings. To show this, you can print numbers.
>>> print(numbers)
['10', '42', '32', '6', '21']
In python 2.7, a string can be compared with another string with (possibly) surprising results
>>> '6' > '42'
True
To avoid this problem, you can change numbers to be a list of integers
>>> numbers = map(int, numbers)
>>> print(numbers)
[10, 42, 32, 6, 21]
where map allows you to apply a function to each of the elements of numbers and return the result.
inputis a reserved word, that your code blocks?