Linus Liljequist
Linus Liljequist

Reputation: 47

Using dictionaries with for loops to compare values

I'm currently working on an assignment, we are reading files containing shares, the shares are stamped with a date and a value of the share. In the assignment we are supposed to use dictionarys as a inparameter in all of our functions.

Here is a small example of the share input;

2000-01-26, 3.67987

2000-01-27, 3.673608

2000-01-28, 3.393913

The goal is to find two dates were buying and selling the shares gets you the most profit and two dates were buying and selling grants you the most loss. I've made a dictionary containing pairs of dates and share values, now i just need to compare them to each other. The dictionary is ordered like this: {share value : date}

Currently i've managed to solve this by putting all the share values in a list were i can compare them to each other easier since they are indexed. I then use the position to find the share value again and then use it to find the value of the corresponding key in the dictionary.

However this solution does not properly use the dictionary as an inparameter so i believe it will not satisfy my professor.

def calc_max_profit():
   value = 0
   profit = 0
   max_profit = 0
   for x in range(0, len(share_list)):
       value = share_list[x]

       for y in range(x+1, len(share_list)):
           profit = share_list[y] - value

           if profit > max_profit:
               max_profit = profit

This is basically how i calculated the max profit, in the if-statement i just need to save the position of the last 'max_proft = profit' that occured, but i wont do that here.

So is there any way to do a similar thing using only dictionaries?

Upvotes: 2

Views: 112

Answers (1)

SuperKogito
SuperKogito

Reputation: 2966

This was a bit tricky, but I hope this solves your problem. Note that you have to make sure that the chronological order of the buy and sell dates makes sense. The provided code builds a new dictionary of differences (keys=diffs & vals=sell_date-buy_date) then you just find the maximum value for max-profit and minimum for max-loss.

from datetime import datetime as dt

shares = {150:'2000-01-01', 10:'2000-07-01', 120:'2000-05-01', 200:'2000-09-01', 50:'2000-08-01'}
diff_values = [i-j for i in shares.keys() for j in shares.keys() 
               if dt.strptime(shares[j], "%Y-%m-%d") <  dt.strptime(shares[i], "%Y-%m-%d") ]

diff_dates  = [[shares[j], shares[i]] for i in shares.keys() for j in shares.keys()
               if dt.strptime(shares[j], "%Y-%m-%d") <  dt.strptime(shares[i], "%Y-%m-%d")]
diffs_dict  = dict(zip(diff_values, diff_dates))

max_diff = max(diffs_dict.keys())
min_diff = min(diffs_dict.keys())

Upvotes: 1

Related Questions