Search This Blog

Ashvini sharma.

Hello dosto! Welcome to my Blog . I am so happy to visit my blog. In this blog you can find your maximum information as like related to Coursera in, you find all quiz and assignment weekly as your course embedded.

Python data structures: Assignment 8.5

Post a comment.

Comments here for more information.........

Popular posts from this blog

Python data structures: assignment 7.1, python data structure: assignment 8.4, programming for everybody (python) assignment 5.2, coursera:web application technologies and django.

Image

Python data structures Chapter 6 Quiz

Image

  • Python »
  • 3.12.2 Documentation »
  • The Python Tutorial »
  • 5. Data Structures
  • Theme Auto Light Dark |

5. Data Structures ¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

5.1. More on Lists ¶

The list data type has some more methods. Here are all of the methods of list objects:

Add an item to the end of the list. Equivalent to a[len(a):] = [x] .

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .

Remove the first item from the list whose value is equal to x . It raises a ValueError if there is no such item.

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.

Remove all items from the list. Equivalent to del a[:] .

Return zero-based index in the list of the first item whose value is equal to x . Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Return the number of times x appears in the list.

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

Reverse the elements of the list in place.

Return a shallow copy of the list. Equivalent to a[:] .

An example that uses most of the list methods:

You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . [ 1 ] This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.

5.1.1. Using Lists as Stacks ¶

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

5.1.2. Using Lists as Queues ¶

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

5.1.3. List Comprehensions ¶

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

or, equivalently:

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

and it’s equivalent to:

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

List comprehensions can contain complex expressions and nested functions:

5.1.4. Nested List Comprehensions ¶

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

The following list comprehension will transpose rows and columns:

As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:

which, in turn, is the same as:

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The del statement ¶

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

del can also be used to delete entire variables:

Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.

5.3. Tuples and Sequences ¶

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple .

A tuple consists of a number of values separated by commas, for instance:

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing : the values 12345 , 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets ¶

Python also includes a data type for sets . A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

Similarly to list comprehensions , set comprehensions are also supported:

5.5. Dictionaries ¶

Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys , which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {} . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

5.6. Looping Techniques ¶

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

5.7. More on Conditions ¶

The conditions used in while and if statements can contain any operators, not just comparisons.

The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .

Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

5.8. Comparing Sequences and Other Types ¶

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

Table of Contents

  • 5.1.1. Using Lists as Stacks
  • 5.1.2. Using Lists as Queues
  • 5.1.3. List Comprehensions
  • 5.1.4. Nested List Comprehensions
  • 5.2. The del statement
  • 5.3. Tuples and Sequences
  • 5.5. Dictionaries
  • 5.6. Looping Techniques
  • 5.7. More on Conditions
  • 5.8. Comparing Sequences and Other Types

Previous topic

4. More Control Flow Tools

  • Report a Bug
  • Show Source
  • 90% Refund @Courses
  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

Related Articles

  • Solve Coding Problems
  • Queue in Python
  • Python Linked List
  • Python Data Structures
  • Hash Map in Python
  • Insert and delete at the beginning in Doubly Linked List in Python
  • Stack in Python
  • Heap queue (or heapq) in Python
  • Linked list using dstructure library in Python
  • Tree Traversal Techniques in Python
  • Heapq with custom predicate in Python
  • Stack and Queues in Python
  • SymPy | Subset.subset() in Python
  • Convert Python Code to a Software to Install on Windows Using Inno Setup Compiler
  • SymPy | Subset.prev_binary() in Python
  • How to check if a string is a valid keyword in Python?
  • SymPy | Subset.rank_binary() in Python
  • SymPy | Subset.size() in Python
  • SymPy | Subset.superset() in Python
  • Programming Paradigms in Python

Python Data Structures and Algorithms

This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with the help of good and well-explained examples and practice questions.

Python Data Structures and Algorithms

Python Lists are ordered collections of data just like arrays in other programming languages. It allows different types of elements in the list. The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly operation is inserting or deleting the element from the beginning of the List as all the elements are needed to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the preallocated memory becomes full.

