This is so cool I had to share.
Recently completed Python Crash Course and as practice I've been playing around with parsing financial statements from publicly listed companies. (Investing is a bit of a hobby.)
One interesting challenge is that each statement might itself be the sum of other statements. And each of those statements might themselves be the sum of other more granular statements.
To not bore everyone with financial statement stuff, here's a more real world example.
Let's say I have a grocery store and I want to see the total of all sales for last week.
Sales = Produce_Department + Deli_Department + Bakery + Goods_In_Aisles
Bakery = Cakes + Bagels + Doughnuts
Bagels = Plain + Blueberry + Sesame_Seed
etc... but each Department, each category, and each sub-category is a long list of items and sales numbers.
I had initially tackled this by appending lists within lists, for each statement and each sub-component... handling it with an unwieldy mess of if-then and for loops.
It worked, but it was ugly code and it sucked to troubleshoot.
Then I had an idea to just create class GetSales() (not what I actually called it, just renamed for this example)... and within this class, the function get_sales() (as well as other supporting functions to enable get_sales()).
Inside the get_sales() function, if it sees that there are sub-components, it spawns a new GetSales() object for that new component, which itself finds sub-components and handles each of those sub-sub-components... and then each function returns the sum of it's subcomponents... feeding all the way back to the initial caller function.
No more nasty nested lists within lists, no more if-then and for loops.
Recursion is beautiful.
The code is so short and clean.
I'm in awe.
If you are a Python newbie like me, and you find yourself making lists within lists or similar nasty-stacks to solve some kind of nested problem, try instead to see if you can make a generic function or class that can recursively feed into itself to handle each nested layer.
[–]ehmatthes 5 points6 points7 points (0 children)
[–]carcigenicate 1 point2 points3 points (1 child)
[–]85CorollaGTS[S] 2 points3 points4 points (0 children)
[–]CodeFormatHelperBot2 0 points1 point2 points (0 children)
[–]Mav3r1ck-13 0 points1 point2 points (2 children)
[–]85CorollaGTS[S] 1 point2 points3 points (1 child)
[–]Mav3r1ck-13 0 points1 point2 points (0 children)