aboutsummaryrefslogtreecommitdiff
path: root/tanken.py
blob: 303e3b38a519e62a895b5a9cfc8a170d60690627 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/env python3


# cost should be given in cents
def tanken(drives, cost, service_charge=0):
    passengers = {}
    distance = 0.
    drives = [d.split(' ') for d in drives]

    for d in drives:
        try:
            d[0] = int(d[0])
        except:
            return None, "Lines have to start with the driven distance!"

        # calculate overall distance
        distance += d[0]

        # collect distances per passenger
        for p in d[1:]:
            if p not in passengers:
                passengers[p] = {
                    "distance": d[0],
                    "cost": 0,
                    "service_charge": 0
                }
            else:
                passengers[p]["distance"] += d[0]

    # calculate cost per kilometer
    if distance <= 0:
        return None, "Driven distance must be greater than 0!"

    c = cost / distance

    for d in drives:
        # calculate cost per drive split among passengers
        c_d = int(c * d[0] / (len(d) - 1))
        for p in d[1:]:
            passengers[p]["cost"] += c_d

        # calculate service charge per drive split among passengers
        sc_d = int(service_charge * d[0] / (len(d) - 1))
        for p in d[1:]:
            passengers[p]["service_charge"] += sc_d

    return passengers, None