Python Word Unscrambler:代码不会遍历整个列表,但会置换单个列表项

时间:2018-03-29 16:17:14

标签: python list permutation

我是Python的新手,我正在尝试解读HackThisSite上的挑战。我有一个scrambled_list和一个wordlist。

我对此代码的目标是运行加扰单词的排列并将其存储在名为“perms”的列表中。然后,我想看看正常词汇表中是否存在称为“myWords”的任何排列。如果是这样,它们将被附加到“解决方案”列表中。

我的问题是,代码适用于单个列表项(例如,sWords [0]或sWords [2]),但它不会一次性遍历整个列表。

以下是代码:

import os
import string 
from itertools import permutations

os.chdir('C:\Users\goodmat\Documents\Programming Challenges')

s = open('scrambled_list.txt', 'r')
w = open('wordlist.txt', 'r')

myWords = []
sWords = []
solutions = []

with w as f:
    myWords = [line.strip() for line in f]
with s as g:
    sWords = [line.strip() for line in g]


def permute():
    perms = [''.join(p) for p in permutations(sWords)]
    for each in perms:
        if each in myWords:
            solutions.append(each)

permute()
print solutions

1 个答案:

答案 0 :(得分:0)

您的问题是您正在生成列表的排列,而不是列表中单词的排列。

而是在列表中生成单个单词的排列:

2018-05-01

输出:

scrambled = ['windwo', 'droo', 'phonehead', 'asdfjl']
word_list = ['window', 'door', 'car', 'headphone']

solutions = []
perms = [''.join(p) for s in scrambled for p in set(permutations(s))]

final = [each for each in perms if each in word_list]
print(final)