Example: Creating Python List

List elements can be accessed by the assigned index. In python starting index of the list, a sequence is 0 and the ending index is (if N elements are there) N-1.

python-list-slicing

Example: Python List Operations

Python tuples are similar to lists but Tuples are immutable in nature i.e. once created it cannot be modified. Just like a List, a Tuple can also contain elements of various types.

In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. 

Note: To create a tuple of one element there must be a trailing comma. For example, (8,) will create a tuple containing 8 as the element.

Example: Python Tuple Operations

Python set is a mutable collection of data that does not allow any duplication. Sets are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on average. 

If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.

Set Implementation:

Internal Working of Set

Sets with Numerous operations on a single HashTable:

Internal Working of Set

Example: Python Set Operations

Frozen sets.

Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.

Example: Python Frozen set

Python Strings is the immutable array of bytes representing Unicode characters. Python does not have a character data type, a single character is simply a string with a length of 1.

Note: As strings are immutable, modifying a string will result in creating a new copy.

Python strings

Example: Python Strings Operations

Python dictionary is an unordered collection of data that stores data in the format of key:value pair. It is like hash tables in any other language with the time complexity of O(1). Indexing of Python Dictionary is done with the help of keys. These are of any hashable type i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a dictionary by using curly braces ({}) or dictionary comprehension.

Example: Python Dictionary Operations

A matrix is a 2D array where each element is of strictly the same size. To create a matrix we will be using the NumPy package .

Example: Python NumPy Matrix Operations

Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256.

Example: Python Bytearray Operations

Linked list.

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:

Linked List

A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts:

  • Pointer (Or Reference) to the next node

Example: Defining Linked List in Python

Let us create a simple linked list with 3 nodes.

Linked List Traversal 

In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list.

More articles on Linked List

  • Linked List Insertion
  • Linked List Deletion (Deleting a given key)
  • Linked List Deletion (Deleting a key at given position)
  • Find Length of a Linked List (Iterative and Recursive)
  • Search an element in a Linked List (Iterative and Recursive)
  • Nth node from the end of a Linked List
  • Reverse a linked list

>>> More

A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.

Stack in python

The functions associated with stack are:

  • empty() – Returns whether the stack is empty – Time Complexity: O(1)
  • size() – Returns the size of the stack – Time Complexity: O(1)
  • top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
  • push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
  • pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

More articles on Stack

  • Infix to Postfix Conversion using Stack
  • Prefix to Infix Conversion
  • Prefix to Postfix Conversion
  • Postfix to Prefix Conversion
  • Postfix to Infix
  • Check for balanced parentheses in an expression
  • Evaluation of Postfix Expression

As a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first.

Queue in Python

Operations associated with queue are:

  • Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1)
  • Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1)
  • Front: Get the front item from queue – Time Complexity: O(1)
  • Rear: Get the last item from queue – Time Complexity: O(1)

More articles on Queue

  • Implement Queue using Stacks
  • Implement Stack using Queues
  • Implement a stack using single queue

Priority Queue

Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties.

  • An element with high priority is dequeued before an element with low priority.
  • If two elements have the same priority, they are served according to their order in the queue.

heapq module in Python provides the heap data structure that is mainly used to represent a priority queue. The property of this data structure is that it always gives the smallest element (min heap) whenever the element is popped. Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest element each time. It supports the extraction and insertion of the smallest element in the O(log n) times.

Generally, Heaps can be of two types:

  • Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.
  • Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.

assignment 8 5 python data structures

More Articles on Heap

  • Binary Heap
  • K’th Largest Element in an array
  • K’th Smallest/Largest Element in Unsorted Array
  • Sort an almost sorted array
  • K-th Largest Sum Contiguous Subarray
  • Minimum sum of two numbers formed from digits of an array

Binary Tree

A tree is a  hierarchical data structure that looks like the below figure –

The topmost node of the tree is called the root whereas the bottommost nodes or the nodes with no children are called the leaf nodes. The nodes that are directly under a node are called its children and the nodes that are directly above something are called its parent.

A binary tree is a tree whose elements can have almost two children. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. A Binary Tree node contains the following parts.

  • Pointer to left child
  • Pointer to the right child

Example: Defining Node Class

Now let’s create a tree with 4 nodes in Python. Let’s assume the tree structure looks like below –

Example: Adding data to the tree

Tree traversal.

Trees can be traversed in different ways. Following are the generally used ways for traversing trees. Let us consider the below tree –

Depth First Traversals:

  • Inorder (Left, Root, Right) : 4 2 5 1 3
  • Preorder (Root, Left, Right) : 1 2 4 5 3
  • Postorder (Left, Right, Root) : 4 5 2 3 1

Algorithm Inorder(tree)

  • Traverse the left subtree, i.e., call Inorder(left-subtree)
  • Visit the root.
  • Traverse the right subtree, i.e., call Inorder(right-subtree)

Algorithm Preorder(tree)

  • Traverse the left subtree, i.e., call Preorder(left-subtree)
  • Traverse the right subtree, i.e., call Preorder(right-subtree)

Algorithm Postorder(tree)

  • Traverse the left subtree, i.e., call Postorder(left-subtree)
  • Traverse the right subtree, i.e., call Postorder(right-subtree)

Time Complexity –  O(n)

Breadth-First or Level Order Traversal

Level order traversal of a tree is breadth-first traversal for the tree. The level order traversal of the above tree is 1 2 3 4 5.

For each node, first, the node is visited and then its child nodes are put in a FIFO queue. Below is the algorithm for the same –

  • Create an empty queue q
  • temp_node = root /*start from root*/
  • print temp_node->data.
  • Enqueue temp_node’s children (first left then right children) to q
  • Dequeue a node from q

Time Complexity: O(n) 

More articles on Binary Tree

  • Insertion in a Binary Tree
  • Deletion in a Binary Tree
  • Inorder Tree Traversal without Recursion
  • Inorder Tree Traversal without recursion and without stack!
  • Print Postorder traversal from given Inorder and Preorder traversals
  • Find postorder traversal of BST from preorder traversal

Binary Search Tree

Binary Search Tree is a node-based binary tree data structure that has the following properties:

  • The left subtree of a node contains only nodes with keys lesser than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • The left and right subtree each must also be a binary search tree.

Binary Searcch Tree

The above properties of the Binary Search Tree provide an ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search for a given key.

Searching Element

  • Start from the root.
  • Compare the searching element with root, if less than root, then recurse for left, else recurse for right.
  • If the element to search is found anywhere, return true, else return false.

Insertion of a key 

  • Compare the inserting element with root, if less than root, then recurse for left, else recurse for right.
  • After reaching the end, just insert that node at left(if less than current) else right.

More Articles on Binary Search Tree

  • Binary Search Tree – Delete Key
  • Construct BST from given preorder traversal | Set 1
  • Binary Tree to Binary Search Tree Conversion
  • Find the node with minimum value in a Binary Search Tree
  • A program to check if a binary tree is BST or not

A graph is a nonlinear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes.

Graphs

In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}. The following two are the most commonly used representations of a graph.

Adjacency Matrix

Adjacency list.

Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. The adjacency matrix for an undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w. 

Vertices of Graph [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] Edges of Graph [(‘a’, ‘c’, 20), (‘a’, ‘e’, 10), (‘b’, ‘c’, 30), (‘b’, ‘e’, 40), (‘c’, ‘a’, 20), (‘c’, ‘b’, 30), (‘d’, ‘e’, 50), (‘e’, ‘a’, 10), (‘e’, ‘b’, 40), (‘e’, ‘d’, 50), (‘e’, ‘f’, 60), (‘f’, ‘e’, 60)] Adjacency Matrix of Graph [[-1, -1, 20, -1, 10, -1], [-1, -1, 30, -1, 40, -1], [20, 30, -1, -1, -1, -1], [-1, -1, -1, -1, 50, -1], [10, 40, -1, 50, -1, 60], [-1, -1, -1, -1, 60, -1]]

