Który rok ma najwyższy zysk? (zysk = in-out)

0

Mam do napisania funkcję, która ma wykonywać dokładnie to co jest w temacie. Posiadam plik items_test.csv, który podpinam do wiadomości. W pliku jest sporo linijek informacji, informacje w poszczególnej linii są oddzielone znakiem ";". Wszystko splitujemy i dzielimy na tablice. To rozumiem.

Mam taką funkcję służącą do otwierania pliku, podzielenia linii na tablice. W każdej lini najważniejszą dla mnie informacją jest czwarty element listy - słowo "in" albo "out". Nazwijmy to "kluczami", piąty element to ilość. In to dostawa. Out to powiedzmy sprzedaż.

Muszę obliczyć różnicę tych dwóch zmiennych. Chyba za pomocą pętli i instrukcji warunkowych. Ale nie wiem jak to zrobić


```def get_table_from_file(file_name):
    """
    Reads csv file and returns it as a list of lists.
    Lines are rows columns are separated by ";"

    Args:
        file_name (str): name of file to read

    Returns:
         list: List of lists read from a file.
    """
    with open(file_name, "r") as file:
        lines = file.readlines()
    table = [element.replace("\n", "").split(";") for element in lines]
    return table





Napisałem coś takiego, ale kompletnie to się kupy nie trzyma, nie wiem jak te linie informacji połączyć z funkcją zwracającą tablicę




def profit_in_out():
    with open('items_test.csv', "r") as file:
        for line in file.readlines():
            line = line.split(";")
            print(line)
            for element in line:
                if element[4] == "in":
                    print(element[5])


Moglibyście to napisać ? Chodzi o zrobienie takiej funkcji:

def which_year_max(table):
    """
    Question: Which year has the highest profit? (profit = in - out)

    Args:
        table (list): data table to work on

    Returns:
        number
    """
0

Najgłupsze rozwiązanie jakie chyba mi przyszło do łba:

def get_table_from_file(file_name):
    """
    Reads csv file and returns it as a list of lists.
    Lines are rows columns are separated by ";"

    Args:
        file_name (str): name of file to read

    Returns:
         list: List of lists read from a file.
    """
    with open(file_name, "r") as file:
        lines = file.readlines()
    table = [element.replace("\n", "").split(";") for element in lines]
    return table

table = get_table_from_file("items_test.csv")

year_2016_in = 0
year_2016_out = 0
year_2015_in = 0
year_2015_out = 0

for row in table:
    if row[3] == '2015':
        if row[4] == 'in':
            year_2015_in += int(row[5])
        if row[4] == 'out':
            year_2015_out += int(row[5])
    if row[3] == '2016':
        if row[4] == 'in':
            year_2016_in += int(row[5])
        if row[4] == 'out':
            year_2016_out += int(row[5])

income = {2015 : year_2015_in-year_2015_out, 2016 : year_2016_in - year_2016_out}

for key in income.keys():
    if income[key] == max(income.values()):
        print(key)
0

A taka funkcja ?


```def avg_amount(table, year):
    """
    Question: What is the average (per item) profit in a given year? [(profit)/(items count)]

    Args:
        table (list): data table to work on
        year (number)

    Returns:
        number
    """
0

Chyba coś w stylu:
table = get_table_from_file("items_test.csv")
a następnie:
year_items= [tu lądują dochody z danego roku]
return sum(year_items) / len(year_items)

0

Jak masz juz w liście dane to
diff_2015 = sum(1 for row in table if row[4] == 'in') - sum(1 for row in table if row[4] == 'out')
diff_2016 = sum(1 for row in table if row[5] == 'in') - sum(1 for row in table if row[5] == 'out')

Pozdro

2

Ja bym to wykonał mniej więcej tak chyba jest "poprawnie".

ofc: do poprawki nazwy zmiennych oraz inne pierdoły warto żeby ucząca się osoba klepnęła jakiś unit-test (np: py.test)
ogólnie warto dodac walidacje tego czy nasz csv jest sensowny czy nie ma pustych linii, czy sa zle sformatowane dane
oraz gdy bedzie cos innego niz 'in' i 'out'.

Ogólnie deklarowanie że oczekujemy roku takiego lub innego jest słabe bo co w wypadku gdy będzie 2020 ?

Nie ma chyba tez potrzeby wyliczac in i out wystarczy nam trzymanie jednej wartosci i dodawanie do niej lub odejmowanie.


from collections import defaultdict

def get_table_from_file(file_name):
    """
    Reads csv file and returns it as a list of lists.
    Lines are rows columns are separated by ";"

    Args:
        file_name (str): name of file to read

    Returns:
         list: List of lists read from a file.
    """
    with open(file_name, "r") as file:
        lines = file.readlines()
    table = [element.replace("\n", "").split(";") for element in lines]
    return table

def get_income():

    income = defaultdict(int)
    report = get_table_from_file(file_name='items_test.csv')

    for entry in report:
        year, status, value = entry[3:]
        value = int(value) if status == 'in' else -int(value)
        income[year] += value

    return dict(income)


def highest_income_year():
    income = get_income()
    print("Calculated profits: {}".format(income))
    return "Highest income was achieved in: {}".format(max(income, key=income.get))


print(highest_income_year())


1 użytkowników online, w tym zalogowanych: 0, gości: 1