@virnuls/

What's the day?

Python

One of the OCR Coding Challenges - take a date, validate it, and say what day of the week it would be.

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# a tuple used to name the day
weekday = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
# how long is each month: 0 = January, 1 = February, etc.
length = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# is it a valid date?  Assume yes to begin with
valid = True
full_date = input("Input a date in the form date/month/year: ")
# does it look like a date - i.e. two solidi?
valid = full_date.count("/") == 2
if valid:
  try:
    # split the date into a list
    date = full_date.split("/")
    year = int(date[2])
    d = int(date[0]) # named to match the formula used below
    month = int(date[1])
    # is it a leap year: https://support.microsoft.com/en-us/help/214019/method-to-determine-whether-a-year-is-a-leap-year
    leap = (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)
    # it's valid if the month is between 1 and 12 and the date
    # is between 1 and the length of the month (plus 1 if it's
    # February and it's a leap year)
    # NB. you could do this with several IFs intead
    valid = valid and (month > 0 and month < 13) and (d > 0 and d <= (length[month-1]+(leap and month==2)))
  except:
    valid = False
# print whether it's a valid date
print("That date is","in"*(not valid)+"valid.")
# using this algorithm: https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Disparate_variation
# start with Y = the year, or year - 1 if before March
if valid:
  # variable names and uses as described in Wikipedia
  Y = year-1*(month<3) # subtract 1 if before March
  y = Y % 100 # last two digits of Y
  c = int(Y/100) # first two digits of Y
  # d already defined above
  m = (month + 9) % 12 + 1 # shift months so that 1 = March
  # use formula to generate the number of the day, 0=Sunday
  w = (d + int(2.6*m - 0.2) + y + int(y/4) + int(c/4) - 2*c) % 7
  # print the name of the day
  print(full_date,"is a",weekday[w]+".")