[Tutor] Finding the largest gap in tuple between two lists.
Peter Otten
__peter__ at web.de
Sun Nov 18 13:10:36 EST 2018
Mats Wichmann wrote:
> 1. From an endpoint pair - say Buy/Levski and Sell/Olisar, you need the
> common items. No point in looking further at items that can't both be
> bought at the source and sold at the destination. Fortunately, Python
> sets are really good at this, but first you have to extract only the
> item names from your dictionary, since that comparison is based only on
> good names. Something like this:
>
> def common(curr, other):
> return set(curr.keys()).intersection(set(other.keys()))
As dict.keys() are very similar to a set you can also write
curr.keys() & other.keys()
or
curr.keys() & other # if you don't care about symmetry ;)
> So one way to tackle this might be to build a new dictionary containing
> the items and their price difference. Given our previous idea of having
> a set which contains the common items:
>
> prices = {k: Selling_Olisar[k] - Buying_Levski[k] for k in possibles}
While a dict is almost always a good idea there is no need to build one if
you're only interested in one entry. Instead feed the pairs directly to
max():
selling = dict(Selling_Olisar)
buying = dict(Buying_Levski)
possibles = selling.keys() & buying
if possibles:
profit, good = max(
(selling[k] - buying[k], k) for k in possibles
)
if profit > 0:
print("Best good", good, "wins", profit, "per unit")
else:
print("Found nothing profitable.")
else:
print("Found nothing that can be sold at your destination")
More information about the Tutor
mailing list