Dev
Dev

Reputation: 13

Numpy/Python variable assignment

I have been trying to get this program to work using Numpy in Python. Here is my code.

import numpy as np

def function(inNum):
    return inNum - 1


i = 1
n = 50000000
AllOutputs = np.array([])
while(i < n):
    SingularOutput = np.array([])
    num = i

    while(num > 1):
        print(num)
        num = function(num)
        np.append(SingularOutput,num)
    np.append(AllOutputs,SingularOutput)

    i = i + 1
    print(i)

The output in the console gives decreasing numbers, here is a snippet.

269
268
267
266
265
264
263
262
261
260
259
258
257
256
255
254

It seems as if is being assigned the values returned from function(inNum), but as it can be seen i is not ever assigned any value other than i = i + 1, thus I do not know why this is happening. Lastly, if I modify the num = i assignment to nums = 1 (or I assume anything else) I get the expected output of

1
2
3
4
5
...(etc)

What am I doing wrong?

Upvotes: 0

Views: 75

Answers (1)

hpaulj
hpaulj

Reputation: 231395

Don't try to imitate list methods with numpy:

AllOutputs = []
while(i < n):
    SingularOutput = []
    num = i

    while(num > 1):
        print(num)
        num = function(num)
        SingularOutput.append(num)
    AllOutputs.append(SingularOutput)

print(AllOutputs)
arr = np.array(AllOutputs)
print(arr)
i = i + 1
print(i)

np.empty([]) and np.append are not clones of [] and list.append. Please read the docs with care!

Running the code I see that you are making sublists that differ in length. There's no point to using numpy for this.

In [39]: i=1; n=6
    ...: AllOutputs = []
    ...: while(i < n):
    ...:     SingularOutput = []
    ...:     num = i
    ...:     while(num > 1):
    ...:         print('num',num)
    ...:         num = fun(num)
    ...:         SingularOutput.append(num)
    ...:     AllOutputs.append(SingularOutput)
    ...:     i = i+1
    ...:     print('i',i)
    ...: 
i 2
num 2
i 3
num 3
num 2
i 4
num 4
num 3
num 2
i 5
num 5
num 4
num 3
num 2
i 6
In [40]: AllOutputs
Out[40]: [[], [1], [2, 1], [3, 2, 1], [4, 3, 2, 1]]

Upvotes: 1

Related Questions