[英]Splitting a word into all possible 'subwords' - All possible combinations
我試圖將一個單詞分成子詞 - 所有可能的排列。
Input: Bang
Output: [['B','ang'], ['Ba','ng'], ['Ban','g'], ['B','a','ng'], ['B','an','g'], ['Ba','n','g'], ['B','a','n','g']]
我希望我能夠涵蓋所有可能的方式來安排'Bang'。 我想了很久但卻找不到辦法。
list(permutations('Bang', 3))
排列方法不返回整個單詞。 我可以分成2個單詞,但無法將單詞分成3個或更多(對於更大的單詞)。
可以使用以下代碼分成2個單詞,這是由其中一個成員建議的。
[ [word[:i],word[i:]] for i in range(1,len(word))]
你去..
def combos(s):
if not s:
return
yield (s,)
for i in range(1, len(s)):
for c in combos(s[i:]):
yield (s[:i],) + c
for c in combos('Bang'):
print c
輸出:
('Bang',)
('B', 'ang')
('B', 'a', 'ng')
('B', 'a', 'n', 'g')
('B', 'an', 'g')
('Ba', 'ng')
('Ba', 'n', 'g')
('Ban', 'g')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.