递归搜索

时间:2016-04-28 21:46:45

标签: python recursion

我正在使用txt文件作为“单词搜索板”,其中包含单词。我还在另一个txt文件中使用了一个单词列表,这个单词可能位于单词板中,也可能不位于单词板中。在所有方向,北,南,东,西,NE,NW,SE,SW和相反的方向发现词。通过电路板搜索的功能必须是递归的。在我当前的searchBoard()中,我试图只搜索单词的第一个字母然后检查周围的下一个字母,依此类推。我的递归功能按照我想要的方式工作,任何提示都会受到赞赏。

董事会的示例文本文件:

G J T P B A V K U V L V
M N Q H S G M N T C E E
Y H I J S G Q E N Y C W
G S K M G H C B M U T H
R A T V M N V D G V U T
E P G U E A B P W Q R T
T J C I D D R Q T E E C
U P C I S E N G B U O B
P S J C I V N F O U N N
M P R O J E C T R R A M
O H Q T P P D S H A P G
C O W U K Q E G I J M S

包含单词列表的其他txt文件:

COMPUTER 
SCRAM
COURSE
LECTURE
PROGRAMMING
PROJECT
SCIENCE
STUDENT

我的代码:

#Making the word file into a list
def getWords(wordList):
    fname = open(wordList,'r')
    lines = fname.read().split()

    return(lines)


#Making the puzzle file into a 2d list.
def buildBoard(puzzleBoard):

    fname = open(puzzleBoard,'r')
    boardList = []
    for line in fname:
        number_strings = line.split() 
        letters = [n for n in number_strings] 
        boardList.append(letters)

    fname.close()

    print(boardList[1][0])#row ,then col. Both start at 0s

    return(boardList)



#Recursively search board 
def searchBoard(pos,puzzleBoard,wordList):
    for word in wordList:
        firstLetter = word[:1]
        if puzzleBoard[pos[0]][pos[1]] == firstLetter:
           newPos = pos[0][0]
           searchBoard(newPos,puzzleBoard,wordList)

        #Checking above
        if puzzleBoard[pos[0]-1][pos[1]] == firstLetter:
          newPos = [pos[0]-1,pos[1]]  
          searchBoard(newPos,puzzleBoard,wordList)


def main():
    print("Welcome to the Word Search")
    print("For this, you will import two files: 1. The puzzle board, and 2. The word list.")
    puzzleBoard = input("What is the puzzle file you would like to import?: ")
    wordList = input("What is the word list file you would like to import?: ")

    puzzleBoard = buildBoard(puzzleBoard)    
    wordList = getWords(wordList)


    pos = [puzzleBoard[0][0]]
    searchBoard(pos,puzzleBoard,wordList)
main()

错误:

if puzzleBoard[pos[0]][pos[1]] == firstLetter:

TypeError: list indices must be integers or slices, not str

2 个答案:

答案 0 :(得分:2)

这是一个很好的练习:) 我拿了你的输入拼图板并写了一个小函数,递归搜索拼图板。首先,它尝试找到单词text.find(word[0], pos)的第一个字母,然后使用floor和modulo division更改每个方向的x,y坐标,并查找下一个字母。如果下一个字母不匹配,它会尝试下一个方向,直到找到整个单词,或者字符不匹配或者它离开拼图板的边界。
除了SCRAM之外的所有单词都可以在你的拼图中找到。

text = """
G J T P B A V K U V L V
M N Q H S G M N T C E E
Y H I J S G Q E N Y C W
G S K M G H C B M U T H
R A T V M N V D G V U T
E P G U E A B P W Q R T
T J C I D D R Q T E E C
U P C I S E N G B U O B
P S J C I V N F O U N N
M P R O J E C T R R A M
O H Q T P P D S H A P G
C O W U K Q E G I J M S"""

#cleans the input puzzleBoard
text = text.replace(' ', '').strip()
#gets the width and height of the puzzleboard
width = len(text.splitlines()[0])
text = text.replace('\n', '')
height = len(text) / width

#a dictionary storing the human readable directions
directions={0:'NW',1:'N',2:'NE',3:'W',4:'',5:'E',6:'SW',7:'S',8:'SE'}

#tries to find a word in a text
#returns x,y of the first character and the orientation of the word
def find_word(text, word):
    pos = 0
    while pos != -1:
        pos = text.find(word[0], pos)
        if pos > -1:
            for ori in [0,1,2,3,5,6,7,8]:
                found = True
                i = 0
                x = pos % width
                y = pos // height

                while found:
                    i += 1
                    if i == len(word) and found:
                        return (pos % width, pos // height, directions[ori])
                    #moves x,y in the selected direction
                    x += ori % 3 - 1
                    y += ori // 3 - 1
                    if x < width and y < height and x > -1 and y > -1:
                        found = text[width * y + x] == word[i]
                    else:
                        found = False
            pos += 1
    #nothing found
    return(-1, -1, directions[4])        

更新

解决同样的问题,但通过递归调用相同的函数。该函数返回找到的单词,最后一个字母的x,y位置和方向,即需要向后查找整个单词。

def find_char(text, pos, word, ori):
    x = int(pos % width)
    y = int(pos // height)
    x += ori % 3 - 1
    y += ori // 3 - 1
    if text[pos] != word[0]:
        return None
    if len(word) == 1:
        return (x,y)
    if x < width and y < height and x > -1 and y > -1:
        pos = int(width * y + x)
        if text[pos] == word[1]:
            if len(word) > 1:
                resp = find_char(text, pos, word[1:], ori)
                if resp:
                    return resp
        else:
            return None

word_list = ['COMPUTER', 'SCRAM', 'COURSE', 'LECTURE', 'PROGRAMMING', 'PROJECT', 'SCIENCE', 'STUDENT']
for i in range(len(text)):
    for ori in [0,1,2,3,5,6,7,8]:
        for word in word_list:
            resp = find_char(text, i, word, ori)
            if resp:
                print(word, resp, ori)

答案 1 :(得分:1)

如果在将pos传递给searchBoard()之前打印['G'] ,python会将此打印出来:

pos = [puzzleBoard[0][0]]

您创建了一个包含pos = ['G']的列表,该列表等于puzzleBoard[pos[0]][pos[1]]

因此,当您尝试访问searchBoard()函数中的puzzleBoard['G'][<nonsense>]时,您会尝试访问pos。使用的两个索引都是错误的。

加号searchBoard()不是位置,,但是包含双列表中的一个字符的列表,并且不包含更多信息(实际上甚至不是位置)。

我建议你将整数作为整数传递给searchBoard(0, 0, puzzleBoard,wordList) # xpos and ypos being the first parameters for instance

searchBoard((0, 0), puzzleBoard,wordList)

或者你甚至可以这样做:

pos

这里newPos是一个元组,它包含两个索引,但只包含这些索引,没有其他信息

编辑:正如robyschek在评论中指出的那样,第一个解决方案会更清晰!

如果使用元组解决方案,则进行其他更正:

您必须从newPos = pos[0][0] 更改新的分配:

newPos = (pos[0],pos[0])

类似

{{1}}

我并不了解您计划如何管理索引,但重点是:使其成为元组