本帖最后由 Jesslin 于 2019-10-29 22:30 编辑
问题:从100到200共101个数字中按照顺序取10个数,每个数可以重复取,使十个数的总和为1024,求总共有多少种选择,给出最终的数量。
例如,选择的十个数按照顺序分别为100、100、100、100、100、100、104、106、106、108,这十个数的总和为1024,即为其中一种选择。
本菜鸟第一次写的代码跑到挂机都没跑出答案来:
num = 0
for a in range(100, 201):
for b in range(100, 201):
for c in range(100, 201):
for d in range(100, 201):
for e in range(100, 201):
for f in range(100, 201):
for g in range(100, 201):
for h in range(100, 201):
for i in range(100, 201):
for j in range(100, 201):
if (a <= b <= c <= d <= e <= f <= g <= h <= i <= j) and (a + b + c + d + e + f + g + h + i + j == 1024):
print([a, b, c, d, e, f, g, h, i, j])
num += 1
print(num)
于是有了第二次跑到挂机都没跑出结果:
num = 0
for a in range(100, 125):
for b in range(100, 125):
for c in range(100, 125):
for d in range(100, 125):
for e in range(100, 125):
for f in range(100, 125):
for g in range(100, 125):
for h in range(100, 125):
for i in range(100, 125):
for j in range(100, 125):
if (a <= b <= c <= d <= e <= f <= g <= h <= i <= j) and (a + b + c + d + e + f + g + h + i + j == 1024):
print([a, b, c, d, e, f, g, h, i, j])
num += 1
print(num)
经过本菜鸟的不懈努力,终于写出了不至于挂机的代码:
num = 0
for a in range(100, 125):
for b in range(100, 125):
if a <= b:
for c in range(100, 125):
if b <= c:
for d in range(100, 125):
if c <= d:
for e in range(100, 125):
if d <= e:
for f in range(100, 125):
if e <= f:
for g in range(100, 125):
if f <= g:
for h in range(100, 125):
if g <= h:
for i in range(100, 125):
if h <= i:
for j in range(100, 125):
if (i <= j) and (a + b + c + d + e + f + g + h + i + j == 1024):
print([a, b, c, d, e, f, g, h, i, j])
num += 1
print(num)
终于得到最终答案:num = 1204
本菜鸟编码水平过渣,持续改进ing~
Fighting!Fighting!Fighting!
最后,希望看到此帖的大神能留下你的高见,蟹蟹~
|
|