Get Total Commission Amount¶
A collection is provided with sales amount and commission percentage. Using that collection compute total commission amount. If the commission percent is None or not present, treat it as 0.
- Each element in the collection is a tuple.
- First element is the sales amount and second element is commission percentage.
- Commission for each sale can be computed by multiplying commission percentage with sales (make sure to divide commission percentage by 100).
- Some of the records does not have commission percentage, in that case commission amount for that sale shall be 0
In [1]:
transactions = [(376.0, 8),
(548.23, 14),
(107.93, 8),
(838.22, 14),
(846.85, 21),
(234.84,),
(850.2, 21),
(992.2, 21),
(267.01,),
(958.91, 21),
(412.59,),
(283.14,),
(350.01, 14),
(226.95,),
(132.7, 14)]
In [2]:
type(transactions)
Out[2]:
list
In [3]:
transactions[:6]
Out[3]:
[(376.0, 8), (548.23, 14), (107.93, 8), (838.22, 14), (846.85, 21), (234.84,)]
In [4]:
sale = transactions[0]
In [5]:
type(sale)
Out[5]:
tuple
In [6]:
sale
Out[6]:
(376.0, 8)
In [7]:
commission_amount = round(sale[0] * (sale[1] / 100), 2)
In [8]:
commission_amount
Out[8]:
30.08
In [9]:
sale = (234.84,)
In [10]:
sale[1]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [10], in <cell line: 1>() ----> 1 sale[1] IndexError: tuple index out of range
In [11]:
commission_amount = round(sale[0] * (sale[1] / 100), 2) # errors out
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [11], in <cell line: 1>() ----> 1 commission_amount = round(sale[0] * (sale[1] / 100), 2) IndexError: tuple index out of range
In [12]:
len(sale)
Out[12]:
1
In [13]:
commission_pct = sale[1] / 100 if len(sale) == 2 else 0
In [14]:
commission_pct
Out[14]:
0
In [15]:
transactions_fixed = map(
lambda sale: sale[0] * (sale[1] / 100 if len(sale) == 2 else 0),
transactions
)
In [16]:
list(transactions_fixed)
Out[16]:
[30.080000000000002, 76.75220000000002, 8.634400000000001, 117.35080000000002, 177.8385, 0.0, 178.542, 208.362, 0.0, 201.37109999999998, 0.0, 0.0, 49.001400000000004, 0.0, 18.578]
In [17]:
transactions_fixed = map(
lambda sale: sale[0] * (sale[1] / 100 if len(sale) == 2 else 0),
transactions
)
from functools import reduce
reduce(
lambda tot, ele: round(tot + ele, 2),
transactions_fixed
)
Out[17]:
1066.5
{note}
Using `map` function call as argument.
In [18]:
reduce(
lambda tot, ele: round(tot + ele, 2),
map(
lambda sale: sale[0] * (sale[1] / 100 if len(sale) == 2 else 0),
transactions
)
)
Out[18]:
1066.5
In [19]:
from operator import add
round(
reduce(
add,
map(
lambda sale: sale[0] * (sale[1] / 100 if len(sale) == 2 else 0),
transactions
)
), 2
)
Out[19]:
1066.51