2024-04-18 22:10:07 发布
网友
a)输入是数字列表
i/p = > [2,5,1,4,7,3,1,2,3]
b)输出应按子列表排序
o/p = > [[2,5],[1,4,7],[3],[1,2,3]]
另一种解决方案:
def sortedsublist(): '''create sorted sublist from the given list''' inputl = [] sortedl = [] subl = [] inputl = [7,8,9,2,3,1,2,3,1,2,1] for i in range(len(inputl)): try: if inputl[i] <= inputl[i+1]: subl.append(inputl[i]) else: subl.append(inputl[i]) sortedl.append(subl) subl= [] except IndexError: subl.append(inputl[i]) sortedl.append(subl) subl = [] print sortedl return if __name__="main": sortedsublist()
算法
input = [2,5,1,4,7,3,1,2,3] output = [[]] for idx,val in enumerate(input): if idx > 0 and input[idx-1] > input[idx]: output.append([val]) else: output[-1].append(val) print output
输出为
[[2, 5], [1, 4, 7], [3], [1, 2, 3]]
用文字解释算法:
创建带有空子列表的输出列表。枚举输入列表。如果前一个元素(如果存在)不大于实际元素,则将该元素添加到输出的最后一个子列表中。如果它更大,在输出中创建一个新的子列表,并将其添加到这个新的子列表中。你知道吗
另一种解决方案:
算法
输出为
用文字解释算法:
创建带有空子列表的输出列表。枚举输入列表。如果前一个元素(如果存在)不大于实际元素,则将该元素添加到输出的最后一个子列表中。如果它更大,在输出中创建一个新的子列表,并将其添加到这个新的子列表中。你知道吗
相关问题 更多 >
编程相关推荐