+ indep. WoS citations

Python and Networks -- Class notes -- 2016-02-16

1.  Lists (hello2.py)

L = [0, 1, 2, 3]
K = range(4)
print L

L.append(4)
print L

num = L.pop(-1)

print "num = %d" % num
print "List after pop: ", L

num = L.pop(-2)

print "num = %d" % num
print "List after pop: ", L

# passing by reference
M = ["a", L, "b"]
print "M = ", M
L.append("x")
print "M = ", M

# new reference, data at the old address that was passed into "M" will not change
L = ["x", "y"]
print "M = ", M

# copying
G = ["a", L[:], "b"]
print "G = ", G

# try again
Z = ["alma", "korte"]
X = ["piskota", Z, "pite"]
print "X = ", X
Z.append("szilva")
print "X = ", X

2.  Functions: basic syntax

def hello(L):
        print L

hello(["alma", "korte"])

def hello2(L):
        print L[0] + " " + L[1]

hello2(["alma", "korte"])

3.  Generate a random graph

Also called: Erdos-Renyi network

import random

# Erdos-Renyi graph generator
# Works good if e << n^2
# n nodes, e links
def er(n, e, linkList):
        if (e > n * (n - 1.0) / 10):
                print "er: link number too high"
                return

        while (len(linkList) < e):
                nodePair = []
                nodePairStr = ""
                while True:
                        # the two nodes
                        nodePair = sorted(random.sample(range(n), 2), key = int)
                        nodePairStr = str(nodePair[0]) + " " + str(nodePair[1])

                        # exit "while" if this is a new link
                        if not nodePairStr in linkList:
                                break
                linkList.append(nodePairStr)

linkList = []
er(2000, 10, linkList)
print linkList