You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现影院座位文本文件的动态预订修改功能?

影院座位预订代码完善方案

需求说明

现有模拟影院座位的文本文件,规则如下:

  • O:可用座位
  • X:已预订座位
  • #:墙体
    需完善Python代码,实现以下功能:
  1. 接受类似A1,B14格式的座位输入
  2. 将对应可用座位(O)改为已预订(X)并更新文件
  3. 对已预订座位(X)、墙体(#)给出对应提示

原始座位文件内容

A,OXXX#XXXX#XXOO
B,OOXX#XXXX#XXOO
C,OXXX#XXXO#OXXO
D,OOXX#XXXX#XXOO
E,OOOX#OXXO#XXOO
F,##XX#OXXX#XO##

现有待完善代码

bookSeat = input('Enter seats to book: ').split(',')
    for booking in bookSeat:
        bookRow = booking[0]
        bookColumn = booking[1:]
        availableSeats = seatingPlan[bookRow][int(bookColumn)-1]
            if availableSeats == 'O':
                f = open('Monkey Goes East-202209081430.txt','w')
                #idk whats the next step
            elif availableSeats == 'X':
                print("Seats are already booked!')
            elif availableSeats == '#':
                print('These seats are unavailable')

完善后的可运行代码

# 定义座位文件名
SEAT_FILE = 'Monkey Goes East-202209081430.txt'

# 读取座位文件并转换为字典(键为行号A-F,值为座位字符串)
seating_plan = {}
with open(SEAT_FILE, 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        row, seats = line.split(',', 1)
        seating_plan[row] = seats

# 获取用户输入的座位列表
book_seats = input('Enter seats to book: ').strip().split(',')

# 处理每个预订请求
for booking in book_seats:
    booking = booking.strip()
    if not booking:
        continue
    # 拆分行标识和列号
    book_row = booking[0].upper()
    try:
        book_col = int(booking[1:]) - 1  # 转换为0索引
    except ValueError:
        print(f"无效座位格式:{booking}")
        continue
    
    # 校验行是否存在
    if book_row not in seating_plan:
        print(f"不存在的行:{book_row}")
        continue
    seats = seating_plan[book_row]
    
    # 校验列号是否越界
    if book_col < 0 or book_col >= len(seats):
        print(f"座位{booking}不存在")
        continue
    
    # 处理座位状态
    seat_status = seats[book_col]
    if seat_status == 'O':
        # 字符串不可直接修改,转列表修改后转回字符串
        seats_list = list(seats)
        seats_list[book_col] = 'X'
        seating_plan[book_row] = ''.join(seats_list)
        print(f"座位{booking}已成功预订")
    elif seat_status == 'X':
        print(f"座位{booking}已被预订")
    elif seat_status == '#':
        print(f"座位{booking}是墙体,不可预订")

# 将修改后的座位计划写回文件
with open(SEAT_FILE, 'w') as f:
    for row in sorted(seating_plan.keys()):
        f.write(f"{row},{seating_plan[row]}\n")

效果验证

输入A1,B14后,文件内容更新为:

A,XXXX#XXXX#XXOO
B,OOXX#XXXX#XXOX
C,OXXX#XXXO#OXXO
D,OOXX#XXXX#XXOO
E,OOOX#OXXO#XXOO
F,##XX#OXXX#XO##

内容的提问来源于stack exchange,提问作者Wenyong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:15:42