Book Image

Applying Math with Python - Second Edition

By : Sam Morley
Book Image

Applying Math with Python - Second Edition

By: Sam Morley

Overview of this book

The updated edition of Applying Math with Python will help you solve complex problems in a wide variety of mathematical fields in simple and efficient ways. Old recipes have been revised for new libraries and several recipes have been added to demonstrate new tools such as JAX. You'll start by refreshing your knowledge of several core mathematical fields and learn about packages covered in Python's scientific stack, including NumPy, SciPy, and Matplotlib. As you progress, you'll gradually get to grips with more advanced topics of calculus, probability, and networks (graph theory). Once you’ve developed a solid base in these topics, you’ll have the confidence to set out on math adventures with Python as you explore Python's applications in data science and statistics, forecasting, geometry, and optimization. The final chapters will take you through a collection of miscellaneous problems, including working with specific data formats and accelerating code. By the end of this book, you'll have an arsenal of practical coding solutions that can be used and modified to solve a wide range of practical problems in computational mathematics and data science.
Table of Contents (13 chapters)

Creating networks in Python

To solve the multitude of problems that can be expressed as network problems, we need a way of creating networks in Python. For this, we will make use of the NetworkX package and the routines and classes it provides to create, manipulate, and analyze networks.

In this recipe, we’ll create an object in Python that represents a network and add nodes and edges to this object.

Getting ready

As we mentioned in the Technical requirements section, we need the NetworkX package to be imported under the nx alias. We can do this using the following import statement:

import networkx as nx

How to do it...

Follow these steps to create a Python representation of a simple graph:

  1. We need to create a new Graph object that will store the nodes and edges that constitute the graph:
    G = nx.Graph()
  2. Next, we need to add the nodes for the network using the add_node method:
    G.add_node(1)
    G.add_node(2)
  3. To avoid calling this method repetitively...