06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

110 Dictionaries<br />

10.3 Aliasing and copying<br />

Because dictionaries are mutable, you need <strong>to</strong> be aware of aliasing. Whenever two<br />

variables refer <strong>to</strong> the same object, changes <strong>to</strong> one affect the other.<br />

If you want <strong>to</strong> modify a dictionary and keep a copy of the original, use the copy<br />

method. For example, opposites is a dictionary that contains pairs of opposites:<br />

>>> opposites = {’up’: ’down’, ’right’: ’wrong’, ’true’: ’false’}<br />

>>> alias = opposites<br />

>>> copy = opposites.copy()<br />

alias and opposites refer <strong>to</strong> the same object; copy refers <strong>to</strong> a fresh copy of the<br />

same dictionary. If we modify alias, opposites is also changed:<br />

>>> alias[’right’] = ’left’<br />

>>> opposites[’right’]<br />

’left’<br />

If we modify copy, opposites is unchanged:<br />

>>> copy[’right’] = ’privilege’<br />

>>> opposites[’right’]<br />

’left’<br />

10.4 Sparse matrices<br />

In Section 8.14, we used a list of lists <strong>to</strong> represent a matrix. That is a good choice<br />

for a matrix <strong>with</strong> mostly nonzero values, but consider a sparse matrix like this<br />

one:<br />

0 0 0 1 0<br />

0 0 0 0 0<br />

0 2 0 0 0<br />

0 0 0 0 0<br />

0 0 0 3 0<br />

The list representation contains a lot of zeroes:<br />

matrix = [ [0,0,0,1,0],<br />

[0,0,0,0,0],<br />

[0,2,0,0,0],<br />

[0,0,0,0,0],<br />

[0,0,0,3,0] ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!