Slicing and key-based sorting

Problem

Implement middle_sorted(records). records is a list of (name, score) tuples. Return a new list containing records[1:-1], sorted by descending score and then ascending name. Do not mutate records.

Starter code

def middle_sorted(records):
    pass
Reveal answer or reference solution
def middle_sorted(records):
    return sorted(records[1:-1], key=lambda row: (-row[1], row[0]))

Public tests

  • middle_sorted([('z',0),('b',2),('a',2),('c',1),('x',0)])[('a', 2), ('b', 2), ('c', 1)]
  • middle_sorted([('a',1)])[]

Local history

Loading attempts saved in this browser…

Use with your agent

Share this URL and your attempt. Ask the agent to start with a clarifying question or the smallest useful hint.

Tutor me on https://mlprep.iwase.dev/programming/python/original-py-slice-sort/. If window.mlPrepAgent is available, read attempts for item original-py-slice-sort before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record and read it back.

Appears in