Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Hands-On Data Structures and Algorithms with Python
Hands-On Data Structures and Algorithms with Python

Hands-On Data Structures and Algorithms with Python: Write complex and powerful code using the latest features of Python 3.7 , Second Edition

Arrow left icon
Profile Icon Dr. Basant Agarwal Profile Icon Benjamin Baka
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (13 Ratings)
eBook Oct 2018 398 pages 2nd Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Dr. Basant Agarwal Profile Icon Benjamin Baka
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (13 Ratings)
eBook Oct 2018 398 pages 2nd Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Hands-On Data Structures and Algorithms with Python

Python Data Types and Structures

In this chapter, we are going to examine Python data types in more detail. We have already introduced two data types, the string and list, str() and list(). However, these data types are not sufficient, and we often need more specialized data objects to represent/store our data. Python has various other standard data types that are used to store and manage data, which we will be discussing in this chapter. In addition to the built-in types, there are several internal modules that allow us to address common issues when working with data structures. First, we are going to review some operations and expressions that are common to all data types, and we will discuss more related to data types in Python.

This chapter's objectives are as follows:

  • Understanding various important built-in data types supported in Python 3.7
  • Exploring various additional...

Technical requirements

Built-in data types

Python data types can be divided into three categories: numeric, sequence, and mapping. There is also the None object that represents Null, or the absence of a value. It should not be forgotten that other objects such as classes, files, and exceptions can also properly be considered types; however, they will not be considered here.

Every value in Python has a data type. Unlike many programming languages, in Python you do not need to explicitly declare the type of a variable. Python keeps track of object types internally.

Python built-in data types are outlined in the following table:

Category

Name

Description

None

None

It is a null object.

Numeric

int

This is an integer data type.

float

This data type can store a floating-point number.

complex

It stores a complex number.

bool

It is Boolean type and returns True or...

None type

The None type is immutable. It is used as None to show the absence of a value; it is similar to null in many programming languages, such as C and C++. Objects return None when there is actually nothing to return. It is also returned by False Boolean expressions. None is often used as a default value in function arguments to detect whether a function call has passed a value or not.

Numeric types

Number types include integers (int), that is, whole numbers of unlimited range, floating-point numbers (float), complex numbers (complex), which are represented by two float numbers, and Boolean (bool) in Python. Python provides the int data type that allows standard arithmetic operators (+, -, * and / ) to work on them, similar to other programming languages. A Boolean data type has two possible values, True and False. These values are mapped to 1 and 0, respectively. Let's consider an example:

>>> a=4; b=5   # Operator (=) assigns the value to variable
>>>print(a, "is of type", type(a))
4 is of type
<class 'int'>
>>> 9/5
1.8
>>>c= b/a # division returns a floating point number
>>> print(c, "is of type", type(c))
1.25 is of type <class 'float'>
>>> c # No...

Representation error

It should be noted that the native double precision representation of floating-point numbers leads to some unexpected results. For example, consider the following:

>>> 1-0.9
0.09999999999999998
>>> 1-0.9==.1
False

This is a result of the fact that most decimal fractions are not exactly representable as a binary fraction, which is how most underlying hardware represents floating-point numbers. For algorithms or applications where this may be an issue, Python provides a decimal module. This module allows for the exact representation of decimal numbers and facilitates greater control of properties, such as rounding behavior, number of significant digits, and precision. It defines two objects, a Decimal type, representing decimal numbers, and a Context type, representing various computational parameters such as precision, rounding, and error handling...

Membership, identity, and logical operations

Membership operators (in and not in) test for variables in sequences, such as lists or strings, and do what you would expect; x in y returns True if an x variable is found in y. The is operator compares object identity. For example, the following snippet shows contrast equivalence with object identity:

>>> x=[1,2,3]
>>> y=[1,2,3]
>>> x==y # test equivalence
True
>>> x is y # test object identity
False
>>> x=y # assignment
>>> x is y
True

Sequences

Sequences are ordered sets of objects indexed by non-negative integers. Sequences include string, list, tuple, and range objects. Lists and tuples are sequences of arbitrary objects, whereas strings are sequences of characters. However, string, tuple, and range objects are immutable, whereas, the list object is mutable. All sequence types have a number of operations in common. Note that, for the immutable types, any operation will only return a value rather than actually change the value.

For all sequences, the indexing and slicing operators apply as described in the previous chapter. The string and list data types were discussed in detail in Chapter 1, Python Objects, Types, and Expressions. Here, we present some of the important methods and operations that are common to all of the sequence types (string, list, tuple, and range objects).

All sequences have the following...

Learning about tuples

Tuples are immutable sequences of arbitrary objects. A tuple is a comma-separated sequence of values; however, it is common practice to enclose them in parentheses. Tuples are very useful when we want to set up multiple variables in one line, or to allow a function to return multiple values of different objects. Tuple is an ordered sequence of items similar to the list data type. The only difference is that tuples are immutable; hence, once created they cannot be modified, unlike list. Tuples are indexed by integers greater than zero. Tuples are hashable, which means we can sort lists of them and they can be used as keys to dictionaries.

We can also create a tuple using the built-in function: tuple(). With no argument, this creates an empty tuple. If the argument to tuple() is a sequence then this creates a tuple of elements of that sequence. It is important...

Beginning with dictionaries

In Python, the Dictionary data type is one of the most popular and useful data types. A dictionary stores the data in a mapping of key and value pair. Dictionaries are mainly a collection of objects; they are indexed by numbers, strings, or any other immutable objects. Keys should be unique in the dictionaries; however, the values in the dictionary can be changed. Python dictionaries are the only built-in mapping type; they can be thought of as a mapping from a set of keys to a set of values. They are created using the {key:value} syntax. For example, the following code can be used to create a dictionary that maps words to numerals using different methods:

>>>a= {'Monday':1,'Tuesday':2,'Wednesday':3} #creates a dictionary 
>>>b =dict({'Monday':1 , 'Tuesday': 2, 'Wednesday'...

Sorting dictionaries

If we want to do a simple sort on either the keys or values of a dictionary, we can do the following:

>>> d = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} 
>>> sorted(list(d))
['five', 'four', 'one', 'six', 'three', 'two']
>>> sorted(list(d.values()))
[1, 2, 3, 4, 5, 6]

Note that the first line in the preceding code sorts the keys alphabetically and the second line sorts the values in order of the integer value.

The sorted() method has two optional arguments that are of interest: key and reverse. The key argument has nothing to do with the dictionary keys, but rather is a way of passing a function to the sort algorithm to determine the sort order. For example, in the following code, we use the...

Dictionaries for text analysis

A common use of dictionaries is to count the occurrences of like items in a sequence; a typical example is counting the occurrences of words in a body of text. The following code creates a dictionary where each word in the text is used as a key and the number of occurrences as its value. This uses a very common idiom of nested loops. Here we are using it to traverse the lines in a file in an outer loop and the keys of a dictionary on the inner loop:

def wordcount(fname):  
try:
fhand=open(fname)
except:
print('File can not be opened')
exit()

count=dict()
for line in fhand:
words=line.split()
for word in words:
if word not in count:
count[word]=1
else:
count[word]+=1
return(count)

This will return a dictionary with an element for...

Sets

Sets are unordered collections of unique items. Sets are themselves mutable—we can add and remove items from them; however, the items themselves must be immutable. An important distinction with sets is that they cannot contain duplicate items. Sets are typically used to perform mathematical operations such as intersection, union, difference, and complement.

Unlike sequence types, set types do not provide any indexing or slicing operations. There are two types of set objects in Python, the mutable set object and the immutable frozenset object. Sets are created using comma-separated values within curly braces. By the way, we cannot create an empty set using a={}, because this will create a dictionary. To create an empty set, we write either a=set() or a=frozenset().

Methods and operations of sets are described in the following table:

Method

Description

len...

Modules for data structures and algorithms

In addition to the built-in types, there are several Python modules that we can use to extend the built-in types and functions. In many cases, these Python modules may offer efficiency and programming advantages that allow us to simplify our code.

So far, we have looked at the built-in datatypes of strings, lists, sets, and dictionaries as well as the decimal and fraction modules. They are often described by the term Abstract Data Types (ADTs). ADTs can be considered mathematical specifications for the set of operations that can be performed on data. They are defined by their behavior rather than their implementation. In addition to the ADTs that we have looked at, there are several Python libraries that provide extensions to the built-in datatypes. These will be discussed in the following section.

...

Summary

In the last two chapters, we presented the language features and data types of Python. We looked at the built-in data types and some internal Python modules, most notably the collections module. There are also several other Python modules that are relevant to the topic of this book, but rather than examining them separately, their use and functionality should become self-evident as we begin using them. There are also a number of external libraries, for example, SciPy.

In the next chapter, we will introduce the basic theory and techniques of algorithm design.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand the analysis and design of fundamental Python data structures
  • Explore advanced Python concepts such as Big O notation and dynamic programming
  • Learn functional and reactive implementations of traditional data structures

Description

Data structures allow you to store and organize data efficiently. They are critical to any problem, provide a complete solution, and act like reusable code. Hands-On Data Structures and Algorithms with Python teaches you the essential Python data structures and the most common algorithms for building easy and maintainable applications. This book helps you to understand the power of linked lists, double linked lists, and circular linked lists. You will learn to create complex data structures, such as graphs, stacks, and queues. As you make your way through the chapters, you will explore the application of binary searches and binary search trees, along with learning common techniques and structures used in tasks such as preprocessing, modeling, and transforming data. In the concluding chapters, you will get to grips with organizing your code in a manageable, consistent, and extendable way. You will also study how to bubble sort, selection sort, insertion sort, and merge sort algorithms in detail. By the end of the book, you will have learned how to build components that are easy to understand, debug, and use in different applications. You will get insights into Python implementation of all the important and relevant algorithms.

Who is this book for?

This book is for developers who want to learn data structures and algorithms in Python to write complex and flexible programs. Basic Python programming knowledge is expected.

What you will learn

  • Understand object representation, attribute binding, and data encapsulation
  • Gain a solid understanding of Python data structures using algorithms
  • Study algorithms using examples with pictorial representation
  • Learn complex algorithms through easy explanation, implementing Python
  • Build sophisticated and efficient data applications in Python
  • Understand common programming algorithms used in Python data science
  • Write efficient and robust code in Python 3.7

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 31, 2018
Length: 398 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788991933
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Oct 31, 2018
Length: 398 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788991933
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 102.97
Hands-On Data Structures and Algorithms with Python
€32.99
Python 3 Object-Oriented Programming
€34.99
Learn Python Programming
€34.99
Total 102.97 Stars icon

Table of Contents

15 Chapters
Python Objects, Types, and Expressions Chevron down icon Chevron up icon
Python Data Types and Structures Chevron down icon Chevron up icon
Principles of Algorithm Design Chevron down icon Chevron up icon
Lists and Pointer Structures Chevron down icon Chevron up icon
Stacks and Queues Chevron down icon Chevron up icon
Trees Chevron down icon Chevron up icon
Hashing and Symbol Tables Chevron down icon Chevron up icon
Graphs and Other Algorithms Chevron down icon Chevron up icon
Searching Chevron down icon Chevron up icon
Sorting Chevron down icon Chevron up icon
Selection Algorithms Chevron down icon Chevron up icon
String Algorithms and Techniques Chevron down icon Chevron up icon
Design Techniques and Strategies Chevron down icon Chevron up icon
Implementations, Applications, and Tools Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(13 Ratings)
5 star 15.4%
4 star 30.8%
3 star 15.4%
2 star 15.4%
1 star 23.1%
Filter icon Filter
Top Reviews

Filter reviews by




Readomatic Jun 07, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I like this data science book with Python.
Amazon Verified review Amazon
Mike Cross Nov 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Looking for clear, concise information, well presented, then this is for you.
Amazon Verified review Amazon
DT Nov 23, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I just received the book. It looked fine initially, but once I opened it, the binding ripped, and the first page fell off. The binding is fragile and weak, so I don’t think the book will serve for a long time.I will make sure to update the content when I’m done with it.EDIT: I finished the book. It was something.First of all, the book has a problem with the code snippets. Some of them have basic syntax issues, like “import library assomething” (they forgot the space). Others are just indentation issues, like on page 135 (see for yourself through the “look inside” feature on Amazon). Truly makes me wonder if the reviewers really did read the book.The biggest issue for me was the complete absence of material on balanced trees. Instead, there are two paragraphs teasing you with information you might have had, like an explanation of AA treas and scapegoat trees, but no answer is provided at all. Check for yourself, page 174. I believe it would have been more useful to teach AA treas in the book about Data STRUCTURES & Algorithms rather than Data Visualization with matplotlib.Now, the good part is that it is a nice introduction, after all. I found the explanation of stacks & queues well-written and would have appreciated the material if I did not know that already. I would recommend this book as a first thing to read, but certainly not something to advance your knowledge base.
Amazon Verified review Amazon
Vlad Bezden Jan 25, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Good book if you need to refresh knowledge of DS and Algorithms. It doesn't go to the deep explanation. Good examples to learn from. The book says it uses Python 3.7, but I think there is nothing that can prevent run those examples on Python 3.x. Overall I like this book, but I would not recommend it if you are starting to learn DS.
Amazon Verified review Amazon
David A. May 26, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Hands-on is about as close as you can get to Sedgewick in Python. Now if it could only be expanded to be Numerical Recipes in Python ...
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.