简体   繁体   English

Python动态编程

[英]Dynamic programming in Python

I have been trying for a couple of days to implement a simple program from a Matlab code to Python. 我已经尝试了几天,以实现一个从Matlab代码到Python的简单程序。 I am using numpy but if there is a better way I am open to it. 我正在使用numpy,但如果有更好的方法,我可以接受。

This is my Matlab code: 这是我的Matlab代码:

x=[1,1,1,9];
A=zeros(length(x),length(x));
for i=length(x):-1:1
    for j=length(x):-1:i
        if i==length(x)
            A(i,j)=x(i);
        else
            if j>i
                A(i,j)=A(i+1,j)+(j-i);
            elseif j==i
                A(i,j)=x(i)+min(A(j+1,j+1:end));
            end
        end
    end
end
y=min(A(1,:));

It creates this matrix: 它创建此矩阵:

 12    12    13    15
 0    11    11    12
 0     0    10    10
 0     0     0     9

and the final result is 12 (the minimum from the first row). 最终结果是12(第一行的最小值)。 This is what I have done in Python so far: 到目前为止,这是我在Python中所做的:

import numpy as np

items = np.array([1,1,1,9])
sizeLimit = len(items)
P = np.zeros((len(items),len(items)))

for i in range(0, sizeLimit):
  for j in range(i, sizeLimit):
    if i == sizeLimit-1:
        P[i,j] = items[i]
    else:
        if j > i:
            P[i,j] = P[i+1,j] + [j-i]
        elif j == i:
            P[i,j] = items[i] + P[0, 0:].min()
print P

It seems it gets stuck somewhere and does not iterate. 似乎它卡在某个地方并且不会迭代。

I would be grateful to any help. 我将不胜感激。

I've managed to replicate your Matlab result with: 我设法用以下方法复制您的Matlab结果:

import numpy as np

items = np.array([1,1,1,9])
sizeLimit = len(items)
P = np.zeros((len(items),len(items)))

for i in range(sizeLimit-1, -1, -1):
  for j in range(sizeLimit-1, i-1, -1):
    if i == sizeLimit-1:
        P[i,j] = items[i]
    else:
        if j > i:
            P[i,j] = P[i+1,j] + [j-i]
        elif j == i:
            P[i,j] = items[i] + P[j+1, (j+1):].min()

Giving me 给我

>>> print P
[[ 12.  12.  13.  15.]
 [  0.  11.  11.  12.]
 [  0.   0.  10.  10.]
 [  0.   0.   0.   9.]]

The key point is to translate things like: 关键是翻译以下内容:

octave:1> 4:-1:1
ans =

   4   3   2   1

into

>>> sizeLimit = 4
>>> range(sizeLimit-1, -1, -1)
[3, 2, 1, 0]

In your original Python code things are reversed. 在原始的Python代码中,情况相反。 range also excludes the end-point, unlike the Matlab function. 与Matlab函数不同, range也排除了终点。 You also need to be careful to account for the fact that unlike Matlab, Python has 0-based indexing. 您还需要注意一个事实,即与Matlab不同,Python具有基于0的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM