I want it to give me error when is not 0 or 1

#!/usr/bin/python

def 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'])

Raises ValueError if not every state is specified, the switches and locks are not 0 or 1 or the gs is not one of ('P' 'R', 'N', '2', '3' 'D')

1 answer

  • answered 2018-11-08 08:32 glglgl

    I would do

    if any((i != 0 and i != 1) for i in state):
      raise ValueError("Error: A state is not specified or invalid entry")
    

    This is short and concise.

    It can be even changed to

    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")
    

    bit I am not sure if that is better performance- or readability-wise.