0

I am trying to find a Pythonic way to accomplish a task that seems simple but I can't quite get it into a concise or Pythonic solution.

The core question is this. Suppose there are N accounts, and each account has an object that carries its name, acct number, balance, and cost to withdraw from. The goal is to withdraw from the accounts - possibly taking some to zero - in a way that has the lowest cost. So, for example, right now we might need to raise $1,000, and account A has $250 in it and it will be a 5% charge to access any amount from it; account B has $500 in it and costs 4% to access; account C has $400 in it and costs 3% to access, and account D has $150 in it and costs 2% to access it. The percents may change every time...

The answer is to take $150 from D, then $400 from C, then $450 from B and be done with it, leaving $50 in B and $250 in C.

Some functional languages (like APL) have a 'grade up' function which, if given the list of account objects and the sort figure of merit (the %age here) would give you a list of the same objects sorted by increasing cost to access. Then it is simply cycling through the list until the need is fulfilled would do the job.

I could write such a mapping function, but this seems like a pretty common pattern model,so I am wondering if I am missing some useful mapping or functional tools in Python that would make this more concise.

This was marked as a duplicate, but the answers it points to don't solve the problem. The question is not how to sort a list, but hot so sort a lit of objects based on an attribute of those objects.

eSurfsnake
  • 647
  • 6
  • 17
  • Not sure it is an exact duplicate. All the examples with sort() or sorted() let you sort the elements of the list themselves, or supply a function (like len) to be applied to generate the key to sort. It seems like I need to, now, figure out how to the the attribute of the object by name. For example, if the objects were people, and you want to sort the list of objects by the age - where age is an attribute - I am guessing one needs to use a magic method like getattr() but this seems a bit messy for a simple and repetitive pattern. – eSurfsnake Jan 19 '18 at 21:47
  • In fact, I tried it and that fails - getattr doesn't know how to know it is looking at the current object, as it were. – eSurfsnake Jan 19 '18 at 21:58

0 Answers0