0

So I'm trying to create a function that determines the maximum of a set of values, from scratch.

I'm not sure how to make the function change the new value of Max after a new Max has been found, I'm also not sure if my usage of args is correct.

def Maximum(*args):
    Max = 0
    for item in List:
        if item > Max:
            item = Max
    return Max


List = [1,5,8,77,24,95]

maxList = Maximum(List)
print str(maxList)

Any help would be hugely appreciated.

3
  • for item in List should be for item in args. Commented Jul 27, 2016 at 20:12
  • 1
    Another bug is if args is a list of negative numbers, it will return 0. You could fix it by error handling for when args is empty, and then setting Max = args[0] Commented Jul 27, 2016 at 20:34
  • and key , default? Commented Mar 7, 2019 at 7:35

3 Answers 3

1

You've got one line of code backwards. Your if statement is effectively saying that if item is greater than Max, set item to Max. You need to flip that to say if item is greater than Max, set Max to item.

if item > Max:
    Max = item
return Max

Also, I'm not an expert in Python, but i think you need to change the List inside your function to match the parameter name, in this case args.

Sign up to request clarification or add additional context in comments.

1 Comment

you should return Max after the for loop
1

*args = list of arguments -as positional arguments

You are passing a list as an argument here. So your code should look something like this -

def maximum(nums):
   Max = 0
   for item in nums:
       if item > Max:
           Max=item
   return Max

List = [1,5,8,77,24,95]
print maximum(List)

This would give you the result : 95.

On the other hand you can use the max built in function to get the maximum number in the list.

print max(List)

Comments

1

Using reduce():

Python 2

def Maximum(data):
    return reduce(lambda x, y: x if x > y else y, data)

In Python 3, add

from functools import reduce

Output:

print(Maximum([4, 8, 4, 19, -1]))

19

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.