pandas: A row rule without apply

A shipping rule could be written with apply(axis=1), but the vectorised form is df["zone"].map(base) + 2 * (df["weight"] - 1).clip(lower=0). Compute the same costs.

What to build

A program that prices parcels and adds up the cost.

Requirements

  • The cost is the zone's base price (A: 5, B: 8, C: 12) plus 2 for every kilogram over 1 kg, counting fractions of a kilogram.
  • Print ID,COST for each parcel with the cost to two decimals, then total T with two decimals.

Input

Line 1: n. Then n lines ID,ZONE,WEIGHT.

Output

n + 1 lines.

Constraints

1 ≤ n ≤ 1000; zones are A, B or C; 0 ≤ weight ≤ 100.

Example

Input:

3
p1,A,0.5
p2,B,3
p3,C,1

Output:

p1,5.00
p2,12.00
p3,12.00
total 29.00

Why it works

Clipping the extra weight at 0 stops light parcels from getting a discount, and a dictionary lookup per zone plus arithmetic on the weight is exactly what map and clip do for a whole column at once.

Examples

Example 1 · Input
3
p1,A,0.5
p2,B,3
p3,C,1
Expected output
p1,5.00
p2,12.00
p3,12.00
total 29.00
Example 2 · Input
1
p1,A,2.5
Expected output
p1,8.00
total 8.00

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Look the base price up in a dictionary by zone.

Hint 2

The extra weight is max(0, weight − 1), like clip(lower=0).

Solution

Show one correct solution (try it yourself first)
n = int(input())
base = {"A": 5, "B": 8, "C": 12}
total = 0
for _ in range(n):
    pid, zone, weight = input().split(",")
    cost = base[zone] + 2 * max(0, float(weight) - 1)
    total += cost
    print(f"{pid},{cost:.2f}")
print(f"total {total:.2f}")

Lesson: Method chaining, apply and performance →