1

I have a plot y vs x. Based on some boundary conditions, I have obtained a list of x-values and corresponding y-values

x = [2, 4, 8, 11, 18, 24, 31]

the corresponding y-values are

y = [180, 139, 144, 90, 81, 109, 153]

the output is an array that returns twice the value of x output = [4, 8, 16, 22, 36, 48, 62]

My task is to limit the final output array to 5 values maximum. These values should correspond to the 5 highest values in the array y.

So, I should get

output = [4, 8, 16, 48, 62]

Also, different data sets will give different no. of x and y values. So, if the original output array has less than or equal to 5 values, it should be printed as it is.

I am trying to find a way to do this with a couple of lines of code.

1
  • So, have you done this already with more than the couple of lines you're aiming for (which would be a refactoring issue), or are you having problems implementing this at all? What have you attempted so far? Commented Dec 6, 2018 at 11:51

2 Answers 2

1

Your problem basically comes down to the question on how to obtain n highest values of an array. You will need the argsort() for this.

if len(y) > 4:
    n_highest = 5
else:
    n_highest = len(y)

y_highest = y.argsort()[-n_highest:][::-1] # this gives you the indices of the five highest values of y

x_out = x[y_highest] * 2

If you don't want x_out to be sorted, but rather reflect the original sorting, you'd have to iterate through eatch item, asking if its index is found in y_highest:

x_out = [x[i]*2 for i in range(len(x)) if i in y_highest]
Sign up to request clarification or add additional context in comments.

Comments

1

You can reorder the array with

array = sorted(array)

After that you just need to take the 5 first terms:

output = array[0:4]

Remember that we need to write 4 instead of 5 because on Python array's dimension starts ar 0. You can do this with less code:

output = sorted(array)[0:4]

1 Comment

Only problem is, rahul needs the indices of the n highest values of y and extract those from x. Hence I suggest argsort instead of sorted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.