Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Given a list of words, determine whether the words can be chained to form a circle.
- A word X can be placed in front of another word Y in a circle if the last character of X
- is same as the first character of Y.
- For example, the words ['chair', 'height', 'racket', touch', 'tunic'] can form the following circle:
- chair --> racket --> touch --> height --> tunic --> chair
- '''
- from itertools import permutations
- # FUNCTION 1
- def createPermutations(array):
- N = len(array)
- permsIndices = permutations(list(range(N)))
- # Example: (0,1,2) (0,2,1) (1,0,2) (1,2,0) (2,0,1) (2,1,0)
- arrangements = list()
- for perm in permsIndices:
- arrangement = list()
- for j in range(len(perm)):
- arrangement.append(array[perm[j]])
- arrangements.append(arrangement)
- return arrangements
- # FUNCTION 2
- def chain(array):
- arrangements = createPermutations(array)
- isThereSolution = False
- solution = list()
- for arrangement in arrangements:
- M = len(arrangement)
- flag = True
- for i in range(M-1):
- if arrangement[i][len(arrangement[i]) - 1] != arrangement[i+1][0]:
- flag = False
- break
- if flag == True:
- isThereSolution = True
- solution = arrangement
- break
- if isThereSolution == False:
- print("There is no solution to this problem")
- else:
- return solution
- # MAIN FUNCTION
- array1 = ['chair', 'height', 'racket', 'touch', 'tunic']
- print(array1)
- print(chain(array1))
- print()
- array2 = ["hello", "friend", "old", "dad", "fear", "olaf", "dnipro", "elf" ,"dare"]
- print(array2)
- print(chain(array2))
- print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement