如何实现基于邻座状态的影院座位填充函数并解决IndexError报错
报错原因与修复方案
错误点梳理
- 边界判断越界:
neighbourcounter函数中的行索引合法范围校验错误,影院行索引从0开始到numberrows-1结束,原代码判断v<=numberrows,当v等于numberrows时访问不存在的行,触发索引越界。 - 邻座统计逻辑不符合需求:业务规则需要统计指定位置周边**已占用座位(#)**的数量,原代码统计的是空座位(L)的数量,完全不匹配后续判断逻辑。
- 迭代逻辑变量混淆:迭代代码中的
eachseat是列索引值,原代码直接判断eachseat == '.',没有从原影院列表中读取对应位置的座位状态,判断逻辑完全错误。 - 状态存储结构错误:原影院座位是二维嵌套列表,原代码将新状态存为一维列表,结构不匹配无法进行后续迭代。
- 状态更新逻辑错误:座位状态更新需要全部基于上一轮的完整状态,不能边遍历边修改原列表,否则前面修改的结果会影响后续座位的判断结果。
- 变量名大小写不一致:代码中混用
cinemahall和Cinemahall,可能触发未定义变量报错。
修复后的完整实现
1. 邻座统计函数修复
numberrows = len(Cinemahall) seatsperrow = len(Cinemahall[0]) - 1 # 排除末尾的换行符 def neighbourcounter(cinemahall, row, seating): occupied = 0 # 遍历周边8个方向 for v in range(row-1, row+2): for h in range(seating-1, seating+2): # 跳过自身位置 if v == row and h == seating: continue # 校验边界合法性 if 0 <= v < numberrows and 0 <= h < seatsperrow: # 统计已占用的座位数 if cinemahall[v][h] == '#': occupied += 1 return occupied
2. 迭代更新逻辑修复
def update_cinema(Cinemahall): while True: # 初始化新的二维状态列表 new_hall = [] changed = False for eachrow in range(numberrows): new_row = [] for eachseat in range(seatsperrow): current_status = Cinemahall[eachrow][eachseat] # 无座位直接保留 if current_status == '.': new_row.append('.') continue # 统计周边已占用座位数 neighbor_occupied = neighbourcounter(Cinemahall, eachrow, eachseat) # 规则1:空座位周边无已占用座位,变为已占用 if current_status == 'L' and neighbor_occupied == 0: new_row.append('#') changed = True # 规则2:已占用座位周边>=4个已占用,变为空 elif current_status == '#' and neighbor_occupied >= 4: new_row.append('L') changed = True # 其他情况状态不变 else: new_row.append(current_status) # 补回每行末尾的换行符 new_row.append('\n') new_hall.append(new_row) # 状态不再变化时终止迭代 if not changed: return new_hall # 用新状态替换旧状态进行下一轮迭代 Cinemahall = new_hall # 调用方式 final_cinema = update_cinema(Cinemahall)
内容的提问来源于stack exchange,提问作者ravenb
相关产品推荐
相关产品推荐

