python - 使用 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 适合所有人
解决方案
说得太晚了,但我终于理解并写了一个算法,谢谢@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)
推荐阅读
- java - 为什么使用 java servlet 和 apache POI 库下载的 excel 文件抱怨文件格式或扩展名?
- angular - 将变量的类型更改为 Observable 后的错误(Angular 7)
- python - 在一张图中绘制不同年份的图(datetime64)
- caching - 系统间缓存全局节点可以按第二个节点排序吗?
- html - 根据条件在 2 列上显示数据
- firebase - 为什么同一个firebase帐户的不同服务帐户有不同的私钥
- php - 我无法在 linux 上执行 php artisan serve
- angular - Typescript:处理服务调用 onInit 之间依赖关系的最佳方法
- c# - C# 和 EPPlus,将文本值从表单写入下一个可用的空行
- visual-studio - 写入存储库后,Visual Studio 未显示正确结果