Reputation: 6190
I have a C++ code doing the following:
U[0]=rate[0];
map<int,double> Q[N+1];
map<int,double> r[N+1];
map<int,double> d[N+1];
r[0][0]=rate[0];
d[0][0]=1/(1+r[0][0]*dt);
Q[0][0]=1.0;
for(int i=1;i<=N;i++)
{
for(int j=-i;j<=i;j=j+2)
{
if(j==i)
{Q[i][i]= 0.5*Q[i-1][i-1]*d[i-1][i-1];}
if(j==-i)
{Q[i][-i]=0.5*Q[i-1][-i+1]*d[i-1][-i+1];}
Q[i][j]=0.5*(Q[i-1][j-1]*d[i-1][j-1]+Q[i-1][j+1]*d[i-1][j+1]);
}
}
I need to write the equivalent Python version for this as I'm not too comfortable with C++. I have done the following:
Q, U, r, d = [], [], [], []
Q.append([])
Q[0].append(1)
U.append(rate[1])
r.append([])
r[0].append(rate[1])
d.append([])
d[0].append(1/(1+r[0][0]*dt))
for i in range(0, N):
for j in range(-i, i, 2):
if j == i:
Q[i].append(0.5*Q[i-1][i-1]*d[i-1][i-1])
elif j == -i:
Q[i].insert(-i, (0.5*Q[i-1][-i+1]*d[i-1][-i+1]))
Q[i].insert(j, 0.5*(Q[i-1][j-1]*d[i-1][j-1]+Q[i-1][j+1]*d[i-1][j+1]))
However, I'm getting an index out of range
error in this line:
Q[i].insert(-i, (0.5*Q[i-1][-i+1]*d[i-1][-i+1]))
How do I correctly translate the C++ code to it's python equivalent?
Upvotes: 0
Views: 726
Reputation: 168616
You get the index error because your arrays aren't prepopulated, as they would be in C++.
Try defining them like so:
from collections import defaultdict
...
#map<int,double> Q[N+1];
Q = [defaultdict(float) for _ in range(N+1)]
#map<int,double> r[N+1];
r = [defaultdict(float) for _ in range(N+1)]
#map<int,double> d[N+1];
d = [defaultdict(float) for _ in range(N+1)]
How do I correctly translate the C++ code to it's python equivalent?
If it were me, and I didn't understand the code I was starting with, I'd do a line-by-line, expression-by-expression translation with absolutely minimal changes.
I would also demand a test case that runs correctly with the C++ code and adapt that to confirm the Python code.
Here is my line-by-line, UNTESTED translation:
from collections import defaultdict
#NameError: name 'N' is not defined
N = 12
#NameError: name 'rate' is not defined
rate = [.03]
#NameError: name 'dt' is not defined
dt = 1.0/12
#U[0]=rate[0];
# unused
#map<int,double> Q[N+1];
Q = [defaultdict(float) for _ in range(N+1)]
#map<int,double> r[N+1];
r = [defaultdict(float) for _ in range(N+1)]
#map<int,double> d[N+1];
d = [defaultdict(float) for _ in range(N+1)]
#r[0][0]=rate[0];
r[0][0] = rate[0]
#d[0][0]=1/(1+r[0][0]*dt);
d[0][0] = 1 / (1 + r[0][0] * dt)
#Q[0][0]=1.0;
Q[0][0] = 1.0
#for(int i=1;i<=N;i++)
#{
for i in range(1, N+1, 1):
# for(int j=-i;j<=i;j=j+2)
# {
for j in range(-i, i+1, 2):
# if(j==i)
# {Q[i][i]= 0.5*Q[i-1][i-1]*d[i-1][i-1];}
if j == i:
Q[i][i] = 0.5 * Q[i-1][i-1] * d[i-1][i-1]
# if(j==-i)
# {Q[i][-i]=0.5*Q[i-1][-i+1]*d[i-1][-i+1];}
if j == -i:
Q[i][-i] = 0.5 * Q[i-1][-i+1] * d[i-1][-i+1]
# Q[i][j]=0.5*(Q[i-1][j-1]*d[i-1][j-1]+Q[i-1][j+1]*d[i-1][j+1]);
Q[i][j] = 0.5 * (Q[i-1][j-1] * d[i-1][j-1] + Q[i-1][j+1] * d[i-1][j+1])
# }
#}
Upvotes: 2