python编程 NO.1 求三个数之和为500的所有组合
答案:1 悬赏:30 手机版
解决时间 2021-03-25 02:11
- 提问者网友:姑娘长的好罪过
- 2021-03-24 11:39
python编程 NO.1 求三个数之和为500的所有组合
最佳答案
- 五星知识达人网友:患得患失的劫
- 2021-03-24 11:58
代码:
def main(total):
result = []
for x in range(total-1):
y_plus_z = total - x
for y in range(y_plus_z+1):
z = y_plus_z - y
if z < 0:
break
if is_existed(x,y,z,result):
continue
else:
result.append((x,y,z))
return result
def is_existed(x,y,z,result):
if (x, z, y) in result:
return True
if (y, x, z) in result:
return True
if (y, z, x) in result:
return True
if (z, x, y) in result:
return True
if (z, y, x) in result:
return True
return False以total=10为例, 输出为
result = [(0, 0, 10), (0, 1, 9), (0, 2, 8), (0, 3, 7), (0, 4, 6), (0, 5, 5), (1, 1, 8), (1, 2, 7),
(1, 3, 6), (1, 4, 5), (2, 2, 6), (2, 3, 5), (2, 4, 4), (3, 3, 4)]
def main(total):
result = []
for x in range(total-1):
y_plus_z = total - x
for y in range(y_plus_z+1):
z = y_plus_z - y
if z < 0:
break
if is_existed(x,y,z,result):
continue
else:
result.append((x,y,z))
return result
def is_existed(x,y,z,result):
if (x, z, y) in result:
return True
if (y, x, z) in result:
return True
if (y, z, x) in result:
return True
if (z, x, y) in result:
return True
if (z, y, x) in result:
return True
return False以total=10为例, 输出为
result = [(0, 0, 10), (0, 1, 9), (0, 2, 8), (0, 3, 7), (0, 4, 6), (0, 5, 5), (1, 1, 8), (1, 2, 7),
(1, 3, 6), (1, 4, 5), (2, 2, 6), (2, 3, 5), (2, 4, 4), (3, 3, 4)]
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