How to optimize this Python code (from ThinkPython, Exercise 10.10)

前端 未结 4 877
无人共我
无人共我 2021-01-12 00:54

I\'m working through Allen Downey\'s How To Think Like A Computer Scientist, and I\'ve written what I believe to be a functionally correct solution to Exercise 10.1

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 01:47

    Do it the other way around: Iterate through all words and split them into two words by taking the odd and even letters. Then look up those two words in the dictionary.

    As a side node, the two words that interlock must not necessarily have the same length -- the lengths might also differ by 1.

    Some (untested) code:

    words = set(line.strip() for line in open("words"))
    for w in words:
        even, odd = w[::2], w[1::2]
        if even in words and odd in words:
            print even, odd
    

提交回复
热议问题