Created
July 13, 2023 20:52
-
-
Save dflima/d533b171c581bea5c81b4e4cc50c231e to your computer and use it in GitHub Desktop.
Record aggregation exercise. From: https://twitter.com/zanfranceschi/status/1679497149732585472
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
records = [ | |
%{"data" => "2023-07-13", "qtd" => 12}, | |
%{"data" => "2023-07-14", "qtd" => 30}, | |
%{"data" => "2023-07-13", "qtd" => 4}, | |
%{"data" => "2023-07-14", "qtd" => 98}, | |
%{"data" => "2023-07-12", "qtd" => 4}, | |
%{"data" => "2023-07-12", "qtd" => 8}, | |
%{"data" => "2023-07-12", "qtd" => 31}, | |
%{"data" => "2023-07-15", "qtd" => 74}, | |
%{"data" => "2023-07-13", "qtd" => 12}, | |
%{"data" => "2023-07-12", "qtd" => 1}, | |
%{"data" => "2023-07-17", "qtd" => 3}, | |
%{"data" => "2023-07-16", "qtd" => 35} | |
] | |
records | |
|> Enum.group_by(&Map.get(&1, "data"), &Map.get(&1, "qtd")) | |
|> Map.new(fn {k, v} -> {k, Enum.sum(v)} end) | |
|> IO.inspect() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
def aggregate(records): | |
def f(acc, r): | |
acc[r["data"]] = acc[r["data"]] + r["qtd"] if acc.get(r["data"]) is not None else r["qtd"] | |
return acc | |
return reduce(f, records, {}) | |
records = [ | |
{"data": "2023-07-13", "qtd": 12}, | |
{"data": "2023-07-14", "qtd": 30}, | |
{"data": "2023-07-13", "qtd": 4}, | |
{"data": "2023-07-14", "qtd": 98}, | |
{"data": "2023-07-12", "qtd": 4}, | |
{"data": "2023-07-12", "qtd": 8}, | |
{"data": "2023-07-12", "qtd": 31}, | |
{"data": "2023-07-15", "qtd": 74}, | |
{"data": "2023-07-13", "qtd": 12}, | |
{"data": "2023-07-12", "qtd": 1}, | |
{"data": "2023-07-17", "qtd": 3}, | |
{"data": "2023-07-16", "qtd": 35}, | |
] | |
result = aggregate(records) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment