我有一项必须完成才能上学的练习,但我有点卡住了。 我必须编写一个函数来告诉你照片上是否有一张脸,通过照片我们可以想象一个二维列表,一个由更多列表组成的列表来创建一个二维对象。人脸由 2x2 正方形表示,其中包含单词 face,这些字母可以随机排列。如下图一、二所示:
也可以有更多的脸,只要 face 这个词在整个 2Dlist 中至少出现一次,它就应该返回 True。
问题是字母不能在一行或一列中,如图 III 所示。我真的不知道如何制定一个条件来消除这种情况。到目前为止,我知道如何找出所有字母是否都在该 2D 列表中,并且我消除了只有一行或一列的可能性,如图 IV 所示。和 V..
这是我目前所拥有的:
def is_face_on_photo(photo):
list2D = photo
faces = ['f','a','c','e']
newlist = []
for list in list2D:
for letter in list:
newlist.append(letter)
if 'f' in newlist and 'a' in newlist and 'c' in newlist and 'e' in newlist and (faces not in list2D) and (len(list2D) >= 2) and (len(list2D[0]) >= 2):
print True
else:
print False
pass
我是 python 的新手,所以如果能得到任何帮助,我将不胜感激 :) 非常感谢
请您参考如下方法:
逐个元素搜索每一行,然后是下一行,依此类推,从左到右,再向下,直到找到 F、A、C 或 E。
当您这样做时,由于您是从左到右和从上到下检查,您可以假设您已经找到了潜在“FACE”的左上角。所以检查右边的字母,下面的字母,右下的字母是否满足剩下的FACE。
如果是这样,您就完成了。如果没有,请继续。
编辑:这是一个有点冗长的版本。我还没有测试过,但这是我的想法。
def is_face_on_photo(photo):
found = False
for row,photo_row in enumerate(photo):
for col,letter in enumerate(photo_row):
if (letter in "face") and col + 1 < len(photo_row) and row + 1 < len(photo):
found = True # Until proven otherwise
num_found = {"f":0, "a":0, "c":0, "e":0}
right_letter = photo_row[col + 1]
below_letter = photo[row + 1][col]
below_right_letter = photo[row + 1][col + 1]
letters = [letter, right_letter, below_letter, below_right_letter]
# Could replace with something like defaultdict
for let in letters:
if let in num_found:
num_found[let] += 1
# Would need to change this slightly if the letters of "face" had
# any repetitions, like two "a"s or something
for let in "face":
if num_found[let] == 0:
found = False
break
if found:
break
if found:
break
return found
