通过使用 Python 列表,我们可以模拟火车购票系统,跟踪可用席位并管理乘客的购票和退票请求:创建一个表示席位可用性的布尔型列表。购票时,找到第一个可用席位并将其标记为已售出。退票时,将指定的席位标记为可用。使用 count() 方法计算剩余可用席位数。

用 Python 列表模拟火车购票
通过模拟火车购票系统,我们可以用 Python 列表来有效跟踪和管理可用席位。如下所示,我们可以创建一个名为 seats 的列表来表示火车上的席位:
<code class="python">seats = [True] * 100 # 创建 100 个可用席位</code>
在该列表中,每个元素表示一个席位,True 表示可用,False 表示已售出。
购票
立即学习“Python免费学习笔记(深入)”;
当乘客购买火车票时,我们需要更新 seats 列表以反映席位状态。我们可以使用 index() 方法找到第一个可用的席位,然后将其标记为已售出:
<code class="python">def buy_ticket():
seat_index = seats.index(True)
seats[seat_index] = False</code>退票
当乘客退票时,我们需要将 seats 列表中相应的席位标记为可用:
<code class="python">def return_ticket(seat_index):
if seats[seat_index] == False:
seats[seat_index] = True</code>查询可用席位
我们可以使用 count() 方法轻松地计算剩余可用席位数:
<code class="python">def get_available_seats():
return seats.count(True)</code>完整代码
以下是模拟火车购票系统的完整 Python 代码:
<code class="python">seats = [True] * 100
def buy_ticket():
seat_index = seats.index(True)
seats[seat_index] = False
def return_ticket(seat_index):
if seats[seat_index] == False:
seats[seat_index] = True
def get_available_seats():
return seats.count(True)
# 示例用法
buy_ticket()
buy_ticket()
return_ticket(1)
available_seats = get_available_seats()</code>通过使用 Python 列表,我们可以轻松地模拟火车购票系统,跟踪可用席位并管理乘客的购票和退票请求。
以上就是python列表模拟火车购票的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号