for loop - Understanding how to multiply specific values in tuples in Python -
i no expert no means , not claim exercise have been having hardest time with. having issues understanding how call out values in 1 tuple , multiply them. keep on getting following output.
def cost( ablock ): cost = portfolio[1]*portfolio[2] print(cost) output comes out >>> function cost @ 0x0594ad68
i unclear why want me use "ablock" parameter...
where start program?
blocks of stock. block of stock number of attributes, including purchase date, purchase price, number of shares, , ticker symbol. can record these pieces of information in tuple each block of stock , number of simple operations on blocks.
let's dream have following portfolio.
purchase date purchase price shares symbol current price 25 jan 2001 43.50 25 cat 92.45 25 jan 2001 42.80 50 dd 51.19 25 jan 2001 42.10 75 ek 34.87 25 jan 2001 37.58 100 gm 37.58
we can represent each block of stock 5-tuple purchase date, purchase price, shares, ticker symbol , current price.
portfolio= [ ( "25-jan-2001", 43.50, 25, 'cat', 92.45 ), ( "25-jan-2001", 42.80, 50, 'dd', 51.19 ), ( "25-jan-2001", 42.10, 75, 'ek', 34.87 ), ( "25-jan-2001", 37.58, 100, 'gm', 37.58 ) ]
develop function examines each block, multiplies shares purchase price , determines total purchase price of portfolio.
def cost( ablock ): #compute price times shares return cost
develop second function examines each block, multiplies shares purchase price , shares current price determine total amount gained or lost.
def roi( ablock, pricetoday ): #use cost( ablock ) cost #compute pricetoday times shares return difference
you have 2 ways access value in tuple:
- by index:
shares = block[2]
- by unpacking values:
purchase_date, purchase_price, shares, symbol, price = block
given 2 ways, here 2 possible solutions problem
def total_purchase_price(stocks): res = [] block in stocks: shares = block[2] purchase_price = block[1] res += [shares * purchase_price] return res
or
def total_wins(stocks): win = 0 block in stocks: purchase_date, purchase_price, shares, symbol, current_price = block win += (purchase_price - current_price) * shares return win
you call these functions in manner:
portfolio= [ ( "25-jan-2001", 43.50, 25, 'cat', 92.45 ), ( "25-jan-2001", 42.80, 50, 'dd', 51.19 ), ( "25-jan-2001", 42.10, 75, 'ek', 34.87 ), ( "25-jan-2001", 37.58, 100, 'gm', 37.58 ) ] print total_purchase_price(portfolio) print total_wins(portfolio)
Comments
Post a Comment