Last active
March 15, 2021 22:10
-
-
Save dimkoug/8b8d4f6423bb6a192a14de4bf13e756d to your computer and use it in GitHub Desktop.
Critical path method algorithm python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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_critical_path(data): | |
critical_path = [] | |
for activity in data: | |
predecessors = activity['predecessors'] | |
if not predecessors: | |
es = 0 | |
ef = activity['duration'] + es | |
elif predecessors: | |
ef_list = [d['ef'] for d in data if d['activity'] in predecessors] | |
es = max(ef_list) | |
ef = es + activity['duration'] | |
activity['es'] = es | |
activity['ef'] = ef | |
for index, dactivity in enumerate(reversed(data)): | |
durations = [] | |
if index == 0: | |
dactivity['lf'] = dactivity['ef'] | |
else: | |
items = [ditem for ditem in data if dactivity['activity'] in ditem['predecessors']] | |
durations = [] | |
for ditem in items: | |
durations.append(ditem['ls']) | |
dactivity['lf'] = min(durations) | |
dactivity['ls'] = dactivity['lf'] - dactivity['duration'] | |
dactivity['slack'] = dactivity['lf'] - dactivity['ef'] | |
for item in data: | |
if item['slack'] == 0: | |
critical_path.append(item['activity']) | |
return critical_path | |
critical_path = calculate_critical_path(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