【问题标题】:Why are some of the iterations of for loop skipped in this code?为什么在这段代码中跳过了一些 for 循环的迭代?
【发布时间】:2019-05-20 12:25:16
【问题描述】:

多次跳过for循环体的执行

我尝试运行此代码并得到了意想不到的结果。我在调试时注意到有时 for 循环的主体没有执行。我检查了错误的缩进,但看起来很好。

    def getOutput (X):
        # Write your code here
        sum = 0
        if int(X) not in setA:
            setA.append(int(X))
            setA.sort()

        for a in range(len(setA)-1):

            if a == 0:
                low = 1
            else:
                low = setA[a-1] + 1
            sum += low

            if  a == (len(setA)-1):
                high = N
            else:
                high = setA[a+1] - 1
            sum += high
            #print(setA, a, low, high)

        return sum

N, M = map(int, input().split())
setA = []
while M > 0:
    X = input()
    out_ = getOutput(X)
    print (out_)
    M -= 1

Sample Input:
10 10
2 
7
5
9
6
1
8
10
3
4


Expected output for the above input:
11
20
30
46
58
61
77
96
102
110

【问题讨论】:

  • 你到底想让你的代码做什么?
  • 我正在尝试解决良好范围问题hackerearth.com/problem/algorithm/…
  • 你使用什么作为输入?在 input() 上拆分然后将其映射到整数似乎很奇怪。
  • 我在第一行给 N 和 M 值一个 10 10,然后在每一行上给出更多的数字 - 2、7、..,正如问题的示例输入中所提​​供的那样。跨度>
  • 如果它正在跳过 for 循环,那么 len(setA) 可能是

标签: python-3.x for-loop iteration


【解决方案1】:

for 循环应该是for a in range(len(setA)):

而不是for a in range(len(setA)-1):

我试图为列表中的所有索引迭代循环。 range(len(setA) - 1) 排除列表最后一个元素的迭代。 这是因为 range 函数默认会排除最后一个元素。

例如:range(5) 将给我们 [0, 1, 2, 3, 4]。

所以不需要在上面的代码中添加-1。

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 2021-03-07
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多