使用递归实现
words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse'] def get_results(_start, _current, _seen): if all(c in _seen for c in words if c[0] == _start[-1]): yield _current else: for i in words: if i[0] == _start[-1]: yield from get_results(i, _current+[i], _seen+[i]) new_d = [list(get_results(i, [i], []))[0] for i in words] #print(new_d) final_d = max([i for i in new_d if len(i) == len(set(i))], key=len) print(final_d)
输出:
['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']
工作原理类似于广度优先搜索,因为只要当前值之前没有被调用,get_results函数就会继续遍历整个列表。函数已经查找过的值被添加到_seen列表中,最终停止递归调用流。这个解决方案也会忽略重复的结果,
words = ['giraffe', 'elephant', 'ant', 'ning', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse',] def get_results(_start, _current, _seen): if all(c in _seen for c in words if c[0] == _start[-1]): yield _current else: for i in words: if i[0] == _start[-1]: yield from get_results(i, _current+[i], _seen+[i]) new_d = [list(get_results(i, [i], []))[0] for i in words] #print(new_d) final_d = max([i for i in new_d if len(i) == len(set(i))], key=len) print(final_d)
输出:
['ant', 'tiger', 'racoon', 'ning', 'giraffe', 'elephant']