繁体   English   中英

如何创建一个 function 返回 Python 中给定范围内的所有闰年和非闰年?

[英]How to create a function which returns all the leap and non leap years in given range in Python?

我想创建一个 function,它将 2 个不同的日期作为用户在单个输入字段(如 dd/mm/yyyy 格式)中的输入,并为我们提供一个列表中该日期范围和不同列表中的非闰年之间的所有闰年. 如果是Python3就好了

我虽然创建了 function,但不知道如何在一行中输入该输入,然后从中提取年份。

#Leap Year Program

year = int(input("Enter the Starting Year: "))

year2 = int(input("Enter the Ending Year: "))

s = []

b = []

for i in range(year,(year2)+1):
    if i % 4 == 0:
        if i % 100 != 0:
            s.append(i) 
        elif i % 100 == 0:
           if i % 400 == 0:
                s.append(i)
           else:
                b.append(i)
    else:
        b.append(i)

print("Leap Years: ",end="") 
   

for x in range(len(s)):
              
    print(s[x],end=", ")

print("\n")

# printing non leap year

print(" Non Leap Years: ",end="")        
for x in range(len(b)):                   #Converting List of Non- 
Leap-Years into form of output by traversing it
print(b[x],end=", ")

我必须查看您的单个输入字段才能知道如何按照我们的需要拆分字符串。 但这里有一个示例 function,它接受 2 个参数,开始日期和结束日期。 它将返回两个单独的列表,一个包含所有闰年,另一个包含非闰年。

def get_leap_years(start_date, end_date):
    # Extract the year from the start and end dates
    start_year = int(start_date.split("/")[-1])
    end_year = int(end_date.split("/")[-1])
    
    # Initialize lists to store the leap years and non-leap years
    leap_years = []
    non_leap_years = []
    
    # Iterate through each year in the range specified by the start and end dates
    for year in range(start_year, end_year+1):
        # Check if the year is a leap year (divisible by 4, not divisible by 100, or divisible by 400)
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            leap_years.append(year)
        else:
            non_leap_years.append(year)

    # Return the lists of leap years and non-leap years
    return leap_years, non_leap_years

# Example of using the function
leap_years, non_leap_years = get_leap_years("01/01/2000", "01/01/2023")

# Example of iterating through result lists.
print('Leap Years:')
for i in leap_years:
    print(i)
print('\nNon-Leap Years:')
for i in non_leap_years:
    print(i)

我认为你正在尝试这样做

import datetime
from typing import Tuple


DATE_FORMAT = "%d/%m/%Y"

def is_leap_year(year: int) -> bool:
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

def get_leap_and_not_leap_years_list(start: str, end: str) -> Tuple[list, list]:
    # get year from date
    start_year = datetime.datetime.strptime(start, DATE_FORMAT).year
    end_year = datetime.datetime.strptime(end, DATE_FORMAT).year
    
    leap_years, not_leap_years = [], []
    
    for year in range(start_year, end_year + 1):
        if is_leap_year(year):
            leap_years.append(year)
        else:
            not_leap_years.append(year)
    
    return leap_years, not_leap_years
    
    
leap_years, not_leap_years = get_leap_and_not_leap_years_list("22/03/1995", "4/4/2022")

print(f"{leap_years = }, {not_leap_years = }")

Output:

leap_years = [1996, 2000, 2004, 2008, 2012, 2016, 2020], not_leap_years = [1995, 1997, 1998, 1999, 2001, 2002, 2003, 2005, 2006, 2007, 2009, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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