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

前端 未结 4 848
无人共我
无人共我 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:41

    An alternate version:

    with open('words.txt') as inf:
        words = set(wd.strip() for wd in inf)
    
    word_gen = ((word, word[::2], word[1::2]) for word in words)
    interlocked = [word for word,a,b in word_gen if a in words and b in words]
    

    On my machine this runs in 0.16 seconds and returns 1254 words.


    Edit: as pointed out by @John Machin at Why is this program faster in Python than Objective-C? this can be further improved by lazy execution (only perform the second slice if the first results in a valid word):

    with open('words.txt') as inf:
        words = set(wd.strip() for wd in inf)
    interlocked = [word for word in words if word[::2] in words and word[1::2] in words]
    

    This drops execution time by a third, to 0.104 seconds.

提交回复
热议问题