从输入导入列表
def find_peak(m: List[List[int]]) -> List[int]:
"""
Given an non-empty elevation map m, returns the cell of the
highest point in m.
Examples (note some spacing has been added for human readablity)
>>> m = [[1,2,3],
[9,8,7],
[5,4,6]]
>>> find_peak(m)
[1,0]
>>> m = [[6,2,3],
[1,8,7],
[5,4,9]]
>>> find_peak(m)
[2,2]
"""
max_location = []
for sublist in m:
max_location.append(max(sublist))
max_location = max(max_location)
for sublist in m:
if max_location in sublist:
return (m.index(max_location),sublist.index(max_location))
这实际上不起作用,因为它只返回不在列表中的数字
可以在展开的输入结构中找到最大值,然后返回指定先前找到的最大值位置的坐标:
输出:
^{pr2}$您还可以充分利用
enumerate
。首先查找具有最大数目的行(及其索引)。然后在第二行找到那个数。在在这两种情况下,您都需要为
max
函数提供一个键,以便它考虑值(而不是索引):输出
^{pr2}$我认为当你考虑迭代索引而不是列表上的项目时,它更容易:
相关问题 更多 >
编程相关推荐