Skip to content

Instantly share code, notes, and snippets.

@dimkoug
Created April 27, 2025 08:19
Show Gist options
  • Save dimkoug/fc181f29e8061f3dac55fff7cdcbc14f to your computer and use it in GitHub Desktop.
Save dimkoug/fc181f29e8061f3dac55fff7cdcbc14f to your computer and use it in GitHub Desktop.
Python Critical path calculation
import json
data = [
{
'activity': 'a',
"duration": 3,
"predecessors": []
},
{
'activity': 'b',
"duration": 4,
"predecessors": ['a']
},
{
'activity': 'c',
"duration": 2,
"predecessors": ['a']
},
{
'activity': 'd',
"duration": 5,
"predecessors": ['b']
},
{
'activity': 'e',
"duration": 1,
"predecessors": ['c']
},
{
'activity': 'f',
"duration": 2,
"predecessors": ['c']
},
{
'activity': 'g',
"duration": 4,
"predecessors": ['d', 'e']
},
{
'activity': 'h',
"duration": 3,
"predecessors": ['f', 'g']
}
]
def calculate_cpm(data):
"""
Optimized Critical Path Method (CPM) calculation.
"""
# Build quick lookup for activities
activity_lookup = {activity['activity']: activity for activity in data}
# Step 1: Forward Pass
for activity in data:
es = 0
for pred in activity['predecessors']:
pred_ef = activity_lookup[pred]['ef']
es = max(es, pred_ef)
activity['es'] = es
activity['ef'] = es + activity['duration']
# Step 2: Build successors
successors = {activity['activity']: [] for activity in data}
for activity in data:
for pred in activity['predecessors']:
successors[pred].append(activity['activity'])
# Step 3: Backward Pass
for activity in reversed(data):
if not successors[activity['activity']]:
activity['lf'] = activity['ef']
else:
successor_ls = [activity_lookup[succ]['ls'] for succ in successors[activity['activity']]]
activity['lf'] = min(successor_ls)
activity['ls'] = activity['lf'] - activity['duration']
activity['slack'] = activity['lf'] - activity['ef']
# Step 4: Critical Path
critical_path = [activity['activity'] for activity in data if activity['slack'] == 0]
print(f"Critical Path: {critical_path}")
return data
critical_path = calculate_cpm(data)
print(json.dumps(critical_path, indent=4, sort_keys=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment