promotion image of download ymail app

Python: maximim?

Write a function called maximum according to the specification:



    Name : maximum


        L : a list of numbers


        The largest number in the list


    maximum([50,100,30,27]) == 100

    maximum([-3,-5]) == -3



Write the function without using:

1. range

2. max function

3. sort

4. sorted

2 Answers

  • 1 month ago
    Favorite Answer

    Functions are the most important aspect of an application. A function can be defined as the organised block of reusable code which can be called whenever required. A function is a block of organised, reusable code that is used to perform a single related action

    >>> def maximum(*numbers):

    ... if len(numbers) == 0:

    ... return None

    ... else:

    ... maxnum = numbers[0]

    ... for n in numbers[1:]:

    ... if n > maxnum:

    ... maxnum = n

    ... return maxnum


    • ...Show all comments
    • Quentin
      Lv 7
      1 month agoReport

      def maximum (L):
         while len(L)>1:
          return L[0] if len(L) else None

    • Commenter avatarLogin to reply the answers
  • 1 month ago

    That's a standard, built-in function: max(seq) returns the maximum value in a sequence (list, tuple, set, etc.), so this could be as simple as:

    def maximum(L):

         return max(L)

    If you're writing this to practice looping and conditional statements; then the usual approach is to loop through the elements if the input list, comparing each value with the largest value seen before. 

        for n in numbers:

            if n > max_seen:

                max_seen = n

    You need a starting value for max_seen.  It must be less than or equal to the largest number on the list (why?) and the easiest way to do that is to simply copy the first element.  Add this before the loop:

        max_seen = numbers[0]

    ..and then return max_seen after the loop has finished.

    • ...Show all comments
    • husoski
      Lv 7
      1 month agoReport

      I showed you all the pieces you needed; and those didn't use  any forbidden functions.  By the way, don't hand in that other answer.   It doesn't quite do what you were asked to do. 

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.