Emma
Emma

Reputation: 91

Find the sum and position of the maximum value in a list

I'd like to create a function that will print the sum and the position of the maximum value within a list of numbers, but I'm not sure how to go about doing so.. This is what I've started with so far:

I used some code off a similar question that was asked.

def maxvalpos(variables):
    max = 0 
    for i in range(len(variables)):
        if variables[i] > max:
            max = variables[i]
            maxIndex = i 
    return (max, maxIndex)

print maxvalpos(4, 2, 5, 10)

When I run this code it just returns that the function can only take 1 argument. Thank you.

Upvotes: 0

Views: 179

Answers (3)

John La Rooy
John La Rooy

Reputation: 304127

An easier way to do this

>>> from operator import itemgetter
>>> maxpos, maxval = max(enumerate(my_list), key=itemgetter(1))

eg.

>>> max(enumerate([4, 2, 5, 10]), key=itemgetter(1))
(3, 10)

Upvotes: 1

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

The pythonic way of doing this:

my_list_sum=sum(my_list)
index_max=my_list.index(max(my_list))

This finds the sum of the list and the index of the maximum of the list

But the problem in your code is: You are sending four variables to the function and receiving only 1 variable. For that to work, use:

maxvalpos([4,2,7,10])

This sends only one argument, a list to the function

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798466

Then give it one argument, or modify the definition.

print maxvalpos([4, 2, 5, 10])

or

def maxvalpos(*variables):

Upvotes: 5

Related Questions