Tuples: Exercise Answers

Tuples: Exercise Answers#

  1. Given the following tuple assigned to the variable data - (‘AAPL’, 157.96, 88_140_000). Assign the items to three variables(symbol, price, and volume) and print the values.

1data = ('AAPL', 157.96, 88_140_000)
2symbol, price, volume = data
3print(symbol, price, volume)
AAPL 157.96 88140000
  1. Test if the stock symbol “BAC” is in the data tuple.

1print("BAC" in data)
False
  1. Create a new tuple of the 3rd to 5th elements using the following tuple.

1acc_schools = ("Duke", "Notre Dame", "UNC", "NCSU", "Wake Forest", "Clemson")
2new_schools = acc_schools[2:5]
3print(new_schools, type(new_schools))
('UNC', 'NCSU', 'Wake Forest') <class 'tuple'>
  1. Create a tuple of monthly returns for a stock. Use tuple unpacking with the collector operator to separate the first quarter, middle quarters, and last quarter returns.

 1# Create a tuple of monthly returns for one year
 2monthly_returns = (0.02, -0.01, 0.03, 0.04, 0.01, -0.02,
 3                   0.05, 0.02, -0.01, 0.03, 0.04, 0.01)
 4
 5# Use tuple unpacking with the collector operator
 6jan, feb, mar, *middle_quarters, oct_ret, nov_ret, dec = monthly_returns
 7
 8# Group the results
 9first_quarter = (jan, feb, mar)
10last_quarter = (oct_ret, nov_ret, dec)
11
12# Display the results
13print("First quarter returns:", first_quarter)
14print("Middle quarters returns:", middle_quarters)
15print("Last quarter returns:", last_quarter)
First quarter returns: (0.02, -0.01, 0.03)
Middle quarters returns: [0.04, 0.01, -0.02, 0.05, 0.02, -0.01]
Last quarter returns: (0.03, 0.04, 0.01)
  1. Write a function that accepts any number of stock prices and returns their average price. Use the collector operator to unpack a tuple of stock symbols into the function call.

 1def average_price(*prices):
 2    total = sum(prices)
 3    average = total / len(prices)
 4    return average
 5
 6
 7# Tuple of stock symbols
 8stock_symbols = ("AAPL", "MSFT", "GOOG", "AMZN")
 9
10# Tuple of stock prices in the same order
11stock_prices = (182.35, 415.20, 142.80, 178.90)
12
13# Unpack the price tuple into the function call
14average = average_price(*stock_prices)
15
16print("Stock symbols:", stock_symbols)
17print("Stock prices:", stock_prices)
18print("Average stock price:", average)
Stock symbols: ('AAPL', 'MSFT', 'GOOG', 'AMZN')
Stock prices: (182.35, 415.2, 142.8, 178.9)
Average stock price: 229.8125
  1. Given a tuple of (stock_name, current_price, high_52week, low_52week, dividend_yield), use tuple unpacking to extract the stock name and create a list of just the numerical values.

1# Tuple containing stock information
2stock = ("Apple", 182.35, 199.62, 124.17, 0.0052)
3
4# Use tuple unpacking to separate the stock name from the numerical values
5stock_name, *numerical_values = stock
6
7# Display the results
8print("Stock name:", stock_name)
9print("Numerical values:", numerical_values)
Stock name: Apple
Numerical values: [182.35, 199.62, 124.17, 0.0052]