Puzzle: Find the order of n persons standing in a line (based on their heights)

前端 未结 11 2209
抹茶落季
抹茶落季 2020-12-30 05:58

Saw this question on Careercup.com:

Given heights of n persons standing in a line and a list of numbers corresponding to each person (p) that gives the number of pers

11条回答
  •  醉话见心
    2020-12-30 06:20

    Here is a Python solution that uses only elementary list functions and takes care of ties.

    def solution(heights, infronts):
        person = list(zip(heights, infronts))
        person.sort(key=lambda x: (x[0] == 0, x[1], -x[0]))
        output = []
        for p in person:
            extended_output = output + [p]
            extended_output.sort(key=lambda x: (x[0], -x[1]))
            output_position = [p for p in extended_output].index(p) + p[1]
            output.insert(output_position, p)
        for c, p in enumerate(output):
            taller_infronts = [infront for infront in output[0:c] if infront[0] >= p[0]]
            assert len(taller_infronts) == p[1]
        return output
    

提交回复
热议问题