如何定义一个函数来检查给定的布尔列表是否创建了一个正方形

时间:2016-03-28 01:18:56

标签: python python-3.x

我在项目的这一部分遇到了麻烦:

  

is_square(board):将董事会列为布尔列表,请检查是否存在   表示具有相同行数和列数的方形板。如果   这些行并不都具有相同数量的项目,或者如果是   行数与列数不匹配,此函数   返回False。空板是方形的。

     
      
  • 假设board是布尔列表的列表。

  •   
  • is_square([[True,False,False],[False,False,False],[True,False,False]])→True

  •   
  • is_square([[True,False,False],[False,False,False]])→错误#2行x 3列

  •   
  • is_square([[True],[False,False],[True,False,False]])→错误

  •   

有人可以帮我写一个简单的答案吗?

1 个答案:

答案 0 :(得分:2)

这是一个非常简单的尝试:

def is_square(o):
    # If o is empty, it's a square - that takes care of the True
    # Otherwise, ensure that each of the elements inside o
    # contains the same number of elements as o itself.
    # To do that you just need to compare the length of each element with the length of o
    total_length = len(o)
    return all(len(elem) == total_length for elem in o)

# A somewhat more verbose equivalent would be as follows:
def is_square(o):
    total_length = len(o)
    for elem in o:
        # If there's any sublist that has a different length from the total, return False and we're done
        if len(elem) != total_length:
            return False
    # Empty lists and anything that made past that loop must be a square
    return True

o1 = [[True,False,False],[False,False,False],[True,False,False]]
o2 = [[True,False,False],[False,False,False]]
o3 = [[True],[False,False],[True,False,False]]

for o in o1, o2, o3:
    print(is_square(o))