如果输入单个数字,如何修改我的程序以 return 相同的输出?
How can I modify my program to return the same output if a single number is inputted?
所以我正在尝试创建一个程序来查找 1 to n
中每个数字的所有排列
例如,如果 n = 5,那么基本上我们必须找到 [1, 2, 3, 4, 5] 的排列,例如,如果 n = 3,我们必须找到 [1, 2] 的排列, 3].输出必须 return 编辑为元组。
所以现在我有了这段代码 return 的排列 如果输入只是一个列表 并且它有效..但是我如何将它修改为 return 当 n: int
是输入时的所有排列...
def permutation(lst):
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i] + lst[i + 1:]
for p in permutation(remLst):
l.append([m] + p)
return l
我应该做哪些更改才能使我的代码正常工作?
您可以使用range
内置函数:
def permutation(lst):
if isinstance(lst, int):
lst = list(range(1, lst + 1))
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i] + lst[i + 1:]
for p in permutation(remLst):
l.append(tuple([m] + list(p)))
return tuple(l)
现在整数和列表参数都可以工作了:
print(permutation(3))
或
print(permutation([1, 3, 5]))
所以我正在尝试创建一个程序来查找 1 to n
例如,如果 n = 5,那么基本上我们必须找到 [1, 2, 3, 4, 5] 的排列,例如,如果 n = 3,我们必须找到 [1, 2] 的排列, 3].输出必须 return 编辑为元组。
所以现在我有了这段代码 return 的排列 如果输入只是一个列表 并且它有效..但是我如何将它修改为 return 当 n: int
是输入时的所有排列...
def permutation(lst):
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i] + lst[i + 1:]
for p in permutation(remLst):
l.append([m] + p)
return l
我应该做哪些更改才能使我的代码正常工作?
您可以使用range
内置函数:
def permutation(lst):
if isinstance(lst, int):
lst = list(range(1, lst + 1))
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i] + lst[i + 1:]
for p in permutation(remLst):
l.append(tuple([m] + list(p)))
return tuple(l)
现在整数和列表参数都可以工作了:
print(permutation(3))
或
print(permutation([1, 3, 5]))