首页 > 解决方案 > Cannot understand why IDLE gui is not returning the values that the author is saying it should return

问题描述

I am reading the book Learning Python and the author provides these two snippets of code, he then runs "abc" like so permute1("abc") and this returns all the permutations of abc, when I do it in IDLE. It returns ['abc']. I don't understand how the author is saying that it should return ['abc', 'acb' -- etc ] What am I missing here?

def permute1(seq):
    if not seq:
        return [seq]
    else:
        res = []
        for i in range(len(seq)):
            rest = seq[:i] + seq[i+1:]
            for x in permute1(rest):
                res.append(seq[i:i+1] + x)
            return res

def permute2(seq):
    if not seq:
        yield seq
    else:
        for i in range(len(seq)):
            rest = seq[:i] + seq[i+1:]
            for x in permute2(rest):
                yield seq[i:i+1] + x

标签: python

解决方案


Looks like you added an extra indentation to the return res line in your first for loop.

This is making your function terminate early. After we unindent that permute1("abc") works as expected.


推荐阅读