Python

Python

Explore python code snippets and tutorials

Python

Critical Path Method Algorithm Python

<p>The provided code defines the <code>data</code> list containing information about various activities and their dependencies. The <code>calculate_critical_path</code> function then calculates the critical path for these activities and prints the result …

python
 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
import json
data = [
    {
        'activity': 'a',
        "duration": 3,
        "predecessor": []
    },
    {
        'activity': 'b',
        "duration": 4,
        "predecessor": ['a']
    },
    {
        'activity': 'c',
        "duration": 2,
        "predecessor": ['a']
    },
    {
        'activity': 'd',
        "duration": 5,
        "predecessor": ['b']
    },
    {
        'activity': 'e',
        "duration": 1,
        "predecessor": ['c']
    },
    {
        'activity': 'f',
        "duration": 2,
        "predecessor": ['c']
    },
    {
        'activity': 'g',
        "duration": 4,
        "predecessor": ['d', 'e']
    },
    {
        'activity': 'h',
        "duration": 3,
        "predecessor": ['f', 'g']
    }
]


def calculate_critical_path(data):
    for activity in data:
        es = 0
        predecessors = activity['predecessor']

        if predecessors:
            es = max(d['ef'] for d in data if d['activity'] in predecessors)

        ef = es + activity['duration']
        activity['es'] = es
        activity['ef'] = ef
        activity['ls'] = 0
        activity['lf'] = 0
        activity['slack'] = 0

    # Calculate ls, lf, and slack in reverse order of activities
    max_lf = data[-1]['ef']  # Initialize max_lf with the last activity's ef
    for activity in reversed(data):
        successors = [d for d in data if activity['activity'] in d['predecessor']]
        lf = max_lf if not successors else min(d['ls'] for d in successors)
        activity['lf'] = lf
        activity['ls'] = lf - activity['duration']
        activity['slack'] = activity['lf'] - activity['ef']
        max_lf = activity['lf']  # Update max_lf for the next iteration

    return data


critical_path = calculate_critical_path(data)
print(json.dumps(critical_path, indent=4, sort_keys=True))
Python

Add json field to postgres with python

<p>The provided Python code connects to a PostgreSQL database, creates a table with a JSON column, inserts a JSON object into the table, and then closes the connection to the …

python
 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
import psycopg2
from psycopg2 import Error
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import json
try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="mydatabase")
    connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

    # Create a cursor to perform database operations
    commands = (
        """drop table examplejson """,
        """create table examplejson(
            id serial primary key not null,
            data JSON
            );""",
    )
    cursor = connection.cursor()

    for command in commands:
        cursor.execute(command)
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")
    pitem = {
        "name": 'pc',
        "category": 'desktop pc'
    }
    cursor.execute("INSERT INTO examplejson(data) VALUES (%s)", (json.dumps(pitem),))
    connection.commit()

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)

finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")