Created
July 4, 2018 15:33
-
-
Save jrjames83/160e5aee657ee8086d64ce411e9d633b to your computer and use it in GitHub Desktop.
Recursive algorithm to determine when to buy and sell stocks, not eval'd for edge cases
This file contains hidden or 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
| def get_buy_sell_prices(stocks: list): | |
| if len(stocks) == 1: | |
| return 'Cannot Profit - Down to 1 Stock' | |
| if len(stocks) == 2: | |
| if stocks[0] > stocks[1]: | |
| return 'Cannot Profit - Down to 2 Stocks' | |
| min_price, max_price = min(stocks), max(stocks) | |
| min_index, max_index = stocks.index(min_price), stocks.index(max_price) | |
| if min_price == max_price: | |
| return('Min and Max are the Same Price') | |
| if min_index < max_index: | |
| return ("Buy at {} sell at {}".format(stocks[min_index], | |
| stocks[max_index])) | |
| else: | |
| stocks.pop(stocks.index(max_price)) | |
| return get_buy_sell_prices(stocks) | |
| assert(get_buy_sell_prices([10, 7, 5, 8, 11, 9]) == 'Buy at 5 sell at 11') | |
| assert(get_buy_sell_prices([1,2,12,9,8,3]) == 'Buy at 1 sell at 12') | |
| assert(get_buy_sell_prices([11,3,2,1,5,1]) == 'Buy at 1 sell at 5') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment