0

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
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

3 Answers3

1

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
Yukun Li
  • 244
  • 1
  • 6
0

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)
Diana
  • 140
  • 1
  • 13
  • `max` is a builtin, better use another name. Also, initialize it with `numbers[0]`. There could be `float('-inf')` in there. – actual_panda Nov 20 '19 at 19:21
  • It is better to post text than images of text: that way people can copy/paste any useful data. Otherwise retyping (or using awesome OCR software) is needed. – wallyk Nov 20 '19 at 19:28
  • @IT140user if it helped, mark it as right answer :) – Diana Nov 20 '19 at 19:43
  • 1
    @DianaAyala, why take the max of `numbers` and then take the index? They're both `O(n)` operations and the problem can be solved in 1 pass. – Brian Nov 20 '19 at 20:04
0
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)
Karthik
  • 1
  • 2