# [Tutor] Code not working advise pls

Cameron Simpson cs at zip.com.au
Fri Nov 4 21:19:00 EDT 2016

```On 04Nov2016 21:57, tracey jones-Francis <drtraceyjones at hotmail.com> wrote:
>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.
>
>In addition i want to write the code in a function with only one line of code in it.
>
>So far I have:-
>
>def sumHighest(a, n):
>lambda a, n : sum(a[:n])
>
>This doesn't work but i want to use lambda and the slice in the function.
>An appropriate test would be:-
>input - sumHighest([1,2,3,4], 2)
>output - 7

When you say it doesn't work, it is considered good practice to show a
transcript of it running, what its output (or error) was, and what you hoped to
see. You have provided the second though, which is a good start.

Just looking at the above, as written it should not even compile.

I am presuming you are trying to define "sumHighest" to perform the function
expressed in the lambda. In Python there are basicly two says to define a
function. The commonest way looks like this:

def sumHighest(a, n):
return sum(a[:n])

In a sense, this does two things: it defines a function which accepts `a` and
`n` and returns the result of a sum call; and secondarily, it _binds_ that
function definition to the name "sumHighest".

The less common way, which can be used if the function preforms a single Python
expression, looks like this:

sumHighest = lambda a, n: sum(a[:])

Here the two actions are more clearly separated: the "lambda" on the right hand
side defines a function just as the first example did, and the "sumHigest ="
_binds_ that function to the name "sumHighest".

Both forms now give you a callable function which can be used with the name
"sumHighest".

You seem to have mixed the two forms together. I hope the two example above
show you how they differ. Pick one.

Otherwise, you function isn't quite there. Look up Python's built in "sorted()"
function and consider how it may help.

If you come back with further queries, please include a cut/paste transcript of
the your program's code, and a run of it with the output. (NB: cut/patse the
text, don't attach a screenshot.)

Cheers,
Cameron Simpson <cs at zip.com.au>
```