十几行 python 搞定女儿的练习题

女儿在做英语练习题, 有一种类型叫做字母组合, 就是将打乱顺序的字母组合成学过的单词, 女儿常常想不出来, 我也经常搔头, 顺序是乱的, 查字典也不好使.

这个难不住程序员, 打开电脑写了十几行 python 程序, 这种问题以后就是小菜一碟了

  1. 首先下载一个英语字典的单词文本文件
wget https://github.com/dwyl/english-words/blob/master/words_alpha.txt

格式如下

$ head words_alpha.txt
a
aa
aaa
aah
aahed
aahing
aahs
aal
aalii
aaliis
...
  1. 用 python 写个小程序

程序如下, 加上空行, 总共18行, 轻松搞定

# vi words_compose.py
import sys
from itertools import permutations 

words = []
with open('./words_alpha.txt') as file:
    for line in file: 
        line = line.strip() 
        words.add(line)

inputstr = 'hoiystr'
if(len(sys.argv)>1):
    inputstr = sys.argv[1].lower()

perms = permutations(inputstr)
for p in perms:
    word = ''.join(p)
    if word in words:
        print(word)

  1. 使用方法
    输入参数为乱序的字母串
$ python words_compose.py ipturec
picture
cuprite

$ python words_compose.py oihystr
history
toryish

女儿很满意, 我也乘机自吹了一番, 劝说女儿也学一点 python 编程

拓展阅读

    原文作者:瓦尔特有范
    原文地址: https://www.jianshu.com/p/9a47efeb5c9b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