Program to find out the total number of characters to be changed to fix a misspelled word in Python

PythonServer Side ProgrammingProgramming

Suppose we are given a list of cities and a list of roads that connect each other. The list 'cities' contain the name of cities that a tour bus visits in order. In the list 'roads' the roads are listed in a (source, destination) order meaning there is a one-way road from source to destination. Now, there is a problem that some city names in the list 'cities' may be misspelled. We have to correct such misspelled city names by changing the minimum number of characters. We return the number of characters changed as output.

So, if the input is like cities = ["HWH", "DLI", "BGL"], roads = [["HWH", "DLI"],["DLI", "BCT"], ["BCT", "HWH"]], then the output will be 2.

The misspelled city name in cities is 'BGL'. The correct name would be 'BCT'. So, too correct the name in cities we have to change 2 characters.

To solve this, we will follow these steps −

  • Define a function diff() . This will take a, b
    • return total difference in characters between a and b
  • size := size of cities
  • arr := a new map
  • junctions := a new set from each source city in roads
  • for each j in junctions, do
    • arr[j] := diff(cities[0], j)
  • for i in range 1 to size, do
    • nxt := a new map
    • for each r1, r2 in roads, do
      • if r1 in present in arr, then
        • cost := arr[r1] + diff(cities[i], r2)
        • if r2 is not present in nxt or cost < nxt[r2], then
          • nxt[r2] := cost
    • arr := nxt
  • return minimum of all values in arr

Example

Let us see the following implementation to get better understanding −

def diff(a, b):
   return sum(x != y for x, y in zip(a, b))

def solve(cities, roads):
   size = len(cities)
   arr = dict()
   junctions = set(r[0] for r in roads)
   for j in junctions:
      arr[j] = diff(cities[0], j)
   for i in range(1, size):
      nxt = dict()
      for r1, r2 in roads:
         if r1 in arr:
            cost = arr[r1] + diff(cities[i], r2)
            if r2 not in nxt or cost < nxt[r2]:
               nxt[r2] = cost
      arr = nxt
   return min(arr.values())

print(solve(["HWH", "DLI", "BGL"], [["HWH", "DLI"],["DLI", "BCT"],
["BCT", "HWH"]]))

Input

["HWH", "DLI", "BGL"], [["HWH", "DLI"],["DLI", "BCT"], ["BCT",
"HWH"]]

Output

2
raja
Updated on 19-Oct-2021 11:46:14

Advertisements