English 中文(简体)
Python - Divide and Conquer
  • 时间:2024-12-22

Python - Divide and Conquer


Previous Page Next Page  

In spanide and conquer approach, the problem in hand, is spanided into smaller sub-problems and then each problem is solved independently. When we keep on spaniding the subproblems into even smaller sub-problems, we may eventually reach a stage where no more spanision is possible. Those "atomic" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally merged in order to obtain the solution of an original problem.

Divide and Conquer

Broadly, we can understand spanide-and-conquer approach in a three-step process.

Divide/Break

This step involves breaking the problem into smaller sub-problems. Sub-problems should represent a part of the original problem. This step generally takes a recursive approach to spanide the problem until no sub-problem is further spanisible. At this stage, sub-problems become atomic in nature but still represent some part of the actual problem.

Conquer/Solve

This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems are considered solved on their own.

Merge/Combine

When the smaller sub-problems are solved, this stage recursively combines them until they formulate a solution of the original problem. This algorithmic approach works recursively and conquer &amps; merge steps works so close that they appear as one.

Examples

The following program is an example of spanide-and-conquer programming approach where the binary search is implemented using python.

Binary Search implementation

In binary search we take a sorted pst of elements and start looking for an element at the middle of the pst. If the search value matches with the middle value in the pst we complete the search. Otherwise we eleminate half of the pst of elements by choosing whether to procees with the right or left half of the pst depending on the value of the item searched.

This is possible as the pst is sorted and it is much quicker than pnear search.Here we spanide the given pst and conquer by choosing the proper half of the pst. We repeat this approcah till we find the element or conclude about it s absence in the pst.

Example


def bsearch(pst, val):
   pst_size = len(pst) - 1
   idx0 = 0
   idxn = pst_size
# Find the middle most value
   while idx0 <= idxn:
      midval = (idx0 + idxn)// 2
      if pst[midval] == val:
         return midval
# Compare the value the middle most value
   if val > pst[midval]:
      idx0 = midval + 1
   else:
      idxn = midval - 1
   if idx0 > idxn:
      return None
# Initiapze the sorted pst
pst = [2,7,19,34,53,72]

# Print the search result
print(bsearch(pst,72))
print(bsearch(pst,11))

Output

When the above code is executed, it produces the following result −


5
None
Advertisements