from itertools import *; e= enumerate ; f= lambda l:[ [ [ ' ' ] *( max ( j for k, ( j, c) in o[ 1 :] ) -i) +l[ k] [ :i] +[ c.upper ( ) ] +l[ k] [ i+1 :] for k, ( i, c) in o[ 1 :] ] for p in product( *[ list ( e( w) ) for w in l] ) for o in permutations( list ( e( p) ) ) if [ c for k, ( i, c) in o[ 1 :] ] == l[ o[ 0 ] [ 0 ] ] ] [ 0 ]
tests= [
[ [ 't' , 'o' , 'g' , 'e' , 't' , 'h' , 'e' , 'r' ] , [ 't' , 'e' , 'a' , 'm' ] , [ 'e' , 'v' , 'e' , 'r' , 'y' , 'o' , 'n' , 'e' ] , [ 'a' , 'c' , 'h' , 'i' , 'e' , 'v' , 'e' , 's' ] , [ 'm' , 'o' , 'r' , 'e' ] ] ,
[ [ 'a' , 'a' , 'a' ] , [ 'a' , 'a' , 'a' ] , [ 'a' , 'a' , 'a' ] , [ 'a' , 'a' , 'a' ] ] ,
[ [ 'a' , 'a' , 'a' ] , [ 'a' , 'a' , 'a' ] , [ 'a' , 'a' , 'b' ] , [ 'b' , 'a' , 'a' ] ] ,
[ [ 'l' , 'i' , 'v' , 'e' ] , [ 'e' , 'v' , 'e' , 'r' , 'y' ] , [ 'l' , 'o' , 'v' , 'e' ] , [ 'v' , 'e' , 'r' , 'y' ] , [ 'o' , 'h' , 'i' , 'o' ] ] ,
[ [ 'c' , 'o' , 'w' ] , [ 'o' , 'f' ] , [ 'f' , 'o' , 'x' ] ] ,
[ [ 'l' , 'a' , 't' , 'e' ] , [ 'b' , 'a' , 'l' , 'l' , 'r' , 'o' , 'o' , 'm' ] , [ 'a' , 'n' , 'v' , 'i' , 'l' ] , [ 't' , 'o' ] , [ 'h' , 'e' , 'a' , 'd' ] ]
]
for test in tests:
print '\n ' .join ( '' .join ( r) for r in f( test ) )
print
ZnJvbSBpdGVydG9vbHMgaW1wb3J0KjtlPWVudW1lcmF0ZTtmPWxhbWJkYSBsOltbWycgJ10qKG1heChqIGZvciBrLChqLGMp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