我正在开发一个程序,可以打印一个单词的所有可能组合。一切都能正常工作,但我想更进一步,使它不只打印一个单词的所有组合。它应该删除一个单词的最后一个字符,直到只剩下一个字母。
这是我写的。
# Enter Word
print("Enter your word:")
print()
s = input(colorGreen)
# If s is a string, print all combinations
if all(s.isalpha() or s.isspace() for s in s):
t=list(itertools.permutations(s,len(s)))
for i in range(0,len(t)):
print(colorGreen + "".join(t[i]))
while len(s) != 1:
t=list(itertools.permutations(s,len(s)))
for i in range(0,len(t)):
print(colorGreen + "".join(t[i]))
print()
print("Finished!")
print()
input("Press anything to quit...")
# If s is not a string, print error
if not all(s.isalpha() or s.isspace() for s in s):
print(colorRed + "You did not enter a correct word")
print("Only use a word for Word combinations")
print("Please restart the program.")
print()
input("Press anything to quit...")
先谢谢你了 :D
你可以这样做。
from itertools import permutations
string = 'hello'
c = reversed([''.join(s) for i in range(1,len(string)+1) for s in permutations(string,i)])
print('\n'.join(c))
输出:
olleh
ollhe
olelh
olehl
olhle
olhel
olleh
ollhe
olelh
olehl
olhle
olhel
oellh
oelhl
oellh
oelhl
oehll
oehll
ohlle
ohlel
ohlle
ohlel
ohell
ohell
loleh
lolhe
loelh
loehl
lohle
lohel
lloeh
llohe
lleoh
lleho
llhoe
llheo
leolh
leohl
leloh
lelho
lehol
lehlo
lhole
lhoel
lhloe
lhleo
lheol
lhelo
loleh
lolhe
loelh
loehl
lohle
lohel
lloeh
llohe
lleoh
lleho
llhoe
llheo
leolh
leohl
leloh
lelho
lehol
lehlo
lhole
lhoel
lhloe
lhleo
lheol
lhelo
eollh
eolhl
eollh
eolhl
eohll
eohll
elolh
elohl
elloh
ellho
elhol
elhlo
elolh
elohl
elloh
ellho
elhol
elhlo
eholl
eholl
ehlol
ehllo
ehlol
ehllo
holle
holel
holle
holel
hoell
hoell
hlole
hloel
hlloe
hlleo
hleol
hlelo
hlole
hloel
hlloe
hlleo
hleol
hlelo
heoll
heoll
helol
hello
helol
hello
olle
ollh
olel
oleh
olhl
olhe
olle
ollh
olel
oleh
olhl
olhe
oell
oelh
oell
oelh
oehl
oehl
ohll
ohle
ohll
ohle
ohel
ohel
lole
lolh
loel
loeh
lohl
lohe
lloe
lloh
lleo
lleh
llho
llhe
leol
leoh
lelo
lelh
leho
lehl
lhol
lhoe
lhlo
lhle
lheo
lhel
lole
lolh
loel
loeh
lohl
lohe
lloe
lloh
lleo
lleh
llho
llhe
leol
leoh
lelo
lelh
leho
lehl
lhol
lhoe
lhlo
lhle
lheo
lhel
eoll
eolh
eoll
eolh
eohl
eohl
elol
eloh
ello
ellh
elho
elhl
elol
eloh
ello
ellh
elho
elhl
ehol
ehol
ehlo
ehll
ehlo
ehll
holl
hole
holl
hole
hoel
hoel
hlol
hloe
hllo
hlle
hleo
hlel
hlol
hloe
hllo
hlle
hleo
hlel
heol
heol
helo
hell
helo
hell
oll
ole
olh
oll
ole
olh
oel
oel
oeh
ohl
ohl
ohe
lol
loe
loh
llo
lle
llh
leo
lel
leh
lho
lhl
lhe
lol
loe
loh
llo
lle
llh
leo
lel
leh
lho
lhl
lhe
eol
eol
eoh
elo
ell
elh
elo
ell
elh
eho
ehl
ehl
hol
hol
hoe
hlo
hll
hle
hlo
hll
hle
heo
hel
hel
ol
ol
oe
oh
lo
ll
le
lh
lo
ll
le
lh
eo
el
el
eh
ho
hl
hl
he
o
l
l
e
h