我收到一个异常,我不知道为什么?


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(( 会失败。

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

string_copy不是str;它是一个(单字符(str对象的列表。在将其传递给permutations之前,您需要将元素连接回单个字符串。

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

相关内容

最新更新