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
R$80 R$196.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
R$80 R$196.99
Paperback
R$245.99
Subscription
Free Trial
Renews at R$50p/m
Arrow left icon
Profile Icon Dr. Basant Agarwal Profile Icon Benjamin Baka
Arrow right icon
R$80 R$196.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
R$80 R$196.99
Paperback
R$245.99
Subscription
Free Trial
Renews at R$50p/m
eBook
R$80 R$196.99
Paperback
R$245.99
Subscription
Free Trial
Renews at R$50p/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
R$50 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
R$500 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 R$25 each
Feature tick icon Exclusive print discounts
R$800 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 R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 759.97
Hands-On Data Structures and Algorithms with Python
R$245.99
Python 3 Object-Oriented Programming
R$256.99
Learn Python Programming
R$256.99
Total R$ 759.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

Most Recent
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
Most Recent

Filter reviews by




Amazon Customer Oct 10, 2022
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
There are simply too many typos. If you are a beginner, there is a good chance of being misguided by the information.
Amazon Verified review Amazon
vivek Nov 07, 2021
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Print quality is poor. Has a few mistakes.
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
Daniele Nov 20, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This book offers a nice overview of data structures and algorithms.While the content might be good, there is a general sloppiness in the book that makes it hard to read: typos and mistakes cost time to be respectively detected and unlearnt by the reader. I would definitely not suggest this.I would have given three stars, but a book with words like 'hands-on' and 'python' in the title cannot write code with the wrong indentation. It is not only ugly, but it is also wrong (meaning that many of the examples provided by the book would simply crash if ran exactly as they are presented).
Amazon Verified review Amazon
Dylan Wilson Oct 22, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I have read through and worked through good computer science books. This is not one of them. As shown above, the copyediting is absolutely horrendous. Precisely the same sentence is repeated in a following paragraph, which was obviously meant to be deleted. The book will state that there is a following example code snippet or illustration with none to be found.Some of the information is just blatantly wrong/backwards. For example, the book states that a While loop continues until a Boolean condition is true. This is the opposite of the truth. While loops continue executing while its Boolean criteria is true, i.e. until it is false. The lack of useful examples is astounding. The provided example code snippets are not well-explained, and some of it is not pertinent at all.Overall, don't waste your money on this book. It presents a complicated, technical subject matter in an error-ridden and convoluted fashion.
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.