Python get a value from numpy.ndarray by [index] - python

import numpy as np
ze=np.zeros(3)
print(ze[0]) # -> 0
I am pretty new to Python (3.5.2)
I learned 'list' in python and to show the i th element in list1
print (list1[i])
but, even 'np.zeros(3)' is ndarray, a class in NumPy,
it can be used as the 'list' like above.
What is happening on that?
I am pretty new but I have worked on Java..so I hope the issues can be understood...
I guess this question is too early for one who just learned range() and not known how to define functions(methods?)..
But please let me know how to achieve the access by operator [].
Maybe it will be usefull, when I really start to Python.

If you want to implement a class that can return a value using the [] operator. Then implement the __getitem__(self, key) function in the class, see https://docs.python.org/2/reference/datamodel.html#emulating-container-types.

Related

Attempting to use np.insert in a created class which has subscripts yields "object does not support item assignment" debug

I have defined my own class which takes in any matrix and is defined in such a way to convert this matrix into three numpy arrays inside a parenthesis (which I assume means it's a tuple). Furthermore, I have added a getitem method which allows output arrays to be subscript-able just like normal arrays.
My class is called MatrixConverter, and say x is some random matrix, then:
q=MatrixConverter(x)
Where q gives:
q=(array[1,2,3,4],array[5,6,7,8],array[9,10,11,12])
(Note that this is just an example, it does not produce three arrays with consecutive numbers)
Then, for example, by my getitem method, it allows for:
q[0] = array[1,2,3,4]
q[0][1] = 2
Now, I'm attempting to design a method to add en element into one of the arrays using the np.insert function such as the following:
class MatrixConverter
#some code here
def __change__(self,n,x):
self[1]=np.insert(self[1],n,x)
return self
Then, my desired output for the case where n=2 and x=70 is the following:
In:q.__change__(2,70)
Out:(array[1,2,3,4],array[5,6,70,7,8],array[9,10,11,12])
However, this gives me a TypeError: 'MatrixConverter' object does not support item assignment.
Any help/debugs? Should I perhaps use np.concentate instead?
Thank you!
Change your method to:
def __change__(self,n,x):
temp = np.insert(self[1],n,x)
self[1] = temp
return self
This will help you distinguish between a problem with the insert and a problem with the self[1] = ... setting.
I don't think the problem is with the insert call, but you need to write code that doesn't confuse you on such matters. That's a basic part of debugging.
Beyond that you haven't given us enough code to help you. For example what's the "getitem".
Expressions like array[1,2,3,4] tell me that you aren't actually copying from your code. That's not a valid Python expression, or array display.

Is there any difference between fromlist() method and extend() method of Python array module?

The fromlist() method and extend() method are both used to extend the array by list in the array module.
There is no difference in how it is returning and handling runtime errors.
Almost both behave the same, but why there are two different methods with the same functionality?
I checked in Python docs, Source code but didn't find anything unique.
let me know if I'm missing out on anything here.
Thanks in Advance!
#Sample code
from array import array
arr = array('i',[1,2,3,4,4])
templist = [5,6]
arr.extend(templist)
#arr.fromlist(templist)

typing.Tuple from list of types

I have a list of type objects and want to construct a typing.Tuple object. Is there a way to do this?
tys = [int, str] # This is known only at runtime
x = typing.Tuple(tys) # TypeError: Type Tuple cannot be instantiated; use tuple() instead
Any help will be appreciated. Thanks.
Edit: For clarification about the question-
What I am trying to do - visit a Tuple in python AST and annotate its type. For this the list tys is made out of a loop (and so, I could not start with a tuple in the start). Now, I definitely have to annotate it with a typing.Tuple object and hence the question.
I got the solution.
x = typing.Tuple[tuple(tys)] # This works
Edit: This works for all typing constructs. For eg. while typing.Union(tys) and typing.Union[tys] will give an error, typing.Union[tuple(tys)] works. I am not sure if this is a general "python" thing, or it is special with the typing module. I will update this answer once I know that.

Is this an ideal way to automate object instantiation using functions?

I'm trying to design a function in Python which instantiates a number of objects based on a user input. I've derived one which works, and it looks as follows
class Node(): ...
def initialise():
binary_tree=[]
opt=int(input("Enter the number of nodes you want\n"))
for i in range(opt):
a=Node()
binary_tree.append(a)
although I'm not sure that this is the ideal way to do this.
Is there a better way of programming a function such as the one I've described, or is the above method sufficient for efficiency and clarity purposes?
Any responses are appreciated, thank you in advance.
Your code seems to work ok.
There are other options to format it; for example, you could use list comprehension, which might be slightly faster than using .append() and also uses slightly less code:
def initialise():
opt = int(input("Enter the number of nodes you want\n"))
return [
Node()
for _ in range(opt)]
Careful: this (as well as your version) code might raise a ValueError if the uses enters a string that cannot be converted to int.

jitclass vs extension API : what can be used in a list?

So I did not follow numba developments for a while and I discovered a LOT of exciting things, like #jitclass and list support.
So I wanted to try it out, but if I try to have a list of my jitclass structure in a nopython block I get the error :
reflected list(instance.jitclass.Interval#42f9788<lo:float64,hi:float64>): unsupported nested memory-managed object
With the simple following class
#jitclass([('lo', types.float64), ('hi', types.float64)])
class Interval(object):
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
#property
def width(self):
return self.hi - self.lo
And the simplest corresponding code :
#jit(nopython=True)
def f(my_list):
return my_list
f([Interval(1,2)]*10)
However if I follow the example of using the lengthy Extension API here, I do not get any problem with having a list of Interval.
I thought jitclass was basically a fast way of doing what the lengthy example of the extension API does, am I mistaken? How can one achieve it without having to write these long error prone binding functions?
This doesn't completely answer your question, but if you want a quick work-around, I discovered that unlike lists, tuples seem to work:
f((Interval(1,2),)*10)
gives the output
(<numba.jitclass.boxing.Interval at 0x10d8d0d50>,
<numba.jitclass.boxing.Interval at 0x10d8d0d70>,
[... clipped ...]
<numba.jitclass.boxing.Interval at 0x10d8d0e90>)
This was actually added in Numba 0.39 (http://numba.pydata.org/numba-doc/0.39.0/release-notes.html#version-0-39-0)
List has gained support for containing reference-counted types like NumPy arrays and list. Note, list still cannot hold heterogeneous types.
So now it woks directly.

Categories