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 - Recursion
Python - Recursion
Recursion allows a function to call itself. Fixed steps of code get executed again and again for new values. We also have to set criteria for deciding when the recursive call ends. In the below example we see a recursive approach to the binary search. We take a sorted pst and give its index range as input to the recursive function.
Binary Search using Recursion
We implement the algorithm of binary search using python as shown below. We use an ordered pst of items and design a recursive function to take in the pst along with starting and ending index as input. Then, the binary search function calls itself till find the searched item or concludes about its absence in the pst.
Example
def bsearch(pst, idx0, idxn, val): if (idxn < idx0): return None else: midval = idx0 + ((idxn - idx0) // 2) # Compare the search item with middle most value if pst[midval] > val: return bsearch(pst, idx0, midval-1,val) else if pst[midval] < val: return bsearch(pst, midval+1, idxn, val) else: return midval pst = [8,11,24,56,88,131] print(bsearch(pst, 0, 5, 24)) print(bsearch(pst, 0, 5, 51))
Output
When the above code is executed, it produces the following result −
2 NoneAdvertisements