📚 The CoCalc Library - books, templates and other resources
License: OTHER
Generator functions
Code examples from Think Complexity, 2nd edition.
Copyright 2019 Allen Downey, MIT License
Exercise: In the book I wrote a version of random_pairs
that violates Ned’s recommendation to “abstract your iteration”:
Write a better version of this function that uses all_pairs
rather than copying and modifying it.
Exercise: Write a function called random_tree
that takes a number of nodes, n
, as a parameter and builds an undirected graph by starting with a single node, adding one node at a time, and connecting each new node to one existing node. You can use any of the functions in Python’s random
module.
Bonus: Read the various equivalent definitions of tree and then write a function called is_tree
that takes a graph and returns True
if the graph is a tree.
Exercise: Write a function called all_triangles
that takes an undirected graph as a parameter and returns all triangles, where a triangle is a collection of three nodes that are connected to each other (regardless of whether they are also connected to other nodes). Your solution can be an ordinary function that returns a list of tuples, or a generator function that yields tuples. It does not have to be particularly efficient. It’s OK if your solution finds the same triangle more than once, but as a bonus challenge, write a solution that avoids it.