This is a simple Python implementation. Note the global variables p and a should in general be re-generated each pass. p is any prime and a is the primitive root of p.

import random
# Public information
p = 157 # Prime
a = 5   # Primitive root
class Agent():
    def __init__(self, name): = name
    def GenerateN(self):
        self.N = random.randint(1, 1000)
        return self.N
    def ComputeM(self):
        M = (a ** self.N) % p
        print, "computes M to be", M
        return M
    def ComputeK(self, M):
        K = (M ** self.N) % p
        print, "computes K to be", K
        return K
Bob = Agent("Bob")
Alice = Agent("Alice")
for i in range(10):
    print "Run", i
    MA = Alice.ComputeM()
    MB = Bob.ComputeM()
    KA = Alice.ComputeK(MB)
    KB = Bob.ComputeK(MA)
    if KA != KB:
        print "RESULT: Error computing key on run", i
        print "RESULT: Key exchange complete, generated key was", KA