An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph. 

Adjacency List Representation of Graph

Graph Traversal

Breadth-first search or bfs.

Breadth-First Traversal for a graph is similar to Breadth-First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.

For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth-First Traversal of the following graph is 2, 0, 3, 1.

assignment 8 5 python data structures

Time Complexity: O(V+E) where V is the number of vertices in the graph and E is the number of edges in the graph.

Depth First Search or DFS

Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array.

  • Create a recursive function that takes the index of the node and a visited array.
  • Mark the current node as visited and print the node.
  • Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.

More articles on graph

  • Graph representations using set and hash
  • Find Mother Vertex in a Graph
  • Iterative Depth First Search
  • Count the number of nodes at given level in a tree using BFS
  • Count all possible paths between two vertices

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function . Using the recursive algorithms, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

What is the base condition in recursion?

In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. 

In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached.

How memory is allocated to different function calls in recursion?

When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues.

Let us take the example of how recursion works by taking a simple function. 

The memory stack has been shown in below diagram.

recursion

More articles on Recursion

  • Recursion in Python
  • Practice Questions for Recursion | Set 1
  • Practice Questions for Recursion | Set 2
  • Practice Questions for Recursion | Set 3
  • Practice Questions for Recursion | Set 4
  • Practice Questions for Recursion | Set 5
  • Practice Questions for Recursion | Set 6
  • Practice Questions for Recursion | Set 7

Dynamic Programming

Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when needed later. This simple optimization reduces time complexities from exponential to polynomial. For example, if we write simple recursive solution for Fibonacci Numbers, we get exponential time complexity and if we optimize it by storing solutions of subproblems, time complexity reduces to linear.

dynamic-programming

Tabulation vs Memoization

There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problem: 

  • Tabulation: Bottom Up
  • Memoization: Top Down

As the name itself suggests starting from the bottom and accumulating answers to the top. Let’s discuss in terms of state transition.

Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So,  we need to find the value of destination state i.e dp[n].

If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it the Bottom-Up approach as it is quite clear that we started our transition from the bottom base state and reached the topmost desired state.

Now, Why do we call it tabulation method?

To know this let’s first write some code to calculate the factorial of a number using bottom up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x.

Now, it is quite obvious that dp[x+1] = dp[x] * (x+1)

Memoization

Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP.

Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom-most base state.

Once again, let’s write the code for the factorial problem in the top-down fashion

tabulation-vs-memoization

More articles on Dynamic Programming

  • Optimal Substructure Property
  • Overlapping Subproblems Property
  • Fibonacci numbers
  • Subset with sum divisible by m
  • Maximum Sum Increasing Subsequence
  • Longest Common Substring

Searching Algorithms

Linear search.

  • Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
  • If x matches with an element, return the index.
  • If x doesn’t match with any of the elements, return -1.

Linear Search

The time complexity of the above algorithm is O(n). 

For more information, refer to Linear Search .

Binary Search

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

Binary Search

The time complexity of the above algorithm is O(log(n)). 

For more information, refer to Binary Search .

Sorting Algorithms

Selection sort.

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 

Flowchart of the Selection Sort: 

Selection Sort

Time Complexity: O(n 2 ) as there are two nested loops.

Auxiliary Space: O(1) 

Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

Illustration : 

bubble-sort

Time Complexity: O(n 2 )

Insertion Sort

To sort an array of size n in ascending order using insertion sort :

  • Iterate from arr[1] to arr[n] over the array.
  • Compare the current element (key) to its predecessor.
  • If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

Illustration:

insertion-sort

Time Complexity: O(n 2 ))

Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. 

Merge-Sort-Tutorial

Time Complexity: O(n(logn))

Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.

Always pick first element as pivot.

  • Always pick last element as pivot (implemented below)
  • Pick a random element as pivot.
  • Pick median as pivot.

The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time.

quicksort

Partition Algorithm

There can be many ways to do partition, following pseudo code adopts the method given in CLRS book. The logic is simple, we start from the leftmost element and keep track of index of smaller (or equal to) elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element. 

ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow the exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h th element is sorted.

