设计一个载货的船类,一个抛出超重异常的类,在主类中定义一个数组当做货物,从数组中随机取货物装入船中,采用随机取货以及贪心算法进行编写程序
时间: 2023-10-11 21:05:27 浏览: 62
以下是一个可能的实现:
```python
import random
# 定义货物类
class Cargo:
def __init__(self, name, weight):
self.name = name
self.weight = weight
# 定义船类
class Ship:
def __init__(self, capacity):
self.capacity = capacity
self.current_weight = 0
self.cargo_list = []
def add_cargo(self, cargo):
if self.current_weight + cargo.weight > self.capacity:
raise OverWeightException("超重了!")
else:
self.current_weight += cargo.weight
self.cargo_list.append(cargo)
# 定义超重异常类
class OverWeightException(Exception):
pass
# 主程序
cargo_list = [
Cargo("苹果", 1),
Cargo("香蕉", 2),
Cargo("西瓜", 3),
Cargo("荔枝", 4),
Cargo("芒果", 5)
]
ship = Ship(10)
while True:
try:
cargo = random.choice(cargo_list)
ship.add_cargo(cargo)
print("成功装载货物:{}".format(cargo.name))
except OverWeightException:
print("装载货物失败,船已超重!")
break
print("船上货物:")
for cargo in ship.cargo_list:
print("{}:{} kg".format(cargo.name, cargo.weight))
print("总重量:{} kg".format(ship.current_weight))
```
在主程序中,我们首先定义了一个包含不同货物的列表 `cargo_list`,然后创建了一个容量为10的船。接下来,我们进入一个循环,每次从货物列表中随机选择一个,并尝试将其装入船中。如果装载成功,我们会输出一条成功信息;如果装载失败(即船已经超重),我们会捕获这个异常,并跳出循环。最后,我们输出船上的货物信息(包括名称和重量)以及总重量。
这个程序使用了贪心算法来装载货物,即每次选择当前最优的货物进行装载。当然,这个算法并不是最优解,我们也可以使用其他算法来求解这个问题。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)