I am making an exam schedule generator in python and I need my algorithm to work like this:
I give it a date and from that date it has to run 6 days ago, if there is a Saturday or Sunday it must run one more day, so far I have this:
from datetime import date,timedelta
fecha_final = date(2019, 1, 15)
fecha_inicial = fecha_final - timedelta(days=6)
i = 1
fecha_nueva = fecha_inicial
for i in range(i < 6):
if fecha_nueva.weekday() == 5:
print("No hay examen el: " + fecha_nueva)
fecha_nueva = fecha_inicial + timedelta(days=i)
if fecha_nueva.weekday() == 6:
print("No hay examen el: " + fecha_nueva)
fecha_nueva = fecha_inicial + timedelta(days=i)
else:
i +=1
print("final")
However, it cannot detect when it is Saturday or Sunday
UPDATE:
I tried to implement it in the following way, however it still doesn't work for me :/
from datetime import date,timedelta
fecha_final = date(2019, 1, 15)
i = 1
while i < 7:
fecha_nueva = fecha_final - timedelta(days=1)
if fecha_nueva.weekday() == 5:
print("No hay examen el: " + str(fecha_nueva))
elif fecha_nueva.weekday() == 6:
print("No hay examen el: " + str(fecha_nueva))
else:
i+=1
If it were just a matter of getting the start date from the end date, so that there are six business days in between, it would be as simple as subtracting 8 days from the end date (since you will always find at least one weekend in the middle), unless the end date is Monday, in which case you have to subtract 10 days (because you will catch two weekends in between).
Once you have the start date, you go in a loop from this date to the end, printing each day if there is an exam or not:
It would come out in this case:
For a more generic case in which you could have other holidays, or the number of days instead of 6 is any other given as a parameter, it may be easier to start from the final date and decrease one by one, seeing if the day is skillful and counting how many skillful there are, until having the desired number of them. Each date traveled can be saved in a list with the appropriate message and at the end print that list upside down. For example:
Which could be called for example like this:
and would show in this case:
In this case, it happens that the
for
is unnecessary, so it is up to you to remove it.They are asking you to verify if the agreed day is Saturday or Sunday to move the exam date... then the displacement must necessarily be 2 days or 1:
Although both conditionals can also be merged using a
while
:Note that the calls to
print
. It is necessary to convertfecha_nueva
to string, withstr()
so that the concatenation is done correctly.And now, to top it off, notice that now the variable
i
has no use, then it can also be deleted.From what I understand, what you are looking for I think could be as follows: