Error then trying to multiply two arrays by using '#' [duplicate] - python

This question already has answers here:
Matrix Multiplication in pure Python?
(12 answers)
Closed 2 months ago.
I am trying to multiply two arrays by using '#' but this is the error I get
a#b
unsupported operand type(s) for #: 'list' and 'list'
I read that '#' is used for matrix multiplication, which is what I need

From the error message it appears as though you are using lists. You need to use arrays for which you can use the numpy module like this:
import numpy as np
x = [1,2,3,4]
y = [10,20,30,40]
x = np.array(x)
y = np.array(y)
z = x#y
print(z)
which returns this:
300
If you want to multiply lists without numpy you can do this:
# method 1
z = 0
for i, v in enumerate(x):
z = z + (x[i]*y[i])
print(z)
# method 2
z = sum([x*y for x,y in zip(x,y)])
print(z)
Both would return the same value as above...

Related

Python Help -- How to extract a specific range of values from a 1D array? [duplicate]

This question already has answers here:
Numpy: find index of the elements within range
(12 answers)
Closed 2 years ago.
In python, is there a command that allow me to extract a specific subset of a given array?
For example, let's say that I have the following 1D array:
x = np.array([1,0,35,9,1,23,10,2,4,8,3])
How do I get only element between 2 and 10? So, I want the output to be something like:
subx = [9,2,4,8,3]
Just to clarify, I do not want the indices. I just want the values.
One of the methods is to use a list comprehension
Note: Inclusive of 2, the lower bound but excluding 10, the upper bound
x = [1,0,35,9,1,23,10,2,4,8,3]
y = [c for c in x if c >=2 and c<10]
Since you are using numpy
Method 1:
import numpy as np
y = np.where(np.logical_and(x>=2, x<10))
Method 2:
import numpy as np
x = np.array([1,0,35,9,1,23,10,2,4,8,3])
y = x[(x>=2) * (x<10)]
Hope this helps
a=[1,0,35,9,1,23,10,2,4,8,3]
li=[]
for ele in a:
if ele in range(2,10):
li.append(ele)
print(li)
Output:
[9, 2, 4, 8, 3]
Since you are using a numpy array, you can do:
x[(x >= 2) & (x < 10)]

How to perform a calculation n amount of times? [duplicate]

This question already has answers here:
'NoneType' object has no attribute 'append' python
(4 answers)
Closed 3 years ago.
I have a homework problem where we have to count the amount of rectangular blocks used in the construction of a pyramid design. The pyramid design consists of 'x' rows, 'y' columns and 'z' layers. For example if the values x = 2, y = 3, z = 1 were entered, the program would output 6, which would be the number of blocks. Every layer that comes after has one more row (x+1) and one more column(y+1). So if the values x = 2, y = 3, z = 2 were entered, 12 would be returned which is the number of total blocks and so on.
This is what I have so far but I keep getting an error:
def blocks(x,y,z):
if z == 1:
return x * y
else:
result = []
total = x * y #<--- initial calculation
for i in range(z):
total = ((x+1)*(y+1))
result = result.append(total)
print (blocks(2,3,4))
The error message I get is:
result = result.append(total)
AttributeError: 'NoneType' object has no attribute 'append'
list.append() returns None, so your reassignment:
result = result.append(total)
will reassign result to None on each iteration of your loop. Instead, remove the reassignment, since append modifys the existing list in place.
replace result = result.append(total)
with result.append(total)
when you append an object to a list, there is no need to set the result equal to a new list; it does the appending on the list in place.

Python: Compare array elements with float, getting a boolean list

I want to compare all elements of a two-dimensional list
array with a float
x.
The result should be a list:
b = [[True, False,...],...].
I tried it like that:
import numpy as np
array = [[a1,a2,...], [a3,a4,...],...,]
x = 2.0
b = np.array([a >= x for a in array])`
"TypeError: '>=' not supported between instances of 'list' and 'float'"
When I use a one-dimensional list it works fine.
Thanks in advance!!
b = np.array([[a >= x for a in row] for row in array])

Adding an integer number to all elements of a list that are not integer

Method 1 : Error : ufunc 'add' did not contain a loop with signature matching types dtype('
x = numpy.array(x)
x_5= x + 5
Method 2 : Error : must be str, not int
x_5 = [x+5 for x in x]
Method 3 : Error : invalid literal for int() with base 10: '-0.081428368'
I tried to convert the x data first to integer
x_int = list(map(int, x))
x_5 = [x+5 for x in x]
method 4 : Error : 'numpy.float64' object is not iterable
x = numpy.array(x, dtype=float)
x = numpy.array(x)
x_piu_5= x + 5
Method 5 : Error : float object is not iterable
x_piu_5=[]
xfl=[float(i) for i in x]
x_piu_5[:] = [x + 5 for x in xfl]
Hi All
I am trying to add an integer number to my list which contains a lot of numbers like 0.00085695 , etc, and I have used two methods but I have been unsuccessful
Update 1 : Added method 4 , I have obtained the values I wanted, but the problem now is that it say the numpy.float is not iterable
Update 2 : Added method 5, Should I convert the float to string before iteration ?
The core of your problem is that your list x contains strings representing floating-point numbers. You need to convert those strings to float objects.
More precisely:
Method 1 can be fixed by using dtype=float, as suggested on the comments:
x = numpy.array(x, dtype=float)
x_5 = x + 5
Method 2 can be fixed by converting the items of x to float values before adding 5:
x_5 = [float(i) + 5 for i in x]
Method 3 can be fixed by using float instead of int, as your values are not integers but rather floating-point values:
x_float = list(map(float, x))
x_5 = [i + 5 for i in x_float]
Note that this solution is equivalent to method 2, just a bit slower and more space consuming, as you are creating an additional list.
Method 4 can be fixed by removing the spurious x = numpy.array(x) line. You will end up with the same code as method 1.
As for method 5, I suspect that x is not the usual list, but rather it's a float object.
Other than converting values to the correct type, another thing you should try is to use different variable names for different things. In your code snippets, you're using x both for your lists/arrays and for the elements of those lists. While it's not always strictly required, using different variable names would solve a lot of confusion and save you from many headaches!

Get a fixed number of items from a generator [duplicate]

This question already has answers here:
How to get the n next values of a generator into a list
(5 answers)
Closed 5 years ago.
What is the most efficient way to get a fixed number of items from a generator?
What I currently do is using zip and range. In this example I take
chunks of size 3 from the generator.
def f():
x = 0
while x < 21:
yield x
x += 1
g = f()
while True:
x = [i for _, i in zip(range(3), g)]
if not x:
break
print x
The background is that the database I use provides a generator object for query results. Than I fill a fixed size numpy array with data and process it as one batch.
Use itertools.islice:
import itertools
for elem in itertools.islice(f(), 3):
print elem
and directly into your numpy array:
my_arr = np.array(itertools.islice(f(), 3))

Categories

Resources