[img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/921499945386174.png
[img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/95652005538615.jpg
找第一个三位数的最大,那就从最大数987开始找,逐渐减小,找到第一个满足算式的就结束。也就是先有three_first,得到three_a,three_b,three_c,再生成剩下的两个三位数。也可以简化,使用排列组合,按从大到小排序,然后找符合条件的数。
你的循环没有退出条件,使用随机数不确定性太大,我用排列组合的方式,生成代码如下,供参考:
import itertools
# 将num_list中的数字组合成三位数
def list_to_number(num_list):
return num_list[0] * 100 + num_list[1] * 10 + num_list[2]
# 从num_list中删除sub_list中的数字
def remove_list(num_list, sub_list):
for i in sub_list:
num_list.remove(i)
count = 0
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 生成前3个数字的组合,从大到小
permutations9 = list(itertools.permutations(num_list, 3))
sorted_permutations9 = sorted(permutations9, reverse=True)
for three_first_i in sorted_permutations9:
num_list1 = num_list.copy()
remove_list(num_list1, three_first_i)
three_first = list_to_number(three_first_i)
# 生成中间3个数字的组合
permutations6 = list(itertools.permutations(num_list1, 3))
for three_second_i in permutations6:
three_second = list_to_number(three_second_i)
if three_second > three_first:
count += 1
continue
num_list2 = num_list1.copy()
remove_list(num_list2, three_second_i)
# 生成剩余3个数字的组合
permutations3 = list(itertools.permutations(num_list2, 3))
for three_third_i in permutations3:
count += 1
three_third = list_to_number(three_third_i)
# 如果三个格子的数字之和等于999,则输出这个组合
if three_first + three_second + three_third == 999:
print(three_first, three_second, three_third)
print("循环执行了 %d 次 " % count)
exit(0)
不知道你这个问题是否已经解决, 如果还没有解决的话:定义 HTML 页面中的图像