# Load data from presidents.txt, find years for which greatest and least
# number of presidents were alive
##############################################################################

def load_data():
    with open("presidents.txt", "r") as file:
        lines = file.read().splitlines()
    dictionary = {}
    for line in lines:
        items_list = line.split(",")
        if items_list[2] == "None":
            items_list[2] = "2016"
        dictionary[items_list[0]] = (items_list[1], items_list[2])
    return dictionary

def years_alive():
    dictionary = load_data()
    for key, value in dictionary.items():
        list_years = []
        for n in range(int(value[0]), (int(value[1])+1)):
            list_years.append(n)
        dictionary[key] = list_years
    return dictionary

def count_years():
    dictionary = years_alive()
    years_counter = {}
    for key, value in dictionary.items():
        for n in value:
            if years_counter.__contains__(n):
                years_counter[n] +=1
            else:
                years_counter[n] = 1
    return years_counter

def greatest_least():
    dictionary = count_years()
    sorted_years = sorted(dictionary, key = dictionary.__getitem__)
    greatest = sorted_years[-1]
    least = sorted_years[0]
    presidents_greatest = []
    presidents_least = []
    dic_names_years = years_alive()
    for key, item in dic_names_years.items():
        if greatest in item:
            presidents_greatest.append(key)
        if least in item:
            presidents_least.append(key)
    presidents_least_str = ", ".join(presidents_least)
    presidents_greatest_str = ", ".join(presidents_greatest)
    with open("greatest_least.txt", "w") as fout:
        fout.write("Least = {}\n".format(least) + presidents_least_str + "\n" +
            "Greatest = {}\n".format(greatest) + presidents_greatest_str + "\n")


##############################################################################
def main():
    
    greatest_least()

if __name__ == '__main__':
    main()
