繁体   English   中英

从字母中获取所有单词组合和路径

[英]get all words combinations and path from letters arry

我创建了一个 boogle 游戏,我需要构建一个接收输入的函数:字母板(列表列表)、合法单词列表和整数 n。

该函数必须返回所有 n 长度的有效单词轨道。 例如 n = 3 那么该函数必须返回三长板上的所有路径,这些路径实际上是有效的单词。

我编写了一个代码,在特定示例中返回必须返回的三个路由中的一个路由。

输入:

board1 = [['Q', 'O', 'Q', 'Q'],
                 ['D', 'O', 'G', 'Q'],
                 ['Q', 'O', 'Q', 'Q'],
                 ['Q', 'Q', 'Q', 'Q']]
word_dict = {'DOG': True}
n = 3
board = Board(board1)
length_n_paths(3, board, word_dict)

我的输出:

[((1, 0), (1, 1), (1, 2))]

想要的输出:

[[(1, 0), (0, 1), (1, 2)], [(1, 0), (1, 1), (1, 2)], [(1, 0), (2, 1), (1, 2)]]

我使用了一个组合,首先找到长度为n的字母的所有可能组合,然后我通过一个坐标坐标,根据它前面的坐标检查每个坐标是否在有效位置,然后我检查是否来自字母组合的单词是单词列表中的单词。 如果是这样 - 我将在列表中返回它的路径以及其他合法单词路径。

我的代码:

direct_lst=['Up','Down','Right','Left','Up_right','Up_left','Down_right','Down_left']

class Board:
    def __init__(self, board):
        self.board = board


    def get_board_coordinate(self):

        cord_lst = []
        row = len(self.board)
        col = len(self.board[0])
        for i in range(row):
            for j in range(col):
                cord_lst.append((i, j))
        return cord_lst

    def possible_directions(self, coordinate, next_coordinate):




        y, x = coordinate
        directions_funcs = {
            # A dictionary that matches between a letter and the direction of the desired search
            'Up': (y - 1, x),
            'Down': (y + 1, x),
            'Right': (y, x + 1),
            'Left': (y, x - 1),
            'Up_right': (y - 1, x + 1),
            'Up_left': (y - 1, x - 1),
            'Down_right': (y + 1, x + 1),
            'Down_left': (y + 1, x + 1)
        }
        it_ok = False
        for direction in direct_lst:
            if directions_funcs[direction] == next_coordinate:
                it_ok = True
        return it_ok




def is_valid_path(board, path, words):

    word = board.board[path[0][0]][path[0][1]]
    board_coordinates = board.get_board_coordinate()
    for cord in range(len(path)-1):
        if path[cord] in board_coordinates and path[cord+1] in board_coordinates:
            if not board.possible_directions(path[cord], path[cord + 1]):
                return None
            else:
                word += board.board[path[cord + 1][0]][path[cord + 1][1]]
        else:
            return None
    if word in set(words):
        return word
import itertools

def create_dict(board, n):
    new_dict = dict()
    row = len(board.board)
    col = len(board.board[0])
    for i in range(row):
        for j in range(col):
            new_dict[(i, j)] = board.board[i][j]
        result_list = list(map(list, itertools.combinations(new_dict.items(), n)))
    return result_list



def coordinates_lst_and_str_lst(board, n):

    combine = create_dict(board, n)

    all_cord_dic = dict()
    for lst in combine:
        is_it_ok = True
        cord_lst = []
        str_l = ""
        for i in range(n):

            cord_lst.append(lst[i][0])
            str_l += lst[i][1]
            try:
                if not board.possible_directions(lst[i][0], lst[i + 1][0]):
                    is_it_ok = False
                    break
            except IndexError:
                break
        if is_it_ok:

            all_cord_dic[tuple(cord_lst)] = str_l
            all_cord_dic[tuple(cord_lst)[::-1]] = str_l[::-1]
    return all_cord_dic

def length_n_paths(n, board, words):
    possible_words = coordinates_lst_and_str_lst(board, n)

    my_dict = {key:val for key, val in possible_words.items() if val in words}
    return list(my_dict.keys())

我认为问题出在组合中,但我不知道如何解决。 我很乐意提供任何帮助。

调试后,很明显结果possible_words不包含键(1, 0), (0, 1), (1, 2) ,所以这就解释了为什么它不是答案的一部分——所以问题变成了为什么不t 调用coordinates_lst_and_str_lst()生成该元组(以及另一个“缺失”的元组)

如果在coordinates_lst_and_str_lst _lst_and_str_lst 中构造combine后中断,您会发现[((1, 0), 'D'), ((0, 1), 'O'), ((1, 2), 'G')]不在combine中,这意味着coordinates_lst_and_str_lst找不到它作为解决方案。

因此,问题一定出在create_dict中,显然它并没有创建所有合法动作。

实际上,在create_dict中,您使用itertools.combinations() ,它为您提供集合中n项的所有唯一组合,而不管它们的 order ,但您关心的是 order。

所以,你不想要itertools.combinations(new_dict.items(), n) ,你想要itertools.permutations(new_dict.items(), n) 仔细看看组合和排列(大小为 n)之间的区别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM