首页 > 解决方案 > 使用 Python 编写平铺地板的算法

问题描述

我试图做我的功课,但我做不到我研究了很多关于这个的话题,但我找不到答案,所以我需要帮助。

我们的老师想要这个;制定一个计划,用 4 × 4 英寸的黑白交替瓷砖铺设矩形浴室地板。地板尺寸(以英寸为单位)是 4 的倍数

确定输入和输出。

输入是地板尺寸(长×宽),以英寸为单位。

输出是瓷砖地板。

Step2)将问题分解为更小的任务。

一个自然的子任务是铺设一排瓷砖。如果你能解决这个问题,那么你可以通过将一排并排放置来解决问题,从一面墙开始,直到你到达对面的墙。你怎么排一排?从一面墙上的瓷砖开始。如果是白色的,就在旁边放一个黑色的。如果它是黑色的,就在它旁边放一个白色的。继续前进,直到到达对面的墙。该行将包含宽度 / 4 个图块。

Step-3) 用伪代码描述每个子任务。

假设您要平铺一个 20 × 12 英寸的区域。第一步是在西北角放置一块黑色瓷砖。

所以顺便说一句,我很抱歉,我什么都听不懂,我们的老师也没有告诉任何关于那个话题的事情。

def place_tiles( room_length, room_width, tile_dim ):
"""
Place alternating colored tiles in the specified room and return the layout
of the tiling. The length and width of the room are provided by the first two
parameters, and tile_dim provides the dimension of each tile, which we will
assume to be a square.
"""
# We can replace each row of tiles as a list. Therefore, the entire placement
# can be represented as a list of lists.
placement = []
# COMPLETE THE REST OF THE CODE BEFORE NEXT TIME

我们正在学习这本书;

Horstman and Necaise 2016 Python 适合所有人

标签: pythonfunction

解决方案


说得太晚了,但我终于理解并写了一个算法,谢谢@Micheal Butscher

def place_tiles(room_length, room_width , tile_dim):
    placement = []

    num_of_tiles_per_row = int(room_length / tile_dim)
    num_of_tiles_per_col = int(room_width / tile_dim)
    prev_tile = None

    for c in range(num_of_tiles_per_col):
        cur_row_tiles = []


        for r in range(num_of_tiles_per_row):
            if prev_tile and prev_tile == "w":
                cur_row_tiles.append("b")
                prev_tile = "b"

            else:
                cur_row_tiles.append("w")
                prev_tile = "w"
        placement.append(cur_row_tiles)
        prev_tile = cur_row_tiles[0]
    return placement

place_tiles(4,4,1)

推荐阅读