3 回答
TA贡献1821条经验 获得超4个赞
这将是一种具有递归函数的蛮力方法:
import math
def f(temp, numbers):
for i, j in zip(temp[:-1], temp[1:]):
sqrt = math.sqrt(i+j)
if int(sqrt) != sqrt:
return False
if not numbers:
return temp
for i in numbers:
result = f(temp + [i], [j for j in numbers if j != i])
if result:
break
return result
n = int(input("Arrange numbers from 1 to ").strip())
numbers = list(range(1, n+1))
print("Input:", numbers)
print("Output:", f([], numbers))
示例 4:
Arrange numbers from 1 to 4
Input: [1, 2, 3, 4]
Output: False
15 的例子:
Arrange numbers from 1 to 15
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Output: [8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9]
添加回答
举报