-1

Imagine i have the following 2 lists.

List years- contains all years between 1901 and 2099

years=[1901,...,2099]

List leap years-contais all leap years between 1901 and 2099

I want to creat a non leap_years list that contains all the elements from the first list that are not leap years.

For leap years list i iterate using range(1901,2100,4) but i cant make the non leap years list. What should be the algorithm?

I actually dont have any code since this is a teoric question.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
Luismaia1994
  • 143
  • 1
  • 8
  • 2
    Usually if someone want to collect leap years he/she is trying to do some date calculations. Doing that manually is by far not the best approach, so what is the original problem you are trying to solve with this? – Klaus D. May 03 '19 at 10:06
  • yes im trying to input a date and return the number of days between yy/mm/dd to another – Luismaia1994 May 03 '19 at 10:23

4 Answers4

2

I think this is what you are looking for:

[i for i in years if i not in leap_years]

Fill a list with the numbers from years if the number is not contained in leap_years

funie200
  • 3,688
  • 5
  • 21
  • 34
2
years =[i for i in range(1901,2100)]
leap_year = [i for i in range(1904,2100,4)]

result = list(set(years)-set(leap_year))

use set property on your list is better than using if year in list

sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1

First of all, range(1901,2100,4) won't give you a list of leap years between 1901 and 2099. range(1904,2100,4) will give you that.

The algorithm could be something along the lines of (in psuedocode):

non-leap years is the empty list
for year in range(1901, 2099):
    if year%4 != 0:
        add year to non-leap years
Ollie
  • 1,641
  • 1
  • 13
  • 31
-1

A simple list-comprehension should suffice, just find all years which are not in leap_years (list of leap years) but are in all_years (list of all years)

non_leap_years = [year for year in all_years if year not in leap_years]

Another approach is to convert both to sets, and take the set difference

non_leap_years = list(set(all_years) - set(leap_years))

As an extra tidbit, we already have a calendar.isleap function which will tell you if the year is leap year

import calendar

all_years = list(range(1901,2100))
leap_years = [year for year in all_years if calendar.isleap(year)]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40