-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcost_prorating.py
More file actions
79 lines (59 loc) · 2.44 KB
/
cost_prorating.py
File metadata and controls
79 lines (59 loc) · 2.44 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import math
def cost_prorating(cost:float, weights:list[float]):
if cost < 0:
raise ValueError("Cost must be non-negative.")
if not weights:
raise ValueError("Weights list cannot be empty.")
if not all(w >= 0 for w in weights):
raise ValueError("All weights must be non-negative.")
total = sum(weights)
if total == 0:
if cost == 0:
return [0] * len(weights)
else:
raise ValueError("Total weight is zero, cannot distribute positive cost.")
prorated_cost = [0] * len(weights)
remainders = [0] * len(weights)
current_allocation_total = 0
for i in range(len(weights)):
if weights[i] == 0:
prorated_cost[i] = 0
elif weights[i] > 0:
exact_share = (cost * weights[i]) / total
prorated_cost[i] = math.floor(exact_share)
remainders[i] = exact_share - prorated_cost[i]
unassigned_cost = cost - sum(prorated_cost)
return prorated_cost
## Set your own values for cost and weights or comment for the examples below
try:
cost = float(input("Enter the total cost to prorate: "))
weights = []
print("Enter weights (enter 'done' when finished)")
while True:
weight_input = input("Enter a weight (or 'done' to finish): ")
if weight_input.lower() == 'done':
break
weights.append(float(weight_input))
result = cost_prorating(cost, weights)
print(f"Prorated costs: {result}")
except ValueError as e:
print(f"Error: {e}")
# cost1 = 100
# weights1 = [10, 20, 70]
# print(f"Cost: {cost1}, Weights: {weights1}, Prorated: {prorate_cost(cost1, weights1)}")
# # Expected: [10, 20, 70] (Exact shares are integers)
# cost2 = 100
# weights2 = [1, 1, 1]
# print(f"Cost: {cost2}, Weights: {weights2}, Prorated: {prorate_cost(cost2, weights2)}")
# # Expected: [34, 33, 33] or similar. Exact = 33.33... Remainders all 0.33...
# # Floor = [33, 33, 33]. Sum = 99. Remainder units = 1.
# # Give 1 unit to one with largest remainder (they are equal, first one gets it). Output: [34, 33, 33]
# cost3 = 7
# weights3 = [1, 2, 3, 0]
# print(f"Cost: {cost3}, Weights: {weights3}, Prorated: {prorate_cost(cost3, weights3)}")
# # Total weight = 6.
# # Exact: [1.166, 2.333, 3.5, 0]
# # Floor: [1, 2, 3, 0]. Sum = 6. Remainder units = 1.
# # Fractions: [0.166, 0.333, 0.5, -1]. Sorted indices by fraction: 2, 1, 0, 3
# # Give 1 unit to index 2.
# # Expected: [1, 2, 4, 0]