Home > front end >  Check if the number of slots is > 0 before picking a date and an hour?
Check if the number of slots is > 0 before picking a date and an hour?

Time:12-30

I am building a vaccination appointment program that automatically assigns a slot to the user. This builds the table and saves it into a CSV file:

import pandas

start_date = '1/1/2022'
end_date = '31/12/2022'
list_of_date = pandas.date_range(start=start_date, end=end_date)
df = pandas.DataFrame(list_of_date)
df.columns = ['Date/Time']
df['8:00'] = 100
df['9:00'] = 100
df['10:00'] = 100
df['11:00'] = 100
df['12:00'] = 100
df['13:00'] = 100
df['14:00'] = 100
df['15:00'] = 100
df['16:00'] = 100
df['17:00'] = 100
df.to_csv(r'C:\Users\Ric\PycharmProjects\pythonProject\new.csv')

And this code randomly pick a date and an hour from that date in the CSV table we just created:

import pandas
import random
from random import randrange
#randrange randomly picks an index for date and time for the user
random_date = randrange(365)
random_hour = randrange(10)
list = ["8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"]
hour = random.choice(list)
df = pandas.read_csv('new.csv')
date=df.iloc[random_date][0]
# 1 is substracted from that cell as 1 slot will be assigned to the user
df.loc[random_date, hour] -= 1
df.to_csv(r'C:\Users\Ric\PycharmProjects\pythonProject\new.csv',index=False)
print(date)
print(hour)

I need help with making the program check if the random hour it chose on that date has vacant slots. I can manage the while loops that are needed if the number of vacant slots is 0. And no, I have not tried much because I have no clue of how to do this.

P.S. If you're going to try running the code, please remember to change the save and read location.

CodePudding user response:

import pandas
import random
from random import randrange

# randrange randomly picks an index for date and time for the user
random_date = randrange(365)
# random_hour = randrange(10) #consider removing this line since it's not used
lista = [# consider avoid using Python preserved names
    "8:00",
    "9:00",
    "10:00",
    "11:00",
    "12:00",
    "13:00",
    "14:00",
    "15:00",
    "16:00",
    "17:00",
]
hour = random.choice(lista)
df = pandas.read_csv("new.csv")
date = df.iloc[random_date][0]
# 1 is substracted from that cell as 1 slot will be assigned to the user
if df.loc[random_date, hour] > 0:#here is what you asked for
    df.loc[random_date, hour] -= 1
else:
    print(f"No Vacant Slots in {random_date}, {hour}")
df.to_csv(r"new.csv", index=False)
print(date)
print(hour)

CodePudding user response:

Here is how I would do it. I've also cleaned it up a bit.

import random

import pandas as pd

start_date, end_date = '1/1/2022', '31/12/2022'
hours = [f'{hour}:00' for hour in range(8, 18)]

df = pd.DataFrame(
    data=pd.date_range(start_date, end_date),
    columns=['Date/Time']
)

for hour in hours:
    df[hour] = 100

# 1000 simulations
for _ in range(1000):
    random_date, random_hour = random.randrange(365), random.choice(hours)
    
    # Check if slot has vacant slot
    if df.at[random_date, random_hour] > 0:
        df.at[random_date, random_hour] -= 1
    else:
        # Pass here, but you can add whatever logic you want
        # for instance you could give it the next free slot in the same day
        pass

print(df.describe())

CodePudding user response:

Here's another alternative. I'm not sure you really need the very large and slow-to-load pandas module for this. This does it with plan Python structures. I tried to run the simulation until it got a failure, but with 365,000 open slots, and flushing the database to disk each time, it takes too long. I changed the 100 to 8, just to see it find a dup in reasonable time.

import csv
import datetime
import random

def create():
    start = datetime.date( 2022, 1, 1 )
    oneday = datetime.timedelta(days=1)
    headers = ["date"]   [f"{i}:00" for i in range(8,18)]
    data = []
    for _ in range(365):
        data.append( [start.strftime("%Y-%m-%d")]   [8]*10 ) # not 100
        start  = oneday
    write( headers, data )

def write(headers, rows):
    fcsv = csv.writer(open('data.csv','w',newline=''))
    fcsv.writerow( headers )
    fcsv.writerows( rows )

def read():
    days = []
    headers = []
    for row in csv.reader(open('data.csv')):
        if not headers:
            headers = row
        else:
            days.append( [row[0]]   list(map(int,row[1:])))
    return headers, days

def choose( headers, days ):
    random_date = random.randrange(365)
    random_hour = random.randrange(len(headers)-1) 1

    choice = days[random_date][0]   " "   headers[random_hour]
    print( "Chose", choice )
    if days[random_date][random_hour]:
        days[random_date][random_hour] -= 1
        write(headers,days)
        return choice
    else:
        print("Randomly chosen slot is full.")
        return None

create()
data = read()
while choose( *data ):
    pass
  • Related