# 6 lines python

• ``````def reconstructQueue(self, people):

people = sorted(people, key=lambda x: x[1])
people = sorted(people, key=lambda x: -x[0])
res = []
for p in people:
res.insert(p[1], p)
return res``````

• combine

``````    people = sorted(people, key=lambda x: x[1])
people = sorted(people, key=lambda x: -x[0])
``````

to

``````    people = sorted(people, key=lambda x: (-x[0], x[1]))
``````

5 lines remained

• Ugly one-liner :-)

``````def reconstructQueue(self, people):
return reduce(lambda q, p: q.insert(p[1], p) or q, sorted(people, key=lambda (h, t): (-h, t)), [])``````

• Can anyone explain how this works?

• @ts That won't work

• @StefanPochmann said in 6 lines python:

Ugly one-liner :-)

``````def reconstructQueue(self, people):
return reduce(lambda q, p: q.insert(p[1], p) or q, sorted(people, key=lambda (h, t): (-h, t)), [])
``````

Can you explain why this approach works?

• @agave Do you mean my particular implementation or already @Xilai626's, i.e., the underlying idea? (I'm uncertain because you're explicitly asking me.)

• @StefanPochmann I understand your implementation, I meant the idea. I am asking you because you're very good at explaining things and concepts :-)

• @agave Ok, I just posted an explanation here.

• after sorted the people is

[[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]

then

res.insert(p[1], p)

how it comes to the answer ? is the p[1] a position?

• @zchang0307 Yes, p[1] is the position that the item should be inserted.

• i do not understand why should sort twice at here.

``````    people = sorted(people, key=lambda x: x[1])
people = sorted(people, key=lambda x: -x[0])
``````

I konw it should sort by 2nd column descending when the 1st column are equal. Who can explain it?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.