【问题标题】:Retrieving list item values检索列表项值
【发布时间】:2014-04-25 18:50:27
【问题描述】:

我一直在尝试编写一个座位预订程序,它执行以下操作:

  • 接受用户输入(行、座位数)
  • 根据上述输入检查外部 CSV 文件中的可用席位。
  • 返回空闲座位的数量(如果有)并且座位号告诉用户该行没有足够的空间。

一切正常,但是我正在努力检索免费座位的座位号。我目前的方法有什么想法吗?非常感谢!

import csv
from itertools import groupby

LargeBlock = 0

SpacesReq = int(input("How many spaces do you require? (8 Max.) "))
while SpacesReq > 8:
    print("Invalid amount.")
    break
SectionReq = input("What row would you like to check between A-E? (Uppercase required) ")

with open('data.csv', 'rt') as file:

    open_f = csv.reader(file,  delimiter=',')

    for line in open_f:
        if line[10] == SectionReq:

            LargeBlock = max(sum(1 for _ in g) for k, g in groupby(line) if k == '0')

            if SpacesReq > LargeBlock:
                print('There are only ', LargeBlock, ' seats together, available on row ',SectionReq,'.')
            else:
                print('There is room for your booking of ',SpacesReq,' seats on row ',SectionReq,'.')
            break

CSV 结构

1   0   1   0   0   0   0   0   0   0   E
0   0   0   0   0   0   0   0   0   0   D
0   0   0   0   0   1   0   0   0   0   C
0   0   0   0   0   0   0   0   1   0   B
0   0   0   0   0   1   1   1   1   1   A

【问题讨论】:

  • 这里有一个权衡 - 您可以在计算是否有足够的座位时收集座位位置(在这种情况下,如果没有足够的座位,您会“浪费”位置的努力座位),或者一旦你知道有足够的位置,你就可以找到位置(当有足够的座位时,你要做双倍的工作)。

标签: python python-3.x


【解决方案1】:

这是解决此问题的另一种方法:

for line in open_f:
        if line[10] == SectionReq:

            blockfound = "".join([str(e) for e in line[:-1]]).find("0"*SeatsReq)

            if blockfound is not -1:
                print('There are not enough seats together, available on row ',SectionReq,'.')
            else:
                print('There is room for your booking of ',SpacesReq,' seats on row ',SectionReq,', in seats ',str(blockfound),' through ',str(SeatsReq+blockfound),'.')
            break

如果不足以满足他们的需要,您的规范(如书面)不要求我们告诉用户该行实际可用的座位数。

【讨论】:

    【解决方案2】:

    (在这种情况下使用行E

    这个

    >>> groups = [(k, len(list(g))) for k, g in groupby(line)]
    >>> groups
    [('1', 1), ('0', 1), ('1', 1), ('0', 7)]
    

    为您提供占用/空闲连续行数的映射

    那么,

    >>> [i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq]
    [3]
    

    为您提供具有足够空间的块的所有索引

    或者,blockIndex = next((i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq), None) 返回第一个匹配块或None

    那么,

    >>> sum(blockSize for _, blockSize in groups[:blockIndex])
    3
    

    在足够大的街区之前为您提供座位总数。

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2012-08-21
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      相关资源
      最近更新 更多