dimanche 21 février 2021

Python put output in print of list

Got this exellent coding help from Tom Wojcik https://stackoverflow.com/users/5833429/tom-wojcik

with the code below I find YoY changes and can list those that have consecutive gotten better or worse. It works on my large country list. Everything is good.

But now I'm assigned to do a printout of the Countries, Year and score per year for those that have improved every year.

The code lists in this case two countries that have YoY improvement every year. But how do I get that find_yoy() to print to information from the nested list (lst) instead of just the names?

I've tried to find the indexes of the country name that is output, but it just becomes to complex for me putting that info to something useful.

Do you have any tips or trix on how to approach this?

Code below:

lst = [
    ['',2018,2015,2012,2009,2006,2003],
    ["Country1",523,525,527,530,531,532],
    ["Country2",551,548,561,555,547,550],
    ["Country3",545,538,536,534,533,529],
    ["Country4",526,524,515,510,505,500]
]

_, *year_data = lst.pop(0)
countries = lst


def is_decreasing(lst) -> bool:
    last_checked, *rest = lst
    for year_data in rest:
        if year_data < last_checked:
            last_checked = year_data
        else:
            return False
    return True


def is_increasing(lst) -> bool:
    last_checked, *rest = lst
    for year_data in rest:
        if year_data > last_checked:
            last_checked = year_data
        else:
            return False
    return True


def find_yoy():
    increasing_yoy = []
    decreasing_yoy = []

    for country in countries:
        country_name, *country_data = country
        assert len(year_data) == len(country_data)
        sorted_year_data, sorted_country_data = zip(*sorted(zip(year_data, country_data)))

        if is_increasing(sorted_country_data):
            increasing_yoy.append(country_name)
        elif is_decreasing(sorted_country_data):
            decreasing_yoy.append(country_name)

    print("countries with increasing yoy:", ', '.join(increasing_yoy), '.')
    print("countries with decreasing yoy:", ','.join(decreasing_yoy), '.')

find_yoy()

Aucun commentaire:

Enregistrer un commentaire