I've been trying to code a seat booking program which does the following:
Everything works as it should however I'm struggling with retrieving the seat numbers of the free seats. Any ideas with my current method? Much appreciated!
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 structure
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
Here is one alternate way to go about this:
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
Your specification (as written) does not require us to tell the user how many seats actually are available in the row if it is not enough for their needs.
(Using line E
in this case)
This
>>> groups = [(k, len(list(g))) for k, g in groupby(line)]
>>> groups
[('1', 1), ('0', 1), ('1', 1), ('0', 7)]
Gives you the mapping of the number of occupied/free consecutive rows
Then,
>>> [i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq]
[3]
Gives you all the indices of the blocks that have sufficient space
Or, blockIndex = next((i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq), None)
returns the first matching block or None
Then,
>>> sum(blockSize for _, blockSize in groups[:blockIndex])
3
Gives you the total number of seat before your large enough block.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.