题:
1.功能:输入任意一个整数数组,得到想要的数组输出;
(如下是两个case):
1)输入数组:[1,2,3,4,5,7,8] ==>输出数组:[“1->5”,”7->8”]
2)输入数组:[1,4,5,6,9,10]==>输出数组:[“1”,”4->6”,”9->10”]
请理解case中的输出规则,写一个函数实现如上功能;
def s(l1):
l = []
start = l1[0]
for i,j in enumerate(l1):
if i+1 < len(l1) and l1[i+1] - j == 1:
pass
elif i+1 < len(l1) and l1[i+1] - j != 1:
if start == j:
s = '%s'%j
else:
s = "%s->%s" % (start, j)
l.append(s)
start = l1[i+1]
else:
if start == j:
s = '%s' % j
else:
s = "%s->%s" % (start, j)
l.append(s)
return l
l = [1, 2, 3, 4, 5, 7, 8]
l1 = [1,4,5,6,9,10,12]
print(s(l1))
代码看起来很low 但是功能确实显示了 ,有兴趣再优化吧~~