在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
‘’’
这道题的思路就是从右上角开始寻找,
逐步缩减行和列。
如果不用numpy的话,就要输出参数就要包括行数和列数。
用numpy的话,有个bug,如果lis是一维数组,m,n = np.shape(lis)就会报错,
因为如果lis是一维的话,shape只会返回一个参数。
‘’’
import numpy as np
#解决了numpy的bug,如果lis是一维数组,也不会报错
def Find(lis,num):
if not isinstance(lis,list)==1 or len(lis) == 0:
print(“list列表为空”)
return False
if len(np.shape(lis)) == 1:
m=0
n=np.shape(lis)[0]
else:
m,n = np.shape(lis)
row = 0
col = n-1
while row = 0:
if lis[row][col] == num:
return True
elif lis[row][col] < num:
row += 1
else:
col -= 1
return False
#不用numpy,如果是一维数组会报错
def find(lis,num):
if not isinstance(lis,list)==1 or len(lis) == 0:
print(“list列表为空”)
return False
m = len(lis)-1
n = len(lis[0])-1
row = 0
col = n-1
while row = 0:
if lis[row][col] == num:
return True
elif lis[row][col] < num:
row += 1
else:
col -= 1
return False
if name ==‘main’ :
lis = [[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]]
lis1 = [1,2]
# print(Find(lis, 9.5))
print(find(lis,1))