码迷,mamicode.com
首页 > 其他好文 > 详细

Code Signal_练习题_Sort by Height

时间:2018-07-22 20:45:31      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:pre   stand   rate   none   opened   pass   open   which   习题   

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:
12                 li.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):
2 
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
View Code

 

Code Signal_练习题_Sort by Height

标签:pre   stand   rate   none   opened   pass   open   which   习题   

原文地址:https://www.cnblogs.com/YD2018/p/9351176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!