递归实现排队找零问题
时间: 2023-06-29 11:16:27 浏览: 68
排队找零问题可以使用递归来实现。以下是一个简单的示例代码,可以实现排队找零的模拟:
```python
def make_change(customers):
if len(customers) == 0:
return
customer = customers[0]
change = customer.paid - customer.price
print(f"{customer.name} 支付了 {customer.paid} 元,需要找零 {change} 元。")
make_change(customers[1:])
```
这段代码中,`make_change` 函数接受一个参数 `customers`,表示所有的顾客。当 `customers` 为空时,递归结束。否则,取出第一个顾客,计算找零并输出结果,然后递归调用 `make_change` 函数处理剩余的顾客。
你可以调用 `make_change` 函数来模拟排队找零的过程。例如,如果你有一组顾客和商品,你可以这样调用:
```python
customers = [
Customer("张三", 100, 50),
Customer("李四", 200, 80),
Customer("王五", 150, 100),
Customer("赵六", 120, 60),
Customer("钱七", 80, 50)
]
make_change(customers)
```
这将输出以下内容:
```
张三 支付了 100 元,需要找零 50 元。
李四 支付了 200 元,需要找零 120 元。
王五 支付了 150 元,需要找零 50 元。
赵六 支付了 120 元,需要找零 60 元。
钱七 支付了 80 元,需要找零 30 元。
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)