Skip to content

Instantly share code, notes, and snippets.

@mekhami
Created December 3, 2018 18:53
Show Gist options
  • Save mekhami/ea9d569993e6cf308baccd1492558be5 to your computer and use it in GitHub Desktop.
Save mekhami/ea9d569993e6cf308baccd1492558be5 to your computer and use it in GitHub Desktop.
def parse_range(years):
years = years.split(', ')
years = [split_years(year.strip()) for year in years if split_years(year)]
years = flatten(years)
return [x for x in sorted(set(years)) if in_valid_years(x)]
def in_valid_years(year):
return 1999 <= year <= 2018
def split_years(year):
if '-' not in year:
return int(year) if year else None
beginning, ending = [year for year in year.split('-')]
return range(int(beginning), int(ending)+1)
def flatten(array):
arr = []
for item in array:
if isinstance(item, list):
arr.extend(instance for instance in item if instance)
else:
arr.append(item)
return arr
assert parse_range('1999, 2002-2005, 2007') == [1999, 2002, 2003, 2004, 2005, 2007]
assert parse_range('2002-2005, 2002-2005, 2002 - 2005') == [2002, 2003, 2004, 2005]
assert parse_range('2017') == [2017]
assert parse_range('2017 - 2015') == []
assert parse_range('2015 - 2015') == [2015]
assert parse_range('1999 , 2000, , 2008') == [1999, 2000, 2008]
assert parse_range('2015, 2014, 2010') == [2010, 2014, 2015]
assert parse_range('1999, 3000') == [1999]
assert parse_range('1998, 2020') == []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment