find the largest number in that list and output its index, not the actual value

978 views Asked by At

This is the assignment on Codio. I am new to programming and don't know what to do here.

We will pass in a list of numbers. Your job is to find the largest number in that list and output its index, not the actual value.

Tip: you will need to use a utility variable to store the maximum value and a decision to see if each number is bigger than the current maximum value encountered in previous iterations.

# Get our numbers from the command line
import sys
numbers= sys.argv[1].split(',')
numbers= [int(i) for i in numbers]

# Your code goes here
3

There are 3 answers

4
Diana On

So, first, you have to send the values through command line, like this:

python app.py 1,2,3,4,5

This is the code:

First, you have to find the max value:

max_number = numbers[0]
for n in numbers:
  if n > max_number:
      max_number = n

Then, you just need to locate where that value is:

max_index = numbers.index(max_number)
print(max_index)

So the output will be: 4

Remember, it's 4 and not 5 because in Python, array indexes start at 0.

enter image description here

Edit:

In case you are not allowed to use the index function:

i = 0
for n in numbers:
  if n == max_number:
    break
  i += 1

print(i)

Of course, the easiest way is this:

max_number = max(numbers)
max_index = numbers.index(max_number)
print(max_index)
1
Yukun Li On

never use codio before, but here is how usually people find max of a list:

list1 = [1,2,3,4,5,6,10]
ans = list1.index(max(list1))

if you are not allowed to use max

list1 = [1,2,3,4,5,6,10]
ans = 0
for i,n in enumerate(list1):
  if n > list1[ans]:
    ans = i
return ans
0
Karthik On
import sys
if len(sys.argv) >= 2:
    numbers = sys.argv[1].split(',')
    numbers= [int(i) for i in numbers]
    max_index = 0
    maximum = numbers[0]
    for index, number in enumerate(numbers):
        if number > maximum:
            maximum = number
            max_index = index
    print "Maximum value:",maximum," at index:",max_index
else:
    print "No numbers entered"
    exit(1)

or

import sys
if len(sys.argv) >= 2:
    numbers = sys.argv[1].split(',')
    numbers= [int(i) for i in numbers]
    print numbers.index(max(numbers))
else:
    print "No numbers entered"
    exit(1)