使用Python函数get_shape_list()生成随机形状列表
发布时间:2024-01-09 16:18:15
get_shape_list()函数可以用来生成随机形状的列表。这个函数接受三个参数:num_shapes,表示要生成的形状数量;min_value和max_value,表示形状的最小和最大值。
下面是get_shape_list()函数的实现:
import random
def get_shape_list(num_shapes, min_value, max_value):
shape_list = []
shapes = ["circle", "rectangle", "triangle", "square"]
for _ in range(num_shapes):
shape = random.choice(shapes)
if shape == "circle":
radius = random.randint(min_value, max_value)
shape_list.append({"type": shape, "radius": radius})
elif shape == "rectangle":
length = random.randint(min_value, max_value)
width = random.randint(min_value, max_value)
shape_list.append({"type": shape, "length": length, "width": width})
elif shape == "triangle":
base = random.randint(min_value, max_value)
height = random.randint(min_value, max_value)
shape_list.append({"type": shape, "base": base, "height": height})
elif shape == "square":
side = random.randint(min_value, max_value)
shape_list.append({"type": shape, "side": side})
return shape_list
使用例子:
shapes = get_shape_list(3, 1, 10)
for shape in shapes:
if shape["type"] == "circle":
print(f"Circle with radius {shape['radius']}")
elif shape["type"] == "rectangle":
print(f"Rectangle with length {shape['length']} and width {shape['width']}")
elif shape["type"] == "triangle":
print(f"Triangle with base {shape['base']} and height {shape['height']}")
elif shape["type"] == "square":
print(f"Square with side {shape['side']}")
这个例子将生成3个随机形状,并根据形状类型打印相应信息。形状类型包括:圆形(Circle)、矩形(Rectangle)、三角形(Triangle)和正方形(Square)。形状的具体信息通过字典表示,每个形状类型有不同的属性,比如圆形有半径(radius)、矩形有长度(length)和宽度(width)、三角形有底边(base)和高度(height)、正方形有边长(side)。
在这个例子中,get_shape_list()函数生成的形状列表示为:
[
{"type": "circle", "radius": 5},
{"type": "rectangle", "length": 7, "width": 3},
{"type": "triangle", "base": 4, "height": 9}
]
根据生成的形状列表,打印出的结果为:
Circle with radius 5 Rectangle with length 7 and width 3 Triangle with base 4 and height 9
可以看到,根据形状类型可以轻松从形状列表中获取到相应的形状信息,并进行相应的处理。这样的设计使得生成随机形状列表更加方便和灵活。
