【问题标题】:Python for Algorithm Execution Visualization [closed]用于算法执行可视化的 Python [关闭]
【发布时间】:2017-01-26 21:47:04
【问题描述】:

我有一个非常有趣的算法分析课作业,我应该使用不同的方法(例如动态规划和贪心算法)对一个著名的问题(例如背包问题)进行图形比较。我想知道是否有一个库或工具可以用来帮助我可以使用 Python 中的可视化(主要是时间复杂度)。这个想法将是一个简单的图形,如下所示:

【问题讨论】:

标签: python algorithm time-complexity paradigms


【解决方案1】:

首先,您必须计算算法的实际时间复杂度。这可以通过timeit.timeit(实际挂起时间)或手动计算操作次数来完成。

这是一个冒泡排序算法的例子:

def bubble_sort(a):
    not_sorted = True
    operations = 0
    while not_sorted:
        not_sorted = False
        for i in range(len(a)-1):
            operations += 1
            if a[i] > a[i+1]:
                a[i], a[i+1] = a[i+1], a[i]
                not_sorted = True
    return operations

现在您可以为这个函数提供不同大小的数组,收集每次所需的操作数并制作图表。

import matplotlib.pyplot as plt
from random import sample

# assuming we are in Jupyter:
%matplotlib inline

ns = range(10, 1000, 10)
ops = []
for n in ns:
    my_list = sample(range(n), n)
    ops.append(bubble_sort(my_list))
plt.plot(ns, ops)

您甚至可以使用如下统计数据检查渐近线:

from statsmodels.formula.api import ols
import pandas as pd
df = pd.DataFrame(dict(n=ns, ops=ops))
model = ols('ops ~ n + I(n**2)', df)
model = model.fit()
plt.plot(ns, ops)
plt.plot(ns, model.predict())

要找到实际的挂钟时间,只需使用

from timeit import timeit
time = timeit('bubble_sort(a)', number=10, globals=globals())

【讨论】:

  • 非常感谢,这是一个非常明确的答案,肯定会帮助我完成这项任务!
猜你喜欢
  • 1970-01-01
  • 2012-02-19
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 2015-03-09
  • 1970-01-01
相关资源
最近更新 更多