我正在提出例外情况,我不知道为什么吗?

时间:2018-08-21 16:16:11

标签: python python-3.x

def permutations(string, step = 0):
    # convert parameter to string in case we received something else
    try:
        if isinstance(string, str):
            # if we've gotten to the end, print the permutation
            if step == len(string):
                print "".join(string)

            # everything to the right of step has not been swapped yet
            for i in range(step, len(string)):

                # copy the string (store as array)
                string_copy = [character for character in string]

                # swap the current index with the step
                string_copy[step], string_copy[i] = string_copy[i], string_copy[step]

                # recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)
                permutations(string_copy, step + 1)
        else:
            raise Exception
    except Exception as error:
        print('Caught this error: string passed in paramater is not a string')

permutations("abc", 0)

为什么会引发异常?基本上,我想防止某人传递随机对象(不是字符串)。

因此123或Vehicle()将失败。

但是我在字符串上引发异常(通常是我的递归函数的第二次迭代)

1 个答案:

答案 0 :(得分:1)

string_copy不是str;这是(单个字符)str对象的列表。在将其传递给permutations之前,您需要将元素重新连接到单个字符串中。

permutations(''.join(string_copy), step + 1)