Advertisement
makispaiktis

Chaining Arrays

Apr 29th, 2021 (edited)
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. '''
  2. Given a list of words, determine whether the words can be chained to form a circle.
  3. A word X can be placed in front of another word Y in a circle if the last character of X
  4. is same as the first character of Y.
  5. For example, the words ['chair', 'height', 'racket', touch', 'tunic'] can form the following circle:
  6. chair --> racket --> touch --> height --> tunic --> chair
  7. '''
  8.  
  9. from itertools import permutations
  10.  
  11. # FUNCTION 1
  12. def createPermutations(array):
  13.     N = len(array)
  14.     permsIndices = permutations(list(range(N)))
  15.     # Example: (0,1,2) (0,2,1) (1,0,2) (1,2,0) (2,0,1) (2,1,0)
  16.     arrangements = list()
  17.     for perm in permsIndices:
  18.         arrangement = list()
  19.         for j in range(len(perm)):
  20.             arrangement.append(array[perm[j]])
  21.         arrangements.append(arrangement)
  22.     return arrangements
  23.  
  24.  
  25. # FUNCTION 2
  26. def chain(array):
  27.     arrangements = createPermutations(array)
  28.     isThereSolution = False
  29.     solution = list()
  30.     for arrangement in arrangements:
  31.         M = len(arrangement)
  32.         flag = True
  33.         for i in range(M-1):
  34.             if arrangement[i][len(arrangement[i]) - 1] != arrangement[i+1][0]:
  35.                 flag = False
  36.                 break
  37.         if flag == True:
  38.             isThereSolution = True
  39.             solution = arrangement
  40.             break
  41.     if isThereSolution == False:
  42.         print("There is no solution to this problem")
  43.     else:
  44.         return solution
  45.  
  46.  
  47. # MAIN FUNCTION
  48. array1 = ['chair', 'height', 'racket', 'touch', 'tunic']
  49. print(array1)
  50. print(chain(array1))
  51. print()
  52. array2 = ["hello", "friend", "old", "dad", "fear", "olaf", "dnipro", "elf" ,"dare"]
  53. print(array2)
  54. print(chain(array2))
  55. print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement