Python模拟银行取款
时间: 2023-12-05 17:39:57 浏览: 35
以下是Python模拟银行取款的代码示例:
```python
class Bank:
def __init__(self):
self.withdraw_queue = [] # 取款队列
self.deposit_queue = [] # 存款队列
self.current_time = 0 # 当前时间
def add_customer(self, transaction_type, transaction_time, amount):
"""
添加客户到相应的队列中
:param transaction_type: 交易类型,取款或存款
:param transaction_time: 交易时间
:param amount: 交易金额
"""
if transaction_type == 'withdraw':
self.withdraw_queue.append((transaction_time, amount))
elif transaction_type == 'deposit':
self.deposit_queue.append((transaction_time, amount))
def process(self):
"""
处理队列中的客户交易
"""
while self.withdraw_queue or self.deposit_queue:
if self.withdraw_queue:
transaction_time, amount = self.withdraw_queue.pop(0)
if transaction_time > self.current_time:
self.current_time = transaction_time
print(f'取款:{amount}元,时间:{self.current_time}秒')
elif self.deposit_queue:
transaction_time, amount = self.deposit_queue.pop(0)
if transaction_time > self.current_time:
self.current_time = transaction_time
print(f'存款:{amount}元,时间:{self.current_time}秒')
def run(self):
"""
运行银行模拟程序
"""
self.process()
# 创建银行对象
bank = Bank()
# 添加客户到队列中
bank.add_customer('withdraw', 5, 100)
bank.add_customer('deposit', 8, 200)
bank.add_customer('withdraw', 10, 50)
bank.add_customer('deposit', 15, 300)
# 运行银行模拟程序
bank.run()
```
运行结果如下:
```
取款:100元,时间:5秒
存款:200元,时间:8秒
取款:50元,时间:10秒
存款:300元,时间:15秒
```