#!/usr/bin/pythondef open_doors(state): (ld, rd, li, ri, lo, ro, cl, ml, gs) = state if not(ld == 0 or rd == 0 or li == 0 or ri == 0 and lo == 0 or ro == 0 or cl == 0 or ml == 0): raise ValueError("Error: A state is not specified or invalid entry") if not(ld == 1 or rd == 1 or li == 1 or ri == 1 and lo == 1 or ro == 1 or cl == 1 or ml == 1): raise ValueError("Error: A state is not specified or invalid entry") leftDoor = (ld or li or lo) rightDoor = (rd or ri or ro) if (li and cl): leftDoor = 0 if (ri and cl): rightDoor = 0 if leftDoor and rightDoor and not ml and gs == 'P': print("left door and right door open") elif leftDoor and not ml and gs == 'P': print("open left door") elif rightDoor and not ml and gs == 'P': print("open right door") else: print("both doors stay closed") open_doors([0,0,1,6,0,0,1,0,'2'])如果未指定每个状态,开关和锁不是 0 或 1 或 gs 不是 ('P' 'R', 'N', '2', '3' 'D') 之一,则引发 ValueError
1 回答
慕容森
TA贡献1853条经验 获得超18个赞
我会做
if any((i != 0 and i != 1) for i in state):
raise ValueError("Error: A state is not specified or invalid entry")
这是简短而简洁的。
它甚至可以更改为
valid = set((0, 1))
if any(i not in valid for i in state):
raise ValueError("Error: A state is not specified or invalid entry")
我不确定这是否是更好的性能或可读性。
添加回答
举报
0/150
提交
取消