【问题标题】:Printing how many times an inner nested loops occurs when loops have step sizes > 1?当循环的步长 > 1 时,打印内部嵌套循环发生了多少次?
【发布时间】:2021-06-24 21:29:24
【问题描述】:

我很难理解如何将内部循环的出现次数作为来自0..n 的序列打印出来。

考虑下面的代码:

top = 10
step = 1
for i in range(0, top, step):
  for j in range(0, top, step):
    print((i*top)+j)

这将打印0, 1, 2, ..., 98, 99,这很好,但步长为1。如果步长更大怎么办?

top = 10
step = 2
for i in range(0, top, step):
  for j in range(0, top, step):
    print((i*top)+j)

这不会打印0, 1, 2, ..., 23, 24。但是,以下是:

top = 10
step = 2
idx = 0
for i in range(0, top, step):
  for j in range(0, top, step):
    print(idx)
    idx += 1

使用3 的步长打印0, 1, 2, ..., 14, 154 的步长打印 0, 1, 2, ..., 7, 8。以此类推。

有没有办法在不使用额外变量或幻数的情况下做到这一点?这里调用idx += 1的次数不就是ijtopstep的函数吗?

【问题讨论】:

    标签: arrays loops multidimensional-array indexing


    【解决方案1】:

    您可以用数学方法计算迭代步数。

    您知道范围的起点 (0) 和终点 (top)。当步长不为零时,您每次都会逐步递增。每次迭代都会测试您的当前值是否已达到界限。如果它没有达到边界,则迭代继续。

    当步长为1时,很容易计算迭代次数,只需从下界减去上界即可。示例:10 - 0 = 10 迭代 ([0, 1, 2 ..., 9])。

    当步长不为零时,我们必须考虑每一步都会使我们更快地到达边界。示例:

    • 上界 10
    • lower_bound 0
    • 第 2 步。

    我们需要用 2 秒从 0 到 10。 我们将一些计数器 i 初始化为 0。我们将该计数器与 upper_bound (10) 进行比较。我们检查的第一次迭代是 0 True,所以我们yield 0 并将i 增加step (2)。

    i Comparison Result of Comparison Value Yielded
    0 0 < 10 True Yes
    2 2 < 10 True Yes
    4 4 < 10 True Yes
    6 6 < 10 True Yes
    8 8 < 10 True Yes
    10 10 < 10 False No

    此范围产生 5 个值。我们可以通过将范围转换为列表然后获取它的长度来发现这一点。但是,我们也可以仅根据 upper_boundlower_boundstep 计算值的数量。我们知道我们需要从upper_bound遍历到lower_bound,我们可以通过将要遍历的范围除以步长来确定需要多少次迭代。

    (upper_bound - lower_bound) / step

    (10 - 0) / 2 = 5

    这与我们找到的值 [0, 2, 4, 6, 8] 匹配。

    如果绑定不整齐,事情就会变得棘手。例如偶数步长的奇数上限。示例:

    • 上限 15
    • lower_bound 0
    • 第 2 步。

    在这种情况下,(15 - 0) / 2 是 7.5。

    问题是 range 会进行 7 次或 8 次迭代吗?

    i Comparison Result of Comparison Value Yielded
    0 0 < 15 True Yes
    2 2 < 15 True Yes
    4 4 < 15 True Yes
    6 6 < 15 True Yes
    8 8 < 15 True Yes
    10 10 < 15 True Yes
    12 12 < 15 True Yes
    14 14 < 15 True Yes
    16 16 < 15 False No

    答案是 8,因为当前步骤会将 14 与 15 进行比较。由于 14 小于 15,因此会产生值 14。直到i 变为 16 并打破小于upper_bound 的要求,迭代才会终止。

    在数学方面,我们可以说迭代次数总是除法后的下一个整数,或者除法运算的上限。

    ceiling((upper_bound - lower_bound) / step)

    我们可以使用math 中的ceil 来确保除法总是向上取整。

    现在我们可以根据upper_boundlower_boundstep计算任意范围的迭代次数,我们可以开始看看如何计算嵌套循环的迭代次数了。

    在这种情况下,内循环和外循环运行相同的次数,而内循环每次迭代运行的次数相同(可能并非总是如此)。 但是,在这种情况下,如果内循环运行 5 次,则外循环也将运行 5 次。 5组5次迭代一共是25次迭代。这是内部迭代次数和外部迭代次数的直接乘积。

    total_iterations = outer_iterations * inner_iterations

    在这种特殊情况下,相当于:

    total_iterations = (ceiling((upper_bound - lower_bound) / step))^2

    你的程序可能看起来像这样:

    import math
    
    
    def main():
        range_lower_bound = 0
        range_upper_bound = 15
        range_step = 2
    
        # Calculate the Number of Iterations
        outer_loop_iteration_count = int(math.ceil((range_upper_bound - range_lower_bound) / range_step))
        # Inner Loop Same since range bounds and step for outer and inner are the same
        inner_loop_iteration_count = outer_loop_iteration_count
        # Inner Loop Runs Outer Loop Times
        number_of_iterations = outer_loop_iteration_count * inner_loop_iteration_count
        print(f'{number_of_iterations} Iterations')
        # List of Iteration Counts (0 indexed)
        iterations_as_list = list(range(0, number_of_iterations))
        print(iterations_as_list)
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多