有效座位假设

Valid seat assumption

我对这个功能问题有疑问:

x = [[0,0,0,0,0],[0,0,0,0,1],[0,1,0,0,0]]

函数:Book(seat)#假设座位是A5 该函数假设座位在格式 A、B 和 C 中有效。该函数需要将座位的字母部分转换为整数 A = 0,B = 1 和 C = 2。字符串数字也需要更改为"1"0, "2"1, "3"2, "4"3"5"4。这些可用于检查 x 列表列表中的椅子是否已被预订 10。如果未预订,则应将其更改为已预订,函数应 return True 否则应 return False.

我的解决方案是

a = {"A":[0,0,0,0,0], "B":[0,0,0,0,1], "C":[0,1,0,0,],}
rowIndex = ["A","B","C"]
columnIndex = [1,2,3,4,5]

def book(seat):
    row = seat[0]
    column = seat[1]
    while row in rowIndex and column in columnIndex:
       if x[row][column-1] == 0:
          return True
       else: return False

它在我预订的座位上分别输出False(座位已预订)。我认为我的代码有问题,但似乎无法解决。

您的函数代码存在一些问题:

  1. 没有定义 x 变量 — 你在
    a = {"A":[0,0,0,0,0], "B":[0,0,0,0,1], "C":[0,1,0,0,],}
    
  2. 之后
    row = seat[0]
    column = seat[1]
    
    然后测试以下值:
    while row in rowIndex and column in columnIndex:
    
    这将阻止其余代码的 any 执行,除非它是 True.
  3. 您需要在 whileinside 中遍历所有可能性需要两个 for 循环,一个嵌套在另一个循环中。 然而…
  4. 您根本不需要循环,如下图所示。
    BOOKED = 1
    x = [[0,0,0,0,0], [0,0,0,0,1], [0,1,0,0,0]]
    letter_to_index = {"A": 0, "B": 1, "C": 2}
    digit_to_index = {"1": 0, "2": 1, "3": 2, "4": 3, "5": 4}
    
    def book(seat):
        # Convert each seat character to integer.
        row = letter_to_index[seat[0]]
        col = digit_to_index[seat[1]]
    
        if x[row][col] == BOOKED:
            return False
        else:
            # Book the seat and return True
            x[row][col] = BOOKED
            return True
    
    
    if __name__ == '__main__':
        print(book('A5'))  # -> True
    
        # Try doing it again.
        print(book('A5'))  # -> False
    

这是您的代码的一个更简单的实现。您不需要使用循环。你有一本字典。您可以通过更简单的方式查找字典。

a = {"A":[0,0,0,0,0], "B":[0,0,0,0,1], "C":[0,1,0,0,],}

def book(seat):
    r,c = seat #this allows A to be r and 5 to be C

    #check if value of r in keys of a
    #also check if seat # is within length of seats for key

    if r in a and int(c) <= len(a[r]): 
        #if valid request, then check if seat already booked
        #if not, set seat to booked by setting value to 1
        #return True
        #if already booked, return False

        if a[r][int(c)-1] == 0:
            a[r][int(c)-1] = 1
            return True
        else:
            return False

    # if not a value request, send appropriate message
    else:
        return 'invalid request'

print ('A5', book('A5'))
print ('C2', book('C2'))
print ('A7', book('A7'))
print (a)

这个输出将是:

A5 True
C2 False
A7 invalid request
{'A': [0, 0, 0, 0, 1], 'B': [0, 0, 0, 0, 1], 'C': [0, 1, 0, 0]}