[Tutor] sumHighest function help

Alan Gauld alan.gauld at yahoo.co.uk
Fri Nov 4 21:26:11 EDT 2016


On 04/11/16 16:44, Lloyd Francis wrote:

It looks suspiciously like you posted this same message
from two addresses with different subjects, please don't
do that as it splits the responses and makes searching
archives more difficult.

> I want to write a function that will calculate and return the sum of the *n*
> highest value in a list *a. *Also, when n is less than 0, the answer should
> be zero, and if n is greater than the number of elements in the list, all
> elements should be included in the sum.

I'm not totally clear what you mean. Lets conmsider the value of n:

if n < 0 return 0
if n == 0 return ???
if n > len(lst) return sum(lst)
if n > 0 and n < len(lst) return sum of n "highest" values
 - define highest? eg. What are the 3 highest values in the
   list [1,7,3,9,2,5,1,9]
   are they: [5,1,9] - highest positions
             [9,9,7] - highest valued items
             [9,7,5] - highest individual values
             or something else?

Can you clarify the 2nd and last cases please?

> In addition i want to write the code in a function with only one line of
> code in it.

This is a strange and wholly artificial request.
We can write almost any function with one line but
it's rarely a good idea. Let's ignore it for now and
focus on writing a function that works. If we really
need to we can reduce it to one line later.


> So far I have:-
> 
> def sumHighest(a, n):
> lambda a, n : sum(a[:n])

This makes no sense since your function does not return any value.
And the lambda line defines a function but never calls it.

I'd suggest following the logic of your requirement above:

def sumHighest(a,n):
   if n < 0: return 0
   if n > len(a): return sum(a)
   if n == 0: return ???? # you must clarify
   else:
      newlist = find_N_highest(a,n)
      return sum(newlist)

> This doesn't work but i want to use *lambda *and the slice in the function.

Its not clear what role the slice plays until we
understand what is meant by "highest" And lambda
just returns a function which is not what you want.
You may need a lambda to filter your list but again
we don't know until we understand your requirement
better.

> An appropriate test would be:-
> 
> input - sumHighest([1,2,3,4], 2)
> output - 7

This could mean any of the cases I gave above, it
doesn't clarify anything.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list