Function Name: avg_capacity Parameter: product_list - A list containing a sequence of product descriptions as strings.
Return: A floating point number that denotes the average of capacities as given in the list.
Description: Given a list of product descriptions where each element in the list is of the format 'product_id-capacity', calculate the average of all capacities and return the value.
Let us assume that you are the owner of a store that sells different masks. These masks come in shipments of boxes of a particular capacity. Each box of mask has a unique product ID (no two IDs are the same), and a capacity associated with the box. You want to find all the different capacities of the boxes, and calculate the average of these capacities.
Ex)
product_list = ['A1-10', 'B10-40', 'C403-50', 'D5-10'] return: 27.5
def avg_capacity(product_list):
for capacity in range(len(product_list)):
product_list[capacity] = product_list.split("-")
average = capacity["-":]
return average
print(avg_capacity(['C12-100', 'A10-400']))
I honestly have no idea how to approach this. I was told to use string methods, so I attempted to use split in order to split the product ID at every instance of a dash. However, I don't know how to manipulate the lists in order to take the numbers on the right side of the dash, and put them code that would take the average of every product ID in product list. Any help is appreciated :D
CodePudding user response:
def avg_capacity(product_list):
capacity_list = []
for capacity in product_list:
capacity_list.append(int(capacity.split("-")[1]))
return sum(capacity_list) / len(capacity_list)
print(avg_capacity(['C12-100', 'A10-400']))
CodePudding user response:
def avg_capacity(product_list: list[str]) -> float:
capacities = [int(x.split("-")[1]) for x in product_list]
return sum(capacities) / len(capacities)
CodePudding user response:
There are a number of problems with your code:
- you call
product_list.split("-")
, butproduct_list
is the list itself; you should callsplit
on the individual elements, e.g.product_list[capacity]
in your current code - with
for capacity in range(...)
, capacity is anint
, socapacity["-":]
does not work; if you want the part after the"-"
, get the[1]
element aftersplit("-")
- you never actually sum and divide the individual capacities, as would be required for the average
- you
return
in the first iteration of the loop; you probably want to return after the loop (after fixing the other problems)
You can try something like this:
def avg_capacity(product_list):
total = 0
for mask in product_list:
name, cap = mask.split("-")
total = int(cap)
return total / len(product_list)
The above loop could also be condensed into a one-liner using sum
:
def avg_capacity(product_list):
return sum(int(mask.split("-")[1]) for mask in product_list) / len(product_list)