Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second : collections.Counter, OrderedDict was used solution in Clear category for The Most Frequent Weekdays by keromage
from datetime import datetime, timedelta
from collections import Counter, OrderedDict
def init_odict():
# initialize dictionary
odict = OrderedDict() # ordered dictionary
dlist = [
["Monday", 0],
["Tuesday", 0],
["Wednesday", 0],
["Thursday", 0],
["Friday", 0],
["Saturday", 0],
["Sunday", 0],
]
for i in dlist:
odict[i[0]] = i[1]
return odict
def date_iterator_generator(year):
# date generator
begin = datetime(year, 1, 1)
end = datetime(year, 12, 31)
length = (end - begin).days + 1
# Sequence of Jan. 1 to Dec. 31
for n in range(length):
yield begin + timedelta(n)
def weekdaylist_generator(year):
# Generate day of the week
# weekday: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', ... , 'Monday']
gen = date_iterator_generator(year)
weekday = []
for target in gen:
weekday.append(target.strftime("%A"))
return weekday
# main
def most_frequent_days(year):
weekday = weekdaylist_generator(year)
# Aggregate the occurrence of words in list : collections.Counter(iter)
c = Counter(weekday)
odict = init_odict()
odict.update(c)
# odict: {('Monday', 53), ('Tuesday', 52), ... , ('Sunday', 53)}
common = []
for i in odict:
if odict[i] == max(odict.values()): # Probably 53
common.append(i)
return common
if __name__ == '__main__':
print("Example:")
print(most_frequent_days(1084))
# These "asserts" are used for self-checking and not for an auto-testing
assert most_frequent_days(1084) == ['Tuesday', 'Wednesday']
assert most_frequent_days(1167) == ['Sunday']
assert most_frequent_days(1216) == ['Friday', 'Saturday']
assert most_frequent_days(1492) == ['Friday', 'Saturday']
assert most_frequent_days(1770) == ['Monday']
assert most_frequent_days(1785) == ['Saturday']
assert most_frequent_days(212) == ['Wednesday', 'Thursday']
assert most_frequent_days(1) == ['Monday']
assert most_frequent_days(2135) == ['Saturday']
assert most_frequent_days(3043) == ['Sunday']
assert most_frequent_days(2001) == ['Monday']
assert most_frequent_days(3150) == ['Sunday']
assert most_frequent_days(3230) == ['Tuesday']
assert most_frequent_days(328) == ['Monday', 'Sunday']
assert most_frequent_days(2016) == ['Friday', 'Saturday']
print("Coding complete? Click 'Check' to earn cool rewards!")
Oct. 26, 2020
Comments: