question 410 NumPy Foundations · hard
Vectorise the tip calculation
tip_percentages works, but loops over every trip in Python, and the full taxi file has over a hundred thousand of them. Rewrite it with array operations and no loop or comprehension inside the function. It must return exactly what the loop version returns: for a card trip (payment == 1) with a fare above 0, the tip as a percentage of the fare; for every other trip, 0.0.
Function
tip_percentages(fares, tips, payments)Returnsa list of floats, one per trip
Constraintno
for, while or comprehension inside the functionExamples
calltip_percentages([40.8, 7.2, 17.2, 0], [10.7, 2.55, 0, 1], [1, 1, 2, 1])returns[26.225490196078436, 35.41666666666667, 0, 0]
calltip_percentages([22.06, 5.1], [0, 1], [0, 1])returns[0, 19.607843137254903]
calltip_percentages([], [], [])returns[]