Python Data Structure and Algorithms Tutorial
Python Data Structure & Algorithms Useful Resources
Selected Reading
- Python - Algorithm Justifications
- Python - Amortized Analysis
- Python - Algorithm Classes
- Python - Big-O Notation
- Python - Algorithm Analysis
- Python - Graph Algorithms
- Python - Searching Algorithms
- Python - Sorting Algorithms
- Python - Backtracking
- Python - Recursion
- Python - Divide and Conquer
- Python - Algorithm Design
- Python - Graphs
- Python - Heaps
- Python - Search Tree
- Python - Binary Tree
- Python - Hash Table
- Python - Advanced Linked list
- Python - Dequeue
- Python - Queue
- Python - Stack
- Python - Linked Lists
- Python - Maps
- Python - Sets
- Python - Matrix
- Python - 2-D Array
- Python - Dictionary
- Python - Tuples
- Python - Lists
- Python - Arrays
- Python - DS Environment
- Python - DS Introduction
- Python - DS Home
Python Data Structure & Algorithms Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python - Backtracking
Python - Backtracking
Backtracking is a form of recursion. But it involves choosing only option out of any possibipties. We begin by choosing an option and backtrack from it, if we reach a state where we conclude that this specific option does not give the required solution. We repeat these steps by going across each available option until we get the desired solution.
Below is an example of finding all possible order of arrangements of a given set of letters. When we choose a pair we apply backtracking to verify if that exact pair has already been created or not. If not already created, the pair is added to the answer pst else it is ignored.
Example
def permute(pst, s): if pst == 1: return s else: return [ y + x for y in permute(1, s) for x in permute(pst - 1, s) ] print(permute(1, ["a","b","c"])) print(permute(2, ["a","b","c"]))
Output
When the above code is executed, it produces the following result −
[ a , b , c ] [ aa , ab , ac , ba , bb , bc , ca , cb , cc ]Advertisements