不知道怎么寫,所以標題很糟糕,
基本上,我有一個 4 個字母的單詞,我想生成在其中插入破折號的每一個排列。
所以如果我的話是貓,我想讓它的每一個排列都有一個破折號,
例子:
c-ats
ca-ts
-c-ats
etc,
有人可以幫助我嗎?
uj5u.com熱心網友回復:
我假設您想要生成所有可能的方法來將零個或多個連字符插入到您的單詞中,因為沒有兩個連字符是相鄰的。這是一種方法itertools.product:
from itertools import product
def hyphens(word):
# create template, each {} is to be filled with "" or "-"
template = "{}" "{}".join(word) "{}"
# iterate over all possible ways to fill empty braces
for chars in product(["", "-"], repeat=len(word) 1):
yield template.format(*chars)
list(hyphens('cats'))
# ['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s', 'ca-t-s-',
# 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-a-ts-', 'c-a-t-s',
# 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-cat-s-', '-ca-ts', '-ca-ts-',
# '-ca-t-s', '-ca-t-s-', '-c-ats', '-c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts',
# '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']
uj5u.com熱心網友回復:
word = input("Enter the word: ")
def insert_into_str(s, index, in_str):
arr = list(s)
arr.insert(index, in_str)
return "".join(arr)
permutations = []
for i in range(len(word) 1):
permutations.append(insert_into_str(word, i, "-"))
print(permutations)
>>> Enter the word: cats
>>> ['-cats', 'c-ats', 'ca-ts', 'cat-s', 'cats-']
uj5u.com熱心網友回復:
這是一種不使用itertools的方法。將二進制字串解釋為放置連字符的位置
def add_hyphens(str):
hyphen_words=[]
a=2**len(str)
b=2**(len(str) 1)
for i in range(a,b,1):
str1=bin(i) #a string 0b1<0's and 1's>
str2=str1[3:] #take off the 0b and the first '1'
tmp_s=""
for j,char1 in enumerate(str):
if str2[j] == '1':
tmp_s =tmp_s '-'
tmp_s = tmp_s char1
hyphen_words.append(tmp_s)
hyphen_words.append(tmp_s '-')
return hyphen_words
print(add_hyphens('cats'))
['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s',
'ca-t-s-', 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-
a-ts-', 'c-a-t-s', 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-
cat-s-', '-ca-ts', '-ca-ts-', '-ca-t-s', '-ca-t-s-', '-c-ats', '-
c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts', '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/428048.html
標籤:Python python-3.x 列表 python-2.7 排列
上一篇:Python通過pid監控行程
