2.5 Chapter 2 Homework

This part is based on Professor YY’s module 2 assignment of measuring the friendship paradox.

You can find the homework here.

The following task prompts are based on the above homework. You can use them to keep practicing coding in Python.

2.5.1 Task 2-1: Networkx Basics

  • 2-1-1. Import networkx as nx.

  • 2-1-2. Set both random seed and numpy random seed to be 42.

  • 2-1-3. Create a networkx graph named my_first_graph which contains three nodes and 2 edges, i.e., (1,2) and (2,3).

  • 2-1-4. In the codes you used for Task 2-3: Which element is a class? Which is an object? Which is a method?

  • 2-1-5. Print the number of nodes in my_first_graph. Hint : len()

  • 2-1-6. Print the degree of Node 2, in the format of “Node 2’s degree: m.”

  • 2-1-7. Print Node 2’s neighbors, in the format of “Node 2’s neighbors: [m, n, p, q].” Hint : neighbor() or neighbors()?

    • Note: When you directly return Node 2’s neighbors, the result will be dict_keyiterator at 0x10ec84860, which is an iterator object. Try to solve this problem either by a for loop or through a list comprehension
  • 2-1-8. Print all the node’s neighbors in my_first_graph in the form of “Node 1’s neighbors: [m, n, p, q]” using a python for loop.

    • Hint : The for loop will iterate over the list returned by the nodes() function.
  • 2-1-9. Print all the edges in my_first_graph.

  • 2-1-10. Plot my_first_graph. Hint : .draw()

2.5.2 Task 2-2: Friendship paradox example

  • 2-2-1. Create a star graph with 20 nodes, and plot it.

  • 2-2-2. Calculate the average degree of the star graph you just created. Use a for loop to calculate the total degrees.

    • Hint : You might find the operator of += useful for 2-2-2. a += b is short for a = a + b.
  • 2-2-3. Do the same thing using numpy’s mean function which takes in a list and returns the mean of this list.

I do not understand Professor YY’s note here: “so if you print a numpy float it will display differently than if you printed a python float, which is why we get the intentional truncation of the value when displayed.”
  • 2-2-4. Get star_graph’s average degree using networkx’s info() function.

2.5.3 Task 2-3: Generating random and scale-free networks

  • 2-3-1. Generate a random network with 20 nodes and a connection probability of 0.3. Hint : erdos_renyi_graph.

  • 2-3-2. Generate a scale-free network with 20 nodes with each new node having three edges to attach to existing nodes. Hint : barabasi_albert_graph()

2.5.4 Task 2-4: Homework by Professor YY

Answer Q1 - Q4 as explained by Professor YY.