在 Python 中查詢刪除 k 個字元後所有可能的子字串


給定一個字串。需要完成的任務是從字串中取出一個字母並列印字串中剩餘的字母。我們需要對字串的每個字母都這樣做。

使用迴圈和範圍

這是一種基本的程式設計方法,我們首先列出所需的引數,例如宣告字串、為開始和結束位置建立變數以及為每個字母建立一個臨時佔位符。然後,我們建立一個函式,該函式將遍歷每個字母並建立一個包含剩餘字母的字串。

示例

 即時演示

list = []

def letterCombinations(s, t, start, end, index, k):
   if (index == k):
      elem = ''

      for j in range(k):
         elem += t[j]
      list.append(elem)
      return

   i = start
   while (i <= end and end - i + 1 >= k - index):
      temp[index] = s[i]
      letterCombinations(s, t, i + 1,
                        end, index + 1, k)
      i += 1
stringA = 'Apple'
k = 1
temp = [0] * (len(stringA) - k)
start = 0
end = len(stringA) - 1

letterCombinations(stringA, temp, start, end, 0, len(stringA) - k)
print(set(list))

輸出

執行以上程式碼,得到以下結果:

{'pple', 'Aple', 'Appl', 'Appe'}

使用 itertools

在這種方法中,我們使用名為 itertools 的模組,該模組具有一個名為 combinations 的函式。在我們從給定字串中刪除一個字母后,它負責建立所有可能的字母組合。

示例

from itertools import combinations

stringA = 'Apple'
k = 1

# using combinations
res = set([''.join(i) for i in combinations(stringA, len(stringA) - k)])

print(res)

輸出

執行以上程式碼,得到以下結果:

{'Appl', 'Aple', 'Appe', 'pple'}

更新時間: 2020-08-26

149 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.