Answer to Question #292208 in Python for Anino

Question #292208

Imagine a collection of nuts and bolts that are all together in one pile on a table. Describe, in pseudocode, how you would find all matching pairs of nuts and bolts. You need to find one solution for each of the problem-solving approaches given below. For each of your solution, determine how many comparisons of pairs of nuts and bolts you might have to make in the best- and worst- case scenario. You can assume that there are complete pairs, no single nuts or bolts, and that for each bolt, there is exactly one nut that fits. Describe a solution to the nuts and bolts problem (in pseudocode) using a Brute Force Approach.

1
Expert's answer
2022-02-01T06:22:54-0500
from typing import List

# Method used to print array
def printArray(arr: List[str]) -> None:
   for i in range(6):
      print(" {}".format(arr[i]), end=" ")
   print()

def partition(arr: List[str], low: int, high: int, pivot: str) -> int:
   i = low
   j = low
   while j < high:
      if (arr[j] < pivot):
         arr[i], arr[j] = arr[j], arr[i]
         i += 1
      elif (arr[j] == pivot):
         arr[j], arr[high] = arr[high], arr[j]
         j -= 1
      j += 1
   arr[i], arr[high] = arr[high], arr[i]
   return i

# this function is for sorting
def matchPairs(nuts: List[str], bolts: List[str], low: int, high: int) -> None:
   if (low < high):

      pivot = partition(nuts, low, high, bolts[high])

      partition(bolts, low, high, nuts[pivot])


      matchPairs(nuts, bolts, low, pivot - 1)
      matchPairs(nuts, bolts, pivot + 1, high)

# Driver code
if __name__ == "__main__":

   nuts = ['@', '#', '$', '%', '^', '&']
   bolts = ['$', '%', '&', '^', '@', '#']

   matchPairs(nuts, bolts, 0, 5)
   print("Matched nuts and bolts are : ")
   printArray(nuts)
   printArray(bolts)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS