from itertools import permutationsdef is_magic_square(nums):# 将9个数字填充到3×3的格子中grid = [[nums[0], nums[1], nums[2]],[nums[3], nums[4], nums[5]],[nums[6], nums[7], nums[8]],]# 计算每行、每列、对角线的乘积row_products = [grid[i][0] * grid[i][1] * grid[i][2] for i in range(3)]col_products = [grid[0][i] * grid[1][i] * grid[2][i] for i in range(3)]diag1_product = grid[0][0] * grid[1][1] * grid[2][2]diag2_product = grid[0][2] * grid[1][1] * grid[2][0]# 判断是否为三阶积幻方all_products = row_products + col_products + [diag1_product, diag2_product]return len(set(all_products)) == 1def find_magic_square(nums):# 遍历所有排列for perm in permutations(nums):if is_magic_square(perm):return permreturn None# 输入处理nums = list(map(int, input("请输入9个不同的数字,以空格分隔:").split))if len(nums) != 9:print("请输入恰好9个数字!")else:result = find_magic_square(nums)if result:print("找到三阶积幻方的排列方式:")print(result[:3])print(result[3:6])print(result[6:])else:print("无解")摘要:from itertools import permutationsdef is_magic_square(nums):# 将9个数字填充到3×3的格子中grid = [[nums[0], nums[1], nums[2]],[nums[3], nums[4]
来源:圣杰教育
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!