When it is required to find the number of times every day of the week occurs in a year, a list is defined, and it is iterated over, and is count is incremented respectively.
Below is a demonstration of the same −
Example
import math def num_of_occurrence( n, firstday): my_days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday" ] my_count= [4 for i in range(0,7)] my_position = -1 for i in range(0,7): if (first_day == my_days[i]): my_position = i break inc = n - 28 for i in range( my_position, my_position + inc): if (i > 6): my_count[i % 7] = 5 else: my_count[i] = 5 for i in range(0,7): print (my_days[i] , " " , my_count[i]) num = 31 first_day = "Thursday" num_of_occurrence(num, first_day)
Output
Monday 4 Tuesday 4 Wednesday 4 Thursday 5 Friday 5 Saturday 5 Sunday 4
Explanation
The required packages are imported.
A method named ‘num_of_occurence’ is defined that takes a number and a day of week as parameter.
A list with number of days of week is defined.
Another list with numbers in the range of 0 and 7 is defined.
The range is iterated over, and if the day passed as parameter matches a day from the list, its position is set.
Another iteration is used and the count of every day of the week is incremented depending on the day passed as first day to the method.
The method is called by passing the respective parameters.
The output is displayed on the console.