![](/img/trans.png)
[英]Program gives list of all potential substings from a given string, need to filter out substrings not in alphabetical order
[英]Generate all substrings(in lexicographic order)of given string in alphabetical order
我最近看到了這個問題,並且真的堅持實施它。
問題是從給定的字符串生成所有可能的按字母順序排列的子字符串。
較小的示例:對於字符串xcv
我需要生成輸出:
c cv cvx v vx x
更大的例子:對於字符串hgrte
我需要生成以下子字符串:
e
eg
egh
eghr
eghrt
eght
egr
egrt
egt
eh
ehr
ehrt
eht
er
ert
et
g
gh
ghr
ghrt
ght
gr
grt
gt
h
hr
hrt
ht
r
rt
t
這是我的實現,它沒有產生所需的輸出。
s = sorted(list(input()))
s = ''.join(s)
for i in range(len(s)):
for j in range(i+1, len(s)+1):
temp = s[i:j]
print(''.join(temp))
這是我的代碼的輸出:
e
eg
egh
eghr
eghrt
g
gh
ghr
ghrt
h
hr
hrt
r
rt
t
[]
我知道在打印eghrt
后我必須使用回溯和遞歸,但我真的堅持執行它。 提前致謝 :)
您可以遍歷不同的長度並使用itertools.combinations
生成字母組合:
from itertools import combinations
s = sorted(input())
print(*sorted(''.join(c) for i in range(len(s)) for c in combinations(s, i + 1)), sep='\n')
如果遞歸不是明確的要求,您可以在沒有遞歸的情況下執行此操作:
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
for w in (''.join(sorted(x)) for x in powerset(s) ):
print(w)
取自如何獲取集合的所有子集的powerset
函數? (動力裝置)
您忘記考慮不連續的子字符串。 一個簡單的方法是使用 itertools。
import itertools
word = sorted(list(input()))
print(sorted(set([''.join(j) for i in range(len(word)) for j in itertools.combinations(word, i)])))
這將完成這項工作。 如果您不想使用標准庫,可以使用位掩碼來獲取所有可能的子字符串。
s = 'abc'
n = len(s)
p = 2 ** n # total number of power sets
res = []
for i in range(1, p):
tmp = ''
for j in range(n):
if i & (1 << j):
tmp += s[j]
res.append(tmp)
print(sorted(res)) # ['a', 'ab', 'abc', 'ac', 'b', 'bc', 'c']
# Time Complexity: O(2^n * n)
# Space Complexity: O(n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.