c++行strd.erase(strd.length() - 1)的python代码是什么?其中STRD是字符串

What would be python code for c++ line strd.erase(strd.length() - 1); where strd is a string

本文关键字:strd 是什么 其中 字符串 代码 STRD erase length c++ python      更新时间:2023-10-16

我试过转换下面的c++代码行

 strd.erase(strd.length() - 1);

其中STRD为字符串STRD

python

strd = strd[:len(strd) - 1]

但是它不起作用

在c++中你使用二维数组visited,但在Python中你使用一些字典,所以你的代码不相似。我试着改变它,现在Python使用二维列表visited和打印GEEKS

M = 3
N = 3
dictionary_words = ["GEEKS"]
length = len(dictionary_words)
visited = [[False]* M for x in range(N)]
def isWord(strd):
     for i in range(0, length):
         if strd == dictionary_words[i]:
            return True
     return False
def findWords(boggle):
    for i in range(0, len(boggle)):
        for j in range(0, len(boggle[i])):
            visited[i][j] = False
    strd = ""
    for i in range(0, len(boggle)):
        for j in range(0, len(boggle[i])):
            findWordsUtil(boggle, visited, i, j, strd)

def findWordsUtil(boggle, visited, i, j, strd):
    visited[i][j] = True
    strd = strd + boggle[i][j]
    if (isWord(strd)):
       print strd + "n"
    row = i-1
    while row <= i + 1 and row < len(boggle):
          col = j - 1
          while col <= j + 1 and col < len(boggle[row]):
                if row>=0 and col>=0 and not(visited[row][col]):
                   findWordsUtil(boggle, visited, row, col, strd)
                col = col + 1
          row = row + 1
    strd = strd[:len(strd)-1]
    visited[i][j] = False

def main():
    boggle = [
        ['G','I','Z'],
        ['U','E','K'],
        ['Q','S','E']
    ]
    print "Following words of dictionary are presentn"
    findWords(boggle)

if __name__ == "__main__":
   main()

当然Python代码可以更Python化,例如

def isWord(strd):
     return strd in dictionary_words

但是我不会改变它