How to construct this function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nana pink
    New Member
    • Mar 2011
    • 3

    How to construct this function

    I am trying to construct a function called maxSquare. In which it takes a list of integers X and returns Xi with the maximum square value, without using loops.

    Sample Input/Output

    >>> maxSquare([5, ‐7, 3])
    -7


    If you coul help me with this, I would appreciate it.

    Thanks in advance.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Here's one way of doing it without using a loop:
    Code:
    >>> import operator
    >>> max(map(lambda x:operator.pow(x, 2), [5, -7, 3]))
    49
    >>>

    Comment

    • nana pink
      New Member
      • Mar 2011
      • 3

      #3
      Thank you bvdet for your solution, you are almost there.
      But, how can we return the original value which are -7?

      >>> maxSquare([5, ‐7, 3])
      -7

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Do the same thing but instead of using the pow function, use an absolute value function.

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          It can be done using an additional variable, list method index() and the indexing operator.
          Code:
          >>> numList = 5, -7, 3
          >>> sqList = map(lambda x:operator.pow(x, 2), numList)
          >>> numList[sqList.index(max(sqList))], max(sqList)
          (-7, 49)
          >>>

          Comment

          Working...