#Given an array of equal-length strings, 
#check if it is possible to rearrange the strings in such a way that after the rearrangement 
#the strings at consecutive positions would differ by exactly one character.

#Example

#For inputArray = ["aba", "bbb", "bab"], the output should be
#stringsRearrangement(inputArray) = false;
#For inputArray = ["ab", "bb", "aa"], the output should be
#stringsRearrangement(inputArray) = true.

import random

def stringsRearrangement(inputArray):

	long = len(inputArray)
	palabra = len(inputArray[0])
	#Make a copy
	copyia = list(inputArray)
	#lista = [ sorted(list(inputArray[i])) for i in range(long)]

	inputArray = sorted(inputArray)

	#If =1 printing else no.
	printing = 0
	#print(inputArray)
	#print("Palabras: ",long, " Long de las palabras: ",palabra)

	# For all the words except the last one..
	rand = 1
	while True:
		#First word 
		i = 0
		if printing == 1:
			input("Press Enter to continue...")
			print("Choosed the word: ",inputArray[i])
			print (inputArray)
			print ("Looping over :",len(range(i+1,long)),' words.')
		#Pick the i-esimth word
		for k in range(i+1,long):
			if printing == 1:
				print("Compared with: ",inputArray[k])
			resul = len( [ True for j in range(palabra) if list(inputArray[i])[j] != list(inputArray[k])[j]] )
			if printing == 1:	
				print("They difer by one word?: (so,dim=1)", resul)
			if resul == 1: 
				#It can not be 0 beacuse it cant be the same word
				#There is a match
				#Change to another word in the chain but, before eliminate the word s[i] from the list and move s[k] to the beginning
				if printing == 1:
					print("There was a match")
				if long == 2:
					if printing == 1:
						print("There was a complete match, no more words in the list to match with: ",inputArray)
					return True
				if printing == 1:
					print ("Eliminate word ",inputArray[i], ' from the list')
				del inputArray[i]
				if printing == 1:
					print("Move the match ",inputArray[k-1], ' to the beggining')
				inputArray.insert(0, inputArray.pop(k-1))
				#As I eliminate the 0th element, the match is in the index k-1
				long = long - 1
				if printing == 1:
					print("New array dim = dim-1",long)
					print ("So..", inputArray)
					print("Changing to the next word..")
				break
			else:
				if printing == 1:
					print("There was NOT a match")
					print("Changing to another word to compare ",inputArray[i])
				if k==(long-1):
					if rand <= len(copyia):
						if printing == 1:
							print("Reshuffling!!")
						rand = rand + 1
						random.shuffle(copyia)
						inputArray = list(copyia)
						long = len(copyia)
					else:
						if printing == 1:
							print("No word found to match... exit with False")
						return False