华为机考搭积木python
时间: 2023-07-05 12:32:00 浏览: 124
面试前的华为Python机考题.zip
5星 · 资源好评率100%
好的,以下是华为机考搭积木的 Python 代码实现:
```python
class Block:
def __init__(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth
self.area = width * depth
def build_tower(blocks):
# 按照面积从大到小排序
blocks = sorted(blocks, key=lambda x: x.area, reverse=True)
height = 0
area = 0
tower = []
for block in blocks:
if not tower or block.width < tower[-1].width and block.depth < tower[-1].depth:
tower.append(block)
height += block.height
area += block.area
return height, area
# 测试代码
blocks = [Block(3, 5, 2), Block(4, 6, 3), Block(2, 4, 1), Block(1, 3, 2)]
height, area = build_tower(blocks)
print("Height:", height)
print("Area:", area)
```
这段代码中,`Block` 类表示积木的属性,`build_tower` 函数接受积木列表作为参数,返回积木堆的高度和面积。首先按照面积从大到小排序,然后依次将积木添加到积木堆中,直到无法再添加为止。最后返回积木堆的高度和面积。
阅读全文