组合学
我们可以使用inductive reasoning 写permutations(t) -
- 如果输入
t 为空,则返回空结果
- (归纳)
t 有至少一个 元素。对于子问题t[1:]的所有p,对于第一个元素t[0]的所有r旋转通过p,产量r
def permutations(t):
if not t:
yield () #1
else:
for p in permutations(t[1:]): #2
for r in rotations(p, t[0]):
yield r
rotations((a,b,c), X) 的意思是 X 将“旋转”通过 (a, b, c) 中的每个位置 -
(X, a, b, c)
(a, X, b, c)
(a, b, X, c)
(a, b, c, X)
rotations(t,e) 定义为 -
- 如果输入
t 为空,则产生空旋转,(e)
- (归纳)
t 有至少一个 元素。 yield (e, *t) 和子问题 t[1:] 的所有 r,将第一个元素 t[0] 添加到 r 和 yield
def rotations(t, e):
if not t:
yield (e) # 1
else:
yield (e, *t) # 2
for r in rotations(t[1:], e):
yield (t[0], *r)
for p in permutations("same"):
print(p)
('s', 'a', 'm', 'e')
('a', 's', 'm', 'e')
('a', 'm', 's', 'e')
('a', 'm', 'e', 's')
('s', 'm', 'a', 'e')
('m', 's', 'a', 'e')
('m', 'a', 's', 'e')
('m', 'a', 'e', 's')
('s', 'm', 'e', 'a')
('m', 's', 'e', 'a')
('m', 'e', 's', 'a')
('m', 'e', 'a', 's')
('s', 'a', 'e', 'm')
('a', 's', 'e', 'm')
('a', 'e', 's', 'm')
('a', 'e', 'm', 's')
('s', 'e', 'a', 'm')
('e', 's', 'a', 'm')
('e', 'a', 's', 'm')
('e', 'a', 'm', 's')
('s', 'e', 'm', 'a')
('e', 's', 'm', 'a')
('e', 'm', 's', 'a')
('e', 'm', 'a', 's')
字谜
现在anagrams 可以是一个简单的join 得到的排列 -
def anagrams(s):
for p in permutations(s):
yield "".join(p)
for a in anagrams("same"):
print(a)
same
asme
amse
ames
smae
msae
mase
maes
smea
msea
mesa
meas
saem
asem
aesm
aems
seam
esam
easm
eams
sema
esma
emsa
emas
有效字词
如果您只想找到有效的单词,您需要一个 dictionary 并在 yield 语句之前添加一个条件 -
def anagrams(s, dictionary):
for p in permutations(s):
word = "".join(p)
if word in dictionary:
yield word
mydict = {"valid", "words", "go", "here", ..., }
for a in anagrams("same"):
print(a)
same
maes
mesa
seam