【问题标题】:If-statement in while loop not reading last output from if-statementwhile 循环中的 if 语句未从 if 语句中读取最后一个输出
【发布时间】:2021-03-05 05:54:22
【问题描述】:

我正在尝试将列表 x 中两个数字的总和放入列表 z 中,其中该总和除以 20 是不可能的。我的代码不符合只能使用列表 x 中两个数字组合的规则。因此,例如,35 是无效的,因为它不能通过将列表 x 中的两个数字相加来形成。但是,它仍然出现在列表 z 的结果中。

另外,我将“目标”加 5,因为 5 是列表 x 中的最小数字。

我做错了什么?

x = [200, 100, 50, 20, 10, 5]
target = 5
combi=0
max = x[0]+x[1]
z = []
while target <= max:
    for i in x:
        if i < target:
            pair = target - i
            if pair in x:
                combi = 1
    if combi == 1 and target % 20 != 0:
        z.append(target)
    target += 5
print(z)

给定输出:[10, 15, 25, 30, 35, 45, 50, 55, 65, 70, 75, 85, 90, 95, 105, 110, 115, 125, 130, 135, 145, 150 , 155, 165, 170, 175, 185, 190, 195, 205, 210, 215, 225, 230, 235, 245, 250, 255, 265, 270, 275, 285, 290, 295]

期望的输出:[10, 15, 25, 30, 55, 70, 105, 110, 150, 205, 210, 250]

【问题讨论】:

  • 您永远不会将 combi 重置为 0。应将 combi = 0 赋值移到 while 循环内
  • 请阅读How to debug small programs。您还可以使用Python-Tutor,它有助于逐步可视化代码的执行。

标签: python


【解决方案1】:

问题是您永远不会重置“Combi”变量。这是您的固定代码

x = [200, 100, 50, 20, 10, 5]
target = 5
combi=0
max = x[0]+x[1]
z = []
while target <= max:
    for i in x:
        if i < target:
            pair = target - i
            if pair in x:
                combi = 1
    if combi == 1 and target % 20 != 0:
        z.append(target)
    target += 5
    combi = 0
print(z)

【讨论】:

    【解决方案2】:

    试试这个代码:

    x = [200, 100, 50, 20, 10, 5]
    z = []
    for i in range(0,len(x)):
        for j in range(i+1,len(x)):
            sum=x[i]+x[j]
            if sum%20!=0:
                z.append(sum)
    z.reverse()
    print(z)
    

    你想要的输出:

    输出: [15、25、30、55、70、105、110、150、205、210、250]

    【讨论】:

    • 我认为 10 作为输出无效
    • 因为10不是两个数相加产生的
    • 谢谢,但是 10 = 5+5。
    • 在列表 x 中只有一个 5 ,所以另一个 5 来自?
    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2017-06-16
    • 2013-06-09
    • 2014-01-21
    相关资源
    最近更新 更多