【问题标题】:What is the complexity of a recursive snowflake function?递归雪花函数的复杂性是多少?
【发布时间】:2018-11-03 18:28:38
【问题描述】:
# The base case basically draws a segment.

import turtle
def fractal(order,length):
    if order==0:
        turtle.forward(length)
    else:
        l=length/3
        fractal(order-1,l)
        turtle.left(60)
        fractal(order-1,l)
        turtle.right(120)
        fractal(order-1,l)
        turtle.left(60)
        fractal(order-1,l)
def snowflake(order,length):
    fractal(order,length)
    turtle.right(120)
    fractal(order,length)
    turtle.right(120)
    fractal(order,length)
snowflake(3,300)
turtle.speed(0)
turtle.done()

这是一个递归函数,用于追踪分形雪花。 复杂性取决于顺序。 但是,当我们为每个订单发生这么多递归操作时,我无法弄清楚。

【问题讨论】:

    标签: recursion complexity-theory fractals snowflake-cloud-data-platform


    【解决方案1】:

    虽然函数看起来很复杂,但值得注意的是fractal的执行依赖于order。所以在复杂性方面,它可以简化为:

    def fractal(order):
        if order == 0:
             # do O(1)
        else:
            fractal(order - 1)
            fractal(order - 1)
            fractal(order - 1)
    

    即3 次递归调用 order - 1;那么时间复杂度递归就很简单了:

    T(n) = 3 * T(n - 1) (+ O(1))
    T(1) = O(1)
    

    – 很容易证明是O(3^n)

    snowflakefractal 有 3 个相同的调用,O(3^n) 也是如此。

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 2021-11-17
      • 2015-11-29
      • 2022-11-22
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多