Question

I am no expert by no means and do not claim to be but this is an exercise that I have been having the hardest time with. I am having issues understanding how to call out values in one tuple and multiply them. I keep on getting the following output.

def cost( aBlock ):

 cost = portfolio[1]*portfolio[2]

print(cost)

output comes out to >>> function cost at 0x0594AD68

I am unclear why they want me to use the "aBlock" parameter...

where do i start with this program?

Blocks of Stock. A block of stock as a number of attributes, including a purchase date, a purchase price, a number of shares, and a ticker symbol. We can record these pieces of information in a tuple for each block of stock and do a number of simple operations on the blocks.

Let's dream that we have the 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 as a 5-tuple with purchase date, purchase price, shares, ticker symbol and 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 a function that examines each block, multiplies shares by purchase price and determines the total purchase price of the portfolio.

def cost( aBlock ):
 #compute price times shares
return cost

Develop a second function that examines each block, multiplies shares by purchase price and shares by current price to determine the total amount gained or lost.

def roi( aBlock, priceToday ):
  #use cost( aBlock ) to get cost
  #compute priceToday times shares
return the difference
Was it helpful?

Solution

You have 2 ways to access a value in a Tuple:

  1. By index: shares = block[2]
  2. By unpacking all the values: purchase_date, purchase_price, shares, symbol, price = block

Given this two ways, here are two possible solutions to your problem

def total_purchase_price(stocks):
    res = []
    for block in stocks:
        shares = block[2]
        purchase_price = block[1]
        res += [shares * purchase_price]
    return res

or

def total_wins(stocks):
    win = 0
    for block in stocks:
        purchase_date, purchase_price, shares, symbol, current_price = block
        win += (purchase_price - current_price) * shares
    return win

You would call these functions in this 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top