Code Signal_練習題_Sort by Height
阿新 • • 發佈:2018-07-22
amp eight += order enum should put style spl
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180]
, the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]
.
我的解答:
1 def sortByHeight(a): 2 j = -2 3 y = 0 4 li = [] 5 if -1 not in a: 6 a = sorted(a) 7 else: 8 for i in a: 9 if i == -1: 10 pass 11 else: 12li.append(i) 13 a[a.index(i)] = j 14 j -= 1 15 li = sorted(li) 16 for x in a: 17 if x != -1: 18 a[a.index(x)] = li[y] 19 y += 1 20 return a
感覺自己總是不按常規出牌
膜拜大佬:
1 def sortByHeight(a):View Code2 3 l = sorted([i for i in a if i > 0]) 4 for n,i in enumerate(a): 5 if i == -1: 6 l.insert(n,i) 7 return l
Code Signal_練習題_Sort by Height