By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,923 Members | 1,443 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,923 IT Pros & Developers. It's quick & easy.

How to construct this function

P: 3
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.
Apr 1 '11 #1
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Here's one way of doing it without using a loop:
Expand|Select|Wrap|Line Numbers
  1. >>> import operator
  2. >>> max(map(lambda x:operator.pow(x, 2), [5, -7, 3]))
  3. 49
  4. >>> 
Apr 1 '11 #2

P: 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
Apr 1 '11 #3

Rabbit
Expert Mod 10K+
P: 12,383
Do the same thing but instead of using the pow function, use an absolute value function.
Apr 1 '11 #4

bvdet
Expert Mod 2.5K+
P: 2,851
It can be done using an additional variable, list method index() and the indexing operator.
Expand|Select|Wrap|Line Numbers
  1. >>> numList = 5, -7, 3
  2. >>> sqList = map(lambda x:operator.pow(x, 2), numList)
  3. >>> numList[sqList.index(max(sqList))], max(sqList)
  4. (-7, 49)
  5. >>> 
Apr 2 '11 #5

Post your reply

Sign in to post your reply or Sign up for a free account.