Answer to Question #275959 in Python for jaya

Question #275959

01.Write a Python program to check whether a given date is valid date or not and to out put the following.


• If the date is valid then the message “Date is Valid” otherwise the message “Date is Invalid”.

• If the date is a valid date, then the next date.


Hint:


Follow the following steps. (NOTE: You are not allowed to use any Python built-in functions.)


• Get the inputs Year, Month, and Date separately.

• Use selection statements, i.e., if-else statements to check if the Date, Month, and the Year are valid.

• if the date is a valid date, then print the next date (Increment the date).


Sample Test Cases:


Enter the Date Expected Result Next Date

Test Case 1 2020 02 30 Date is Invalid -

Test Case 2 2020 02 29 Date is Valid 01-03-2021

Test Case 3 2021 09 31 Date is Invalid -

Test Case 4 2021 13 01 Date is Invalid -

Test Case 5 2021 08 31 Date is Valid 01-09-2021


1
Expert's answer
2021-12-05T16:17:47-0500
def get_date(line):
    L = [int(s) for s in line.split()]
    return tuple(L)

def is_leap(y):
    if (y%4 == 0 and  y%100 != 0) or y%400 == 0:
        return True
    return False


def is_correct(date):
    #         Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 
    days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    y, m, d = date
    if m < 1 or m > 12:
        return False
    if m == 2 and is_leap(y):
        days[m] += 1
    if 1 <= d <= days[m]:
        return True
    
    return False

def next_day(date):
    #         Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 
    days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    y, m, d = date
    if is_leap(y):
        days[m] += 1
    d += 1
    if d > days[m]:
        d = 1
        m += 1
    if m > 12:
        m = 1
        y += 1
    return d, m, y

def print_date(date):
    y, m, d = date
    print(f'{d:02d}-{m:02d}-{y}')

def main():
    tests = ['2020 02 30',
             '2020 02 29',
             '2021 09 31',
             '2021 13 01', 
             '2021 08 31']
    for i in range(len(tests)):
        print(f'Test case {i+1} {tests[i]}:', end = ' ')
        date = get_date(tests[i])
        if is_correct(date):
            print('Date is Valid  ', end = ' ')
            date = next_day(date)
            print_date(date)
        else:
            print('Data is invalid -')

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS