I have a list that contains 3 lists.
locations = [[(1,1), (3,3), (6,7)], [(5,2), (3,4), (2,3)], [(3,7), (3,5), (7,7)]]
The first list contains, the location of alphabet A
The second list contains, the location of alphabet B
The third list contains, the location of alphabet C
My task is to find them together where they sit close to each other. It's a word puzzle problem. Thus, alphabet B could sit up, down, right, or left of the A. The C has to be the same direction as the B to A.
In this case, the solution will be a new list with their locations. The answer is -
puzzle_solved_location = [(3,3), (3,4), (3,5)]
I was thinking about using the nested list. But there will be some problems where some words with 10 or 15 letters will be given. I need one program that will solve any word puzzle with any number of letters.
Currently, I'm trying a nested loop but it won't work for longer length word and the codes need to be edited each time for new words. The code is given below-
A= [(1,1), (3,3), (6,7)]
B= [(5,2), (3,4), (2,3)]
C= [(3,7), (3,5), (7,7)]
for row_A,column_A in A:
for row_B,column_B in B:
if (row_A+1==row_B or row_A-1==row_B or row_A==row_B)
and (column_A+1==column_B or column_A-1 ==column_B or column_A==column_B):
for row_C,column_C in C:
x_co, y_co = row_B-row_A, column_B-column_A
if row_B+x_co ==row_C and column_B+y_co ==column_C:
print (row_A, column_A, row_B, column_B, row_C, column_C)
The result gives the location of the solved puzzle.
>> 3 3 3 4 3 5
Is there any other way to do that without writing if statement for each alphabet?
You can use a list comprehension to iterate through the 4 possible directions and the possible starting points (of A
's) to see which ones would result in finding the corresponding points in the rest of the locations:
[[(ax + dx * i, ay + dy * i) for i in range(len(locations))] for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)) for ax, ay in locations[0] if all((ax + dx * i, ay + dy * i) in c for i, c in enumerate(locations[1:], 1))]
This returns:
[[(3, 3), (3, 4), (3, 5)]]
Note that this returns a list of lists of tuples because there could potentially be more than one solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.