Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 矩阵填充算法_Algorithm_Python 3.x_Matrix - Fatal编程技术网

Algorithm 矩阵填充算法

Algorithm 矩阵填充算法,algorithm,python-3.x,matrix,Algorithm,Python 3.x,Matrix,我需要一些帮助来解决这个问题。我需要写一个函数来填满剧院的座位。 例如,我们有一个剧院: theater = [ [1, 1, 1, 0], # 1 row [1, 0, 1, 0], # 2 row [0, 0, 0, 0], # 3 row ] 我们得从一排开始就把座位占满。 首先,我们必须用最少的座位填满这一排。 如果我们有两排座位数量相等的座位,我们就要填满排数较低的那一排,如果第2排的座位数量与第3排的座位数量相

我需要一些帮助来解决这个问题。我需要写一个函数来填满剧院的座位。 例如,我们有一个剧院:

theater = [ [1, 1, 1, 0], # 1 row

            [1, 0, 1, 0], # 2 row

            [0, 0, 0, 0], # 3 row
          ]
我们得从一排开始就把座位占满。 首先,我们必须用最少的座位填满这一排。 如果我们有两排座位数量相等的座位,我们就要填满排数较低的那一排,如果第2排的座位数量与第3排的座位数量相同,我们就必须填满第2排。 最后,我们必须坐满,直到所有的座位都坐满为止。 空座位为0,满座位为-1。 结果必须是元组列表-第一个元素是行的编号,第二个元素是列的编号-2,1-例如,行2和列1

例如:

theater = [ [1, 1, 1],
           [1, 0, 0],
           [1, 0, 0],
           [1, 1, 0] ]

expected = [(4, 3), (2, 2), (2, 3), (3, 2), (3, 3)]

没有人会告诉你非常初步的事情

不过我可以给你提供正确的路线。查看如何定义二维数组。为行和列创建两个变量。从0,0开始行和列。继续增加列数,直到它等于行中的最大座位数,将其设置为零并增加行数

如何在python中定义二维数组

首先你要确定剧院里的空座位 然后反转空列表 然后过滤空位列表检查上排空位长度是否等于 当前行空座位置与上一行空座位置相同,然后将其添加到临时列表中,并对下一行重复此操作 然后你得到你的最终结果 通过此程序,此代码:

theater = [ [1, 1, 1],
           [1, 0, 0],
           [1, 0, 0],
           [1, 1, 0] ]

empty = [[(i+1 ,j+1) for j in range(len(theater[i])) if theater[i][j] == 0]  for i in range(len(theater)) ]
empty = empty[::-1]
#print empty

final_result = []
for i in range(len(empty)):
    result = []
    if i != len(empty)-1 and empty[i] not in final_result:
        j = i+1
        while len(empty[i]) == len(empty[j]):
            flag = False
            for first, second in zip(empty[i], empty[j]):
                if first[1] != second[1]:
                    flag = True
                    break
            if flag:
                break
            else:
                result.insert(0, empty[j])
                j = j+1
                if j == len(empty):
                    break


        for rr in result:
            final_result.append(rr)
        final_result.append(empty[i])

    if empty[i] not in final_result:
        final_result.append(reversed(empty[i]))


expected = []
for i in final_result:
    expected.extend(i)

print expected
输出:

[(4, 3), (2, 2), (2, 3), (3, 2), (3, 3)]

到目前为止你做了什么?在这里显示您的代码。代码中有什么特别的问题吗?我不知道从哪里开始?我正在学习Python大约一个月,这个问题对我来说有点难。有什么想法吗?我真的不知道该怎么办。请帮帮我。海伊@croorc,检查我的答案。