0

I have the following Matlab code (adopted from Programming and Numerical Methods in MATLAB by Otto&Denier, page 75)

clear all
p = input('Enter the power you require: ');

points = p+2;
n = 1:points;
for N = n
     sums(N) = 0;
    for j = 1:N
        sums(N) = sums(N)+j^p;
    end
end

The output for 3 as the given value of p is the following list

>> sums
sums =
       1              9             36            100            225 

I have written the following Python code (maybe not the most 'Pythonic way') trying to follow as much as possible Matlab instructions.

p = int(input('Enter the power you require: '))

points = p+2
n = range(points)
for N in range(1, len(n)+1):
    sums = [0]*N
    for index, item in list(enumerate(sums)):
        sums[index] = item+index**p

Nevertheless the output is not same list. I have tried to replace the inner loop with

for j in range(1,N+1):
    sums[N] = sums[N]+j**p

but this results to an index error message. Thanks in advance for any suggestions.

Dimitris
  • 569
  • 3
  • 14

2 Answers2

1

This might be due to the index difference. In Python, it starts from 0 while it's 1 in Matlab. Also, sums = [0]*N initialize a list of a length N, this has to be moved outside of the loop.

points = p+2
sums = [0]*points
for N in range(0, points):
    for index in range(0, N+1):
        sums[N] = sums[N] + (index+1)**p
user69221
  • 176
  • 6
  • Thank you very much for your time. Do you believe that the Python code could be written in a more pythonic way avoiding loops (using for instance list comprehension)? – Dimitris Jan 18 '23 at 14:41
  • 1
    Interesting question, check this out https://stackoverflow.com/questions/25011078/what-does-pythonic-mean One thing I would avoid is using sums for variable name, it is so similar to the function sum ;-) – user69221 Jan 18 '23 at 14:56
1

sums(N) = 0; does not create an array of all zeros, it sets element N of the existing array to 0, and creates additional elements in the array if it not at least of length N.

Because N grows by one each iteration, you could initialize as an empty array before the loop, and append(0) inside the loop:

sums = []
for N in range(1, len(n)+1):
    sums.append(0)

I don’t particularly like the use of enumerate here either, I would:

    for index in range(N)
        sums[index] += (index + 1)**p

(Notice the +1 on the index that was missing in the code in the OP!)

Finally, n is just confusing here. I would:

for N in range(1, points + 1):
    …
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120