Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
Kernel: Python 3

Generator functions

Code examples from Think Complexity, 2nd edition.

Copyright 2019 Allen Downey, MIT License

%matplotlib inline import networkx as nx import numpy as np # TODO: remove this when NetworkX is fixed from warnings import simplefilter import matplotlib.cbook simplefilter("ignore", matplotlib.cbook.mplDeprecation)

Exercise: Write a function named next_two_digraph that takes a sequence of nodes and returns a NetworkX DiGraph object that represents a directed graph where each node is connected to its successor, and the successor of its successor, wrapping around to the beginning.

# Solution goes here
nodes = list(range(10)) dig = next_two_digraph(nodes)
nx.draw_circular(dig, node_color='C0', node_size=1000, with_labels=True)
dig = next_two_digraph([1, 2, 3, 4]) dig.edges()

Exercise: Suppose you have a Python list of integers called sample where each element of the list is the number of friends of a randomly-chosen person in a social network.

Write a few lines of code to do the following:

  • Make a Pmf object that represents the distribution of the values in sample.

  • Compute the number of people in the sample with exactly 2 friends.

  • Compute the average degree in the network.

sample = np.random.zipf(1.8, size=100)
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here

Exercise: Continuing the previous example, write a few lines of code to do the following:

  • Make a Cdf object that represents the distribution of the values in sample.

  • Compute the number of people in the sample with strictly less than 10 friends.

  • Compute the 75th percentile of the number of friends, that is, the quantile that corresponds to the cumulative probability 0.75.

sample = np.random.zipf(1.8, size=1000)
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here

Bonus: Use the Cdf to compute the median and interquartile range (which is the difference between the 75th and 25th percentiles).

# Solution goes here
# Solution goes here