Time Complexity:  O(n 2 ). 

Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Please Login to comment...

  • Python-Data-Structures
  • simranarora5sos
  • sagartomar9927
  • anandsummer111
  • Top 12 AI Testing Tools for Test Automation in 2024
  • 7 Best ChatGPT Plugins for Converting PDF to Editable Formats
  • Microsoft is bringing Linux's Sudo command to Windows 11
  • 10 Best AI Voice Cloning Tools to be Used in 2024 [Free + Paid]
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

swayam-logo

Programming, Data Structures And Algorithms Using Python

Note: This exam date is subjected to change based on seat availability. You can check final exam date on your hall ticket.

Page Visits

Course layout, books and references, instructor bio.

assignment 8 5 python data structures

Prof. Madhavan Mukund

Course certificate.

  • Assignment score = 25% of average of best 6 assignments out of the total 8 assignments given in the course. 
  • ( All assignments in a particular week will be counted towards final scoring - quizzes and programming assignments). 
  • Unproctored programming exam score = 25% of the average scores obtained as part of Unproctored programming exam - out of 100
  • Proctored Exam score =50% of the proctored certification exam score out of 100

assignment 8 5 python data structures

DOWNLOAD APP

assignment 8 5 python data structures

SWAYAM SUPPORT

Please choose the SWAYAM National Coordinator for support. * :

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

IMAGES

  1. Python Data Structures Assignment 8.5 Solution [Coursera]

    assignment 8 5 python data structures

  2. Data Structures in Python

    assignment 8 5 python data structures

  3. Python Tutorials: How to use Data Structures in Python

    assignment 8 5 python data structures

  4. Python Data Structures Cheat-sheet

    assignment 8 5 python data structures

  5. Python Data Structures: Built-in tools to manipulate data

    assignment 8 5 python data structures

  6. Day 1

    assignment 8 5 python data structures

VIDEO

  1. Assignment 8.5 PYHTON DATA STRUCTURES

  2. NPTEL: Programming , Data Structures and Algorithms Using Python Week 4 Quiz answer with proof(100%)

  3. NPTEL Programming, Data Structures and Algorithms using Python Programming Assignment 2 July-2023

  4. Data Structures And Algorithm in Python

  5. Python For Everybody Assignment 8.5

  6. Explaining Project Stem assignment 8 5 Code Practice

COMMENTS

  1. Python data structures: Assignment 8.5

    Solution:- fname =input ("Enter file name: ") fh = open (fname) count = 0 for line in fh: line = line.rstrip () if not line.startswith ('From '): continue words = line.split () print (words [1]) count += 1 print ("There were", count, "lines in the file with From as the first word") Coursera official website:

  2. Python Data Structures Assignment 8.5 Solution [Coursera ...

    Python Data Structures Assignment 8.5 Solution [Coursera] | Assignment 8.5 Python Data StructuresCoursera: Programming For Everybody Assignment 8.5 program s...

  3. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":".idea","path":".idea","contentType":"directory"},{"name":".gitignore","path":".gitignore ...

  4. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Week-4":{"items":[{"name":"Assignment8.4.py","path":"Week-4/Assignment8.4.py","contentType":"file"},{"name ...

  5. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":".idea","path":".idea","contentType":"directory"},{"name":"Assignment 10.2.py","path ...

  6. 5. Data Structures

    Data Structures 5.1. More on Lists 5.1.1. Using Lists as Stacks 5.1.2. Using Lists as Queues 5.1.3. List Comprehensions 5.1.4. Nested List Comprehensions 5.2. The delstatement 5.3. Tuples and Sequences 5.4. Sets 5.5. Dictionaries 5.6. Looping Techniques 5.7. More on Conditions 5.8. Comparing Sequences and Other Types Previous topic 4.

  7. Python Data Structures Course (UMich)

    This course will introduce the core data structures of the Python programming language. We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. This course will cover Chapters 6-10 of the textbook ...

  8. Common Python Data Structures (Guide)

    set: Your Go-to Set frozenset: Immutable Sets collections.Counter: Multisets Sets and Multisets in Python: Summary Stacks (LIFOs) list: Simple, Built-in Stacks collections.deque: Fast and Robust Stacks queue.LifoQueue: Locking Semantics for Parallel Computing

  9. Python Data Structure Exercise for Beginners

    The data structure is widely used to hold any data. To perform any programming tasks in Python, good knowledge of data structure is a must. Solve this exercise to have a good understanding of basic data structure in Python Also, Solve: Python List exercise Python Dictionary exercise Python Tuple exercise Python Set exercise

  10. Python Data Structures

    About Outcomes Modules Recommendations Testimonials Reviews What you'll learn Explain the principles of data structures & how they are used Create programs that are able to read and write data from files Store data as key/value pairs using Python dictionaries Accomplish multi-step tasks like sorting or looping using tuples Skills you'll gain

  11. Python Data Structures

    Tuple. Python Tuple is a collection of Python objects much like a list but Tuples are immutable in nature i.e. the elements in the tuple cannot be added or removed once created. Just like a List, a Tuple can also contain elements of various types. In Python, tuples are created by placing a sequence of values separated by 'comma' with or without the use of parentheses for grouping of the ...

  12. Python Data Structures: Lists, Dictionaries, Sets, Tuples (2023)

    Conclusions. Data structure is a fundamental concept in programming, which is required for easily storing and retrieving data. Python has four main data structures split between mutable (lists, dictionaries, and sets) and immutable (tuples) types. Lists are useful to hold a heterogeneous collection of related objects.

  13. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":".gitignore","path":".gitignore","contentType":"file"},{"name":"Assignment 2.3","path ...

  14. Python Data Structures and Algorithms

    This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with the help of good and well-explained examples and ...

  15. PYTHON DATA STRUCTURE (Assignment-8.5)- COURSERA

    About Press Copyright Contact us Creators Advertise Developers Terms Privacy Policy & Safety How YouTube works Test new features NFL Sunday Ticket Press Copyright ...

  16. Python Data Structures || Week 4

    0:00 / 1:40 Python Data Structures || Week 4 | Assignment 8.5 | Graded External Tool || Coursera Priya Vishwakarma 483 subscribers Subscribe Subscribed 8 Share Save 679 views 3 years...

  17. 4 Must-Know Python Data Structures

    Python has 4 built-in data structures: List Set Tuple Dictionary They all have different features in terms of storing and accessing data. These differences matter because what fits best for a particular task depends on them. How you can interact with or manipulate these data structures are also different. List

  18. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":"Assignment 10.2-checkpoint.ipynb","path":"Assignment 10.2-checkpoint.ipynb","contentType ...

  19. Programming, Data Structures And Algorithms Using Python

    As far as data structures are concerned, the course covers Python dictionaries as well as classes and objects for defining user defined datatypes such as linked lists and binary search trees. Students in any branch of mathematics/science/engineering, 1st year PREREQUISITES: School level mathematics.

  20. Coursera: 8.5 Assignment solution//Python data structures ...

    #circuitryproject# Coursera #python data structures# PythonCHAPTER :- PYTHON DATA STRUCTURESASSIGNMENT:- 👇👇👇👇Assignment:- 6.5 Solution 👇👇https://youtu...

  21. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Course_2_Python_Data_Structures":{"items":[{"name":"README.md","path":"Course_2_Python_Data_Structures/README.md ...

  22. NPTEL Programming Data Structures And Algorithms Using Python WEEK 8

    Programming Data Structures And Algorithms Using Python PROGRAMMING ASSIGNMENT 8 Answers,Programming Data Structures And Algorithms Using Python PROGRAMMING ...

  23. Python Data Structures Assignment 8.4 Solution [Coursera ...

    Python Data Structures Assignment 8.4 Solution [Coursera] | Assignment 8.4 Python Data StructuresCoursera: Programming For Everybody Assignment 8.4 program s...