python logo


Category: tutorials

python regex

Regular expressions are essentially a highly specialized programming language embedded inside Python that empowers you to specify the rules for the set of possible strings that you want to match.

In Python you need the re module for regular expressions usage. The grammar overview is on the bottom of this page.

Related course:
Python Programming Bootcamp: Go from zero to hero

The Match function


The match function is defined as:

re.match(pattern, string)

The parameters are:

If you want to match a string to a numberic sequence of exactly five, you can use this code:

Parameters Description
pattern a regular expression
string the input string
#!/usr/bin/python
import re

input = raw_input("Enter an input string:")
m = re.match('\d{5}\Z',input)

if m:
print("True")
else:
print("False")

Example outputs:

Email validation regex


We can use the same function to validate email address. The grammar rules are seen in re.compile and in the grammar table.

String Match
12345 True
12358 True
55555 True
123 False
123K5 False
5555555 False
#!/usr/bin/python
import re

input = raw_input("Enter an input string:")
m = re.match('[^@][email protected][^@]+\.[^@]+',input)

if m:
print("True")
else:
print("False")

The Search Function


The search function is defined as:

re.search(pattern, string)

The parameters are:

To search if an e-mail address is in a string:

Parameter Description
pattern a regular expression, defines the string to be searched
string the search space
#!/usr/bin/python
import re

input = "Contact me by [email protected] or at the office."

m = re.search('[^@][email protected][^@]+\.[^@]+',input)

if m:
print("String found.")
else:
print("Nothing found.")

Regular Expression Examples


A few examples of regular expressions:

Regular Expression Grammar


Overview of the regex grammar:
Example Regex
IP address (([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))
Email [^@][email protected][^@]+\.[^@]+
Date MM/DD/YY (\d+/\d+/\d+)
Integer (positive) (?<![-.])\b[0-9]+\b(?!\.[0-9])
Integer [+-]?(?<!\.)\b[0-9]+\b(?!\.[0-9])
Float (?<=>)\d+.\d+|\d+
Hexadecimal \s–([0-9a-fA-F]+)(?:–)?\s

quantum computing python

So we want to make a quantum application with Python, but since we do not own any quantum computer we need to have a simulator first. Simulation will not have the same performance as an actual quantum computer but we will be able to run applications. We have a choice from three simulators: PyQu , QuTip and Qitensor. We decided to pick QuTip as it has a very large code base and as it has the most recent changes. PyQu hasn’t been updated since 2010 and Qitensor since a year or so.

Related course:
Quantum Computing: An Applied Approach

Installing
We use a Unix machine in this tutorial, but you should be fine with any other operating system. Install using:

sudo add-apt-repository ppa:jrjohansson/qutip-releases
sudo apt-get update
sudo apt-get install python-qutip

We then start Python from the command line and type the commands listed below ( >>> ).

Regex Description
\d Matches any decimal digit; this is equivalent to the class [0-9]
\D Matches any non-digit character; this is equivalent to the class [^0-9].
\s Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].
\S Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].
\w Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].
\W Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].
\Z Matches only at end of string
[..] Match single character in brackets
[^..] Match any single character not in brackets
. Match any character except newline
$ Match the end of the string
* Match 0 or more repetitions
+ 1 or more repetitions
{m} Exactly m copies of the previous RE should be matched.
| Match A or B. A|B
? 0 or 1 repetitions of the preceding RE
[a-z] Any lowercase character
[A-Z] Any uppercase character
[a-zA-Z] Any character
[0-9] Any digit
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; from qutip import *
&gt;&gt;&gt; about()

QuTiP: Quantum Toolbox in Python
Copyright (c) 2011 and later.
Paul D. Nation &amp; Robert J. Johansson

QuTiP Version: 3.1.0
Numpy Version: 1.8.2
Scipy Version: 0.13.3
Cython Version: 0.20.1post0
Matplotlib Version: 1.3.1
Fortran mcsolver: True
scikits.umfpack: False
Python Version: 2.7.6
Platform Info: Linux (i686)
Installation path: /usr/lib/python2.7/dist-packages/qutip

This indicates that Qutip has been correctly installed.

The Quantum data structure
In quantum systems we need a data structure that is capable of encapsulating the properties of a quantum operator and ket/bra vectors, we use the Qobj data structure for that. In other words, to effectively simulate a quantum application we need to use the appropriate data structure. Consider the example below:

#!/usr/bin/env python
from qutip import *
from scipy import *

r = rand(4, 4)
print Qobj(r)


And execute with:

python quantum.py

This will output the quantum object:

Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isherm = False
Qobj data =
[[ 0.25529374 0.75548592 0.85680266 0.1438253
[ 0.75070138 0.68628867 0.97435624 0.77396516]
[ 0.69819458 0.81714756 0.2604015 0.69051901]
[ 0.0898242 0.05292657 0.49134431 0.4433644 ]]

If you want to specify user input yourself you could use:

#!/usr/bin/env python
from qutip import *
from scipy import *

x = array([[1],[2],[3],[4],[5]])
q = Qobj(x)
print q

This quantum object will simply hold your user given data:

Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[ 1.]
[ 2.]
[ 3.]
[ 4.]
[ 5.]]

Quantum states and operators
A quantum system is not a simple two-level system, it has multiple states. QuTip includes some predefined states and quantum operators which are listed here.

Qubits and operators
We create a Qubit to hold data. Th Qubit is the quantum analogue of the classical bit. Unlike traditional bits, the qubit can be in a superposition of both states at the same time, a property which is fundamental to quantum computing. The code below will create a qubit:

#!/usr/bin/env python
from qutip import *
from scipy import *

spin = basis(2, 0)
print spin

You can now apply quantum system operators on the qubit:

#!/usr/bin/env python
from qutip import *
from scipy import *

spin = basis(2, 0)
print sigmam() * spin
print sigmap() * spin

Combining qubits
To describe the states of two coupled qubits we need to take the tensor product of the state vectors for each of the system components. Let us try that:

#!/usr/bin/env python
from qutip import *
from scipy import *

q1 = basis(2, 0)
q2 = basis(2,0)

print q1
print q2
print tensor(q1,q2)

The output we will get is:

Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket
Qobj data =
[[ 1.]
[ 0.]]
Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket
Qobj data =
[[ 1.]
[ 0.]]
Quantum object: dims = [[2, 2], [1, 1]], shape = [4, 1], type = ket
Qobj data =
[[ 1.]
[ 0.]
[ 0.]
[ 0.]]

Whats next?
We have built some very simply quantum applications using this simple introduction. Perhaps you want to create an actually useful application, if so you could study more about quantum computing and complete the tutorial at http://qutip.org/docs/latest/index.html