剪刀石头布游戏功能优化:限制同一形状输入不超过2次
剪刀石头布游戏getHandOfShapes函数修复与功能实现
原代码存在几个问题:全局变量会导致多次调用数据残留、循环内提前return导致只收集一次输入、缺少重复形状次数限制。以下是修复并实现需求的代码:
def getHandOfShapes(size): if size < 3: print("Please enter a size of at least 3") return [] shapes = [] for i in range(size): while True: shape = input(f"Shape {i+1}: please select a shape: ").strip().upper() # 检查当前形状是否已出现2次以上 if shapes.count(shape) >= 2: print(f"Cannot have more than 2 {shape}!!") else: shapes.append(shape) break return shapes # 测试示例 print(getHandOfShapes(4))
关键改动说明
- 将
shapes列表移至函数内部,避免多次调用时的全局数据污染 - 对每一轮输入使用
while循环校验:如果当前形状已出现2次,就重复提示输入,直到符合要求 - 移除了原代码中循环内的
return,确保完成size次有效输入后再返回结果 - 增加
.strip()处理输入的前后空格,提升输入容错性
测试输出示例
Shape 1: please select a shape: scissors Shape 2: please select a shape: SCISSORS Shape 3: please select a shape: scissors Cannot have more than 2 SCISSORS!! Shape 3: please select a shape: Paper Shape 4: please select a shape: Stone ['SCISSORS', 'SCISSORS', 'PAPER', 'STONE']
内容的提问来源于stack exchange,提问作者Stainler
相关产品推荐
相关产品推荐

