Program to find number of times each day occurs in a year using Python

Introduction

The task is to find the occurrence of days Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday in a given year.

Program to find number of times each day occurs in a year

Program

import datetime

import calendar




def occurence(ip_year):

    week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    list = [52 for i in range(7)]

    idx = -1

    day = datetime.datetime(ip_year, month = 1, day = 1).strftime("%A")

    for i in range(7):

        if day == week_days[i]:

            idx = i

        if calendar.isleap(ip_year):

            list[idx] += 1

            list[(idx+1)%7] += 1

        else:

            list[idx] += 1

        for i in range(7):

            print(week_days[i], list[i])

           

ip_year = int(input("Enter the year: "))

print("The count of days in year {0} is:".format(ip_year))

occurence(ip_year)

Output

Program to find number of times each day occurs in a year Output

Explanation

As we know that in a particular year we have at least 52 weeks. That means each day will occur at least 52 times in a year. We have created a list of size 7 with initial value 52. We have found the index of the first day of the given year. It the year is found to be leap year, increment the first day and second day by 1. At last calculate the number of days with occurrence and print the result.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.