I have some code right now that is getting stuck on one line:
perm = numpy.random.permutation(128)
To which it give the following error: "TypeError: len() of unsized object." I can't figure out what the issue is since 128 is just an integer. I see that this is a problem that has probably been resolved before here: http://mail.scipy.org/pipermail/numpy-discussion/2007-January/025592.html but their solution isn't helpful to me since it is about floats.
Can anyone see what's going wrong here?
In Sage, the input is preparsed by the Sage preparser.
I'll use 12 instead of 128 so the examples fit in one line.
When you input the following:
sage: import numpy
sage: perm = numpy.random.permutation(12)
The error message you get looks like:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-38b6a5e3e889> in <module>()
----> 1 perm = numpy.random.permutation(Integer(12))
/opt/sage/local/lib/python2.7/site-packages/numpy/random/mtrand.so in mtrand.RandomState.permutation (numpy/random/mtrand/mtrand.c:21297)()
/opt/sage/local/lib/python2.7/site-packages/numpy/random/mtrand.so in mtrand.RandomState.shuffle (numpy/random/mtrand/mtrand.c:20965)()
TypeError: len() of unsized object
where you see in particular the line:
----> 1 perm = numpy.random.permutation(Integer(12))
telling you that your input
perm = numpy.random.permutation(12)
was preparsed to
perm = numpy.random.permutation(Integer(12))
However numpy is not so happy being fed a Sage Integer,
it would prefer a Python int.
The simplest way to input a raw Python integer is to append r to it:
sage: perm = numpy.random.permutation(12r)
This will work for you:
sage: perm = numpy.random.permutation(12r)
sage: perm # random
array([ 9, 0, 11, 4, 2, 10, 3, 5, 7, 6, 1, 8])
Another way is to let Sage transform the Python int to a Sage Integer but then force it to convert it back to a Python integer:
sage: perm = numpy.random.permutation(int(12))
sage: perm # random
array([ 5, 9, 1, 7, 0, 2, 10, 6, 3, 8, 4, 11])
Another thing you could do is to turn off the Sage preparser.
sage: preparser(False)
sage: perm = numpy.random.permutation(12)
sage: perm # random
array([ 0, 2, 7, 5, 8, 11, 1, 6, 9, 10, 3, 4])
Related
I am a little confused after a couple attempts while importing Operator and receiving errors. Along with a couple of examples, I've shared a python doc link for reference below.
What I'm expecting to happen below is that operator will run the product and multiply 3 * 4 in the data list which the answer will start [3, 12....] then multiply 12 by the next element '6' to give, [3, 12, 72...]. However importing Operator here isn't working as expected?
The Output I'm expecting for this problem is:
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
Running the below code in PythonTutor.com gives me an Error:
ImportError: cannot import name 'operator'
from itertools import operator
data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
list(accumulate(data, operator.mul))
I've gotten the same type of error running this in Jupyter notebook:
ImportError Traceback (most recent call last)
<ipython-input-1-bc61652bebb8> in <module>
----> 1 from itertools import operator
2
3 data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
4 list(accumulate(data, operator.mul))
ImportError: cannot import name 'operator' from 'itertools' (unknown location)
I've spelled check about 100 times and I've ran these on both PythonTutor and Jupyter NB, and both are giving me errors - can this be an issue with itertools?
Below is from The Python Docs. I'm using the first case:
operator.mul(a, b)
I'll share for your reference: Here
----> operator.mul(a, b)
operator.__mul__(a, b)
Return a * b, for a and b numbers.
Why isn't this working, and how can I fix it?
operator is its own module, not part of itertools:
import itertools
import operator
Note that itertools.accumulate doesn't modify the iterable it is given. It returns a new object which you are not using above. Consider assigning it to a new variable:
data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
accumulated_list = list(itertools.accumulate(data, operator.mul))
I am trying to translate some of my Java algorithm codes into Python.
For the following Java code, I could not figure out a clean way to convert:
int[] groupBaseIndex = IntStream.iterate(0, n -> n < size, n -> n + step).toArray();
Basically, it generate an array from 0 to size with a step. For example, if size=14 and step=4, it generates:
[0,4,8,12]
Can someone teach me how to convert this cleanly into Python? I am sure there must be a one liner to do this in Python.
You can use the built-in range() method:
size = 14
step = 4
print(list(range(0, size, step)))
Output:
[0, 4, 8, 12]
You can use a list comprehension to generate the list of values.
>>> groupBaseIndex = [i for i in range(0, 13, 4)]
>>> groupBaseIndex
[0, 4, 8, 12]
>>>
alternative you can use list(range()), for example
>>> groupBaseIndex = list(range(0, 13, 4))
>>> groupBaseIndex
[0, 4, 8, 12]
>>>
When I attempt:
data_f = hstack([data,Ki])
I get:
TypeError: 'list' object is not callable.
I have 'googled' in vain without result. What have I missed?
I have successfully created the two arrays I want to combine:
data = []
data = np.vstack([data1,data2,data3,data4,data5,data6,data7,data8,data9,data10])
A = []
A = data[:,1]
Ki = []
Ki = np.exp((1000*A)/(Rcal*Tk))
name_s = name+'_Ki'
np.savetxt(name_s,[A],newline='\n',delimiter = ' ')
data_f = []
hstack = []
data_f = hstack([data,Ki])
Please Read The Fine Manual,
where they clearly explain that hstack() wants
a tuple of ndarrays of similar shape.
You're not supplying that.
Carefully examine data & Ki,
to ensure they have similar .shape
EDIT
Here is an example of calling hstack():
>>> a = np.array(range(3)).reshape(3, 1)
>>> b = np.array(range(12)).reshape(3, 4)
>>> a.shape, b.shape
((3, 1), (3, 4))
>>> np.hstack((a, b))
array([[ 0, 0, 1, 2, 3],
[ 1, 4, 5, 6, 7],
[ 2, 8, 9, 10, 11]])
Notice that making a just np.array(range(3)) would not work.
To understand why, look at the difference between the .shape
of those expressions.
I generate an array with python and then I save it in a txt file. When I recover it and I try to convert it into an array, and I work with it, it gives me the error:
ufunc 'multiply' did not contain a loop with signature matching types
dtype('
This is the code:
import numpy as np
lista=[1,2,3,4,5,6,7,8]
vector=np.array(lista)
print (vector)
lista.append(9)
vector=np.array(lista)
print (vector)
archivo= open('datos.txt','w')
archivo.write('%s'%vector)
archivo=open('datos.txt','r')
dades=archivo.read()
vector2=np.array(dades)
print(vector2)
print(vector2*2)
Can you help me?. Thank
When you read it in dades=archivo.read() you actually get a 19-char string.
In order to turn this into a NumPy array you need to do some processing:
>>> dades_as_ints = list(map(int, dades[1:-1].split()))
>>> vector2 = np.array(dades_as_ints)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> vector2 * 2
array([ 2, 4, 6, 8, 10, 12, 14, 16, 18])
I would suggest you look at numpy docs savetxt, which will store your array in a human readable format, or numpy.save for efficient store/load.
So here I have x1vals:
>>> x1Vals
[-0.33042515829906227, -0.1085082739900165, 0.93708611747433213, -0.19289496973017362, -0.94365384912207761, 0.43385903975568652, -0.46061140566051262, 0.82767432358782367, -0.24257307936591843, -0.1182761514447952, -0.29794617763330011, -0.87410892638408, -0.34732294121174467, 0.40646145339571249, -0.64082861589870865, -0.45680189916940073, 0.4688889876175073, -0.89399689430691298, 0.53549621114138612]
And here is the list of x1Vals indices that I want to select
>>> np.where(np.dot(XValsOnly,newweights) > 0)
>>>(array([ 1, 2, 4, 5, 6, 8, 9, 13, 15, 16]),)
But when I try to get the values of x1Vals the Matlab way, I get this error:
>>> x1Vals[np.where(np.dot(XValsOnly,newweights) > 0)]
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
x1Vals[np.where(np.dot(XValsOnly,newweights) > 0)]
TypeError: list indices must be integers, not tuple
>>> np.where(np.dot(XValsOnly,newweights) > 0)
Is there a way around this?
The problem is that your x1Vals is a list object, which does not support fancy indexing. You just have to build an array out of it:
x1Vals = np.array(x1Vals)
and your approach will work.
A faster approach would be to use np.take:
np.take(x1Vals, np.where(np.dot(XValsOnly,newweights) > 0))