0

I am doing a problem that my school has assigned to me. Here is code till now:

profits = [1,2,5,6]
weights = [2,3,4,5]
n = 8
ratio = []
count = 0
for i in range(len(profits)):
    ratio.append([])
for i in range(len(ratio)):
    ratio[i].append(weights[i])
    ratio[i].append(profits[i] / weights[i])

The output (ratio):

[[2, 0.5], [3, 0.6666666666666666], [4, 1.25], [5, 1.2]]

But the problem is that I want the list to be sorted maximum ratio wise like this:

[[4, 1.25], [5, 1.2], [3, 0.6666666666666666], [2, 0.5]]

3 Answers 3

1

You can pass a key parameter to .sort().

Below your current code, add:

ratio.sort(key=lambda x: x[1])

to sort on the ratio (as opposed to the default sorting mechanism, which starts at the first element in the list).

After this sorting operation, ratio will be:

[[2, 0.5], [3, 0.6666666666666666], [5, 1.2], [4, 1.25]]
Sign up to request clarification or add additional context in comments.

Comments

1

Please try:

print(sorted(ratio, key=lambda x: float(x[1]), reverse=True))

Output:

[[4, 1.25], [5, 1.2], [3, 0.66666666666666663], [2, 0.5]]

1 Comment

I already did it but thanks for your answer.
1

you can try sorting by the ratios and then reverse the list

def key(e):
# To sort by the 2nd element
  return e[1]

profits = [1,2,5,6]
weights = [2,3,4,5]

ratio =[]
for i in range(len(profits)):
    ratio.append([])
for i in range(len(ratio)):
    ratio[i].append(weights[i])
    ratio[i].append(profits[i] / weights[i])

print(ratio)
ratio.sort(key=key)
ratio = ratio[::-1]
print(ratio)

3 Comments

Why sorting the first element and what does this do: ratio.sort(key=key)
key parameter of sort() function takes some function(which you can define) as value. sorting will happen based on the return of this function. for example, if you want to sort a bigger 2d list on the basis of its 3rd element def key(e): return e[2] ratio.sort(key=key)
OK. Thanks I get it now.

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.