gpt4 book ai didi

python - 了解 Kadane 算法 (Python) 中发生的事情

转载 作者:行者123 更新时间:2023-12-04 11:56:29 24 4
gpt4 key购买 nike

我很难理解在我发现的 Kadane 算法的这两个例子中发生了什么。我是 Python 新手,我希望理解这个复杂的算法将帮助我更好地查看/阅读程序。
为什么一个例子比另一个更好,它只是 列表与范围 ?还有其他什么可以使示例之一更有效吗?此外,还有一些关于计算中发生了什么的问题。 (例子中的问题)
我用过 PythonTutor帮助我逐步了解到底发生了什么。
示例 1:
在 PythonTuter 中,当您在提供的屏幕截图中选择下一步时,so_far 的值变为 1。这是怎么回事?给出总和,我认为它加上 -2 + 1 即 -1,所以当 so_far 变成 1 时,这是怎么回事?

        def max_sub(nums):
max_sum = 0
so_far = nums[0]

for x in nums[1:]:
so_far = max(x, x + so_far)
max_sum = max(so_far, max_sum)
return max_sum

nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
max_sub(nums)
6
enter image description here
示例 2:
类似的问题,当我选择 NEXT step 时,max_sum 从 -2 变为 4 ......但是如果它在 2(即 4)中添加元素怎么办。对我来说,那将是 -2 + 4 = 2 ?
def maxSubArraySum(a,size):

max_so_far =a[0]
curr_max = a[0]

for i in range(1,size):
curr_max = max(a[i], curr_max + a[i])
max_so_far = max(max_so_far,curr_max)

return max_so_far

a = [-2, -3, 4, -1, -2, 1, 5, -3]
print("Maximum contiguous sum is" , maxSubArraySum(a,len(a)))
Maximum contiguous sum is 7
enter image description here
所以,这将是一个两部分的问题,而不是:
[1]Based on understandings, why would one be more pythonic and more efficient than the other? 
[2]How can I better understand the calculations happening in the examples?

最佳答案

只需观察每个步骤,您就可以找出这个问题:
[笔记] 这个程序似乎是基于混合整数的假设工作的?只有正面和负面。

# starting
so_far = -2 # init. to nums[0]
max_sum = 0

# in the for-loop:
x = 1 # starting with nums[1:]
so_far = max(1, -1) -> 1 (x is 1, -2 + 1)
max_sum = max(0, 1) -> 1
..... continue .... each step is to find the max accumulated numbers sum, as it's evident in the max( ) statement. *There is no `sum` involved, except it tried to determine the current x is good (not negative) then so add it to the so_far.

关于python - 了解 Kadane 算法 (Python) 中发生的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69003730/

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