简体   繁体   中英

List Comprehension

I am trying to use list comprehension and the power of the nested function to return a list of all Dates being Friday 13 within a given year in the form (dd/mm/yyyy). I am however having very little luck with nested loops, I would appreciate any assistance I could get with resolving this issue.

The previously created function to be used is seen as:

def day_of_week11(d, m, y):
    # Write your code here
    day_names =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
    if m < 3:
        y -= 1
        m += 12
    m -= 2
    yd = y % 100
    yc = y // 100
    day = (d + ((13*m-1)//5) + yd + yd//4 + yc//4 - 2*yc) % 7
    day=(math.ceil(day))
    if 2>day>=1:
        return day_names[0]
    elif 3>day>=2:
        return day_names[1]
    elif 4>day>=3:
        return day_names[2]
    elif 5>day>=4:
        return day_names[3]
    elif 6>day>=5:
        return day_names[4]
    elif 7>day>=6:
        return day_names[5]
    else:
        return day_names[6]

#The function I am attempting to write now is:

def not_lucky (yr):
    def day_of_week11(d, m, y):
    # Write your code here
        i=(d, m, y)
    return len([i for i in range(12) if day_of_week11(d, m, y)(yr,i+1,13)==4])
from datetime import timedelta, date

given_year=2021

start_date = date(given_year, 1, 1)
end_date = date(given_year+1, 1, 1)

list_of_friday_the_thirteenth=[single_date.strftime("%d/%m/%Y") for single_date in (start_date + timedelta(n) for n in range((end_date-start_date).days)) if single_date.weekday()==4 and single_date.day==13 ]

print(list_of_friday_the_thirteenth)

List comprehension would be too complicated in this case. Possible solution is following:

from datetime import date, timedelta

def thirteenth_fridays(year):
    d = date(year, 1, 1)
    if d.weekday() <= 4:
        days = 4 - d.weekday()
    else:
        days = 11 - d.weekday()
    d += timedelta(days)
    while d.year == year:
        if d.day == 13:
            yield d.strftime("%d/%m/%Y")
        d += timedelta(days = 7)
        

for d in thirteenth_fridays(2024):
    print(d)

Prints

13/09/2024
13/12/2024

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM