gpt4 book ai didi

python - python for循环中的原始步骤数

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:58 25 4
gpt4 key购买 nike

我正在阅读算法的复杂性。我有一个代码,我想告诉它原始操作的数量。

sum_res = 0     #1
for num in num_list: # 5 * n + 2
sum_res += num # n * 1
mean = sum_res / len(num_list) # 3

我知道第 1 行是 1 次操作。第 3 行是 1 次操作,但是因为它已经执行了 n 次,所以它总共进行了 n 次操作。最后一行是 3 个操作。但是我不明白为什么循环是5 * n + 2

如果有人能为我分解它,我将不胜感激。

最佳答案

我不确定您的讲师是从哪里得到这些数字的。如果您想查看基于堆栈的 Python 虚拟机对一段代码执行的原始操作,您可以使用 dis.dis功能。

来自文档:

dis.dis(x=None, *, file=None, depth=None)

Disassemble the x object. x can denote either a module, a class, a method, a function, a generator, an asynchronous generator, a coroutine, a code object, a string of source code or a byte sequence of raw bytecode. For a module, it disassembles all functions. For a class, it disassembles all methods (including class and static methods). For a code object or sequence of raw bytecode, it prints one line per bytecode instruction. It also recursively disassembles nested code objects (the code of comprehensions, generator expressions and nested functions, and the code used for building nested classes). Strings are first compiled to code objects with the compile() built-in function before being disassembled. If no object is provided, this function disassembles the last traceback.

我们可以将您的代码放入一个字符串中,然后将其传递给 dis.dis,如下所示:

from dis import dis

src = '''\
sum_res = 0
for num in num_list:
sum_res += num
mean = sum_res / len(num_list)
'''
dis(src)

输出

  1           0 LOAD_CONST               0 (0)
2 STORE_NAME 0 (sum_res)

2 4 SETUP_LOOP 20 (to 26)
6 LOAD_NAME 1 (num_list)
8 GET_ITER
>> 10 FOR_ITER 12 (to 24)
12 STORE_NAME 2 (num)

3 14 LOAD_NAME 0 (sum_res)
16 LOAD_NAME 2 (num)
18 INPLACE_ADD
20 STORE_NAME 0 (sum_res)
22 JUMP_ABSOLUTE 10
>> 24 POP_BLOCK

4 >> 26 LOAD_NAME 0 (sum_res)
28 LOAD_NAME 3 (len)
30 LOAD_NAME 1 (num_list)
32 CALL_FUNCTION 1
34 BINARY_TRUE_DIVIDE
36 STORE_NAME 4 (mean)
38 LOAD_CONST 1 (None)
40 RETURN_VALUE

希望您能大致了解那里发生的事情,但请参阅 dis 文档以了解各种指令的含义。

关于python - python for循环中的原始步骤数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52687866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com