I used scipy.linalg.solve to solve a matrix equation, where X, L, and K are matrices.
K = solve(X, L)
which returned:
K = [1 2 3]
Although the values are correct, I was expecting to see the following format:
K = [1, 2, 3]
that is, with the commmas, but in any case the values are correct in what was returned.
Now I would like to access the individual elements of K, but I can't seem to do it.
If I run
type(K)
I get "NoneType"
If I run
numpy.shape(K)
I get "()"
If I run
print(K[0])
I get "NoneType object is not subscriptable"
How can I access the values of the array?
Thanks
Andy
I was able to resolve the issue as follows:
X = numpy.linalg.inv(X)
K = numpy.dot(X, L)
print(K)
K = [1 2 3]
type(K)
numpy.ndarray
This is really a workaround rather than an answer to my problem with scipy.linalg.solve, but I can move forward with this solution, as K is now a numpy array. Thanks to everyone for your helpful responses.
Related
I want to work with a given group of elements and reorder them as the function set_partitions do but adding a condition to this lists, I will try to explain my problem in a understandable and simple way. A example of how this function works,
from more_itertools import set_partitions
a=[1,2,3]
print(list(set_partitions(a)))
And return the possible agrupations,
[[[1, 2, 3]],
[[1], [2, 3]],
[[1, 2], [3]],
[[2], [1, 3]],
[[1], [2], [3]]]
I want to put a constrain in this function (for example could be, the groups created need to sum a even number). I can simply extract the arrays and apply the constrains, but my problem is that I need to do it for a huge number of list elements, and my computer dies before finishing. If I apply the constrain directly to the function set_partitions the problem will be reduced because the constrain applied is very strong, i mean, for example it reduce a total amount of 4213597 million possible combinations to 12k valid combinations (but i can not go further because of memory problems), so applying the condition will solve the problem.
For this I need to understand the function set_partitions, this function can be used only copying the following code without needing other auxiliar functions, or to import anything,
def set_partitions(iterable, k=None):
L = list(iterable)
n = len(L)
def set_partitions_helper(L, k):
n = len(L)
if k == 1:
yield [L]
elif n == k:
yield [[s] for s in L]
else:
e, *M = L
for p in set_partitions_helper(M, k - 1):
yield [[e], *p]
for p in set_partitions_helper(M, k):
for i in range(len(p)):
yield p[:i] + [[e] + p[i]] + p[i + 1 :]
for k in range(1, n + 1):
yield from set_partitions_helper(L, k)
I' have experience programming and is my work but I do not arrive to this level, so there is some things in the function that I do not understand, as for example what is doing,
e, *M = L or the following elements in the helper function.
I need some help understanding how work this function for finding where the condition can be placed.
Thanks a lot!
Addition explaining my specific case:
The elements I'm trying to group in partitions are matrixes in tensorial product, for example chains of fixed lenght for example,
A element will be a chain of this style, that we can represent as a string,
'xz11y'
I want the elements of the subgroups to commute, 1 commute with everything, x/y/z only commutes with itself (and the identity), so we need to compare the chains only, so for example if we have the 3 matrixes,
['1z'],['zz'],['x1']
A valid agrupation will be
'1z','zz' | 'x1'
Because '1z' commutes with zz.
A invalid agrupation will be
'1z' | 'zz', 'x1'
Because 'zz' and 'x1' have a x and a z in same position, and this operators do not commute.
This is simplified, so I have a Hamiltonian of about 19 or more separate operators of this type and I need to find the agrupations that conserve this commutation.
I am using a binomial tree as a list with 2^T - 1 'nodes' and want to create a set of subsets that work within some given criteria (outlined below) on the elements of the list. Right now, I use the following code to generate a tree
def gen_nodes(T):
nodes = []
for t in range(T):
for i in range(2**t):
nodes += [[t,1 + i]]
return nodes
For instance, for T = 1, we get the root
gen_nodes(1) = [[0,1]],
but for T = 2 and T = 3, we get
gen_nodes(2) = [[0,1], [1,1], [1,2]]
gen_nodes(3) = [[0,1], [1,1], [1,2], [2,1], [2,2], [2,3], [2,4]],
et cetera. Right now, I'm using a powerset function courtesy of this wonderful contributor,
def powerset(s):
x = len(s)
masks = [1 << i for i in range(x)]
for i in range(1 << x):
yield [ss for mask, ss in zip(masks, s) if i & mask]
This has worked great for me, but as I'm sure you've caught at this point, the length of the powerset gets entirely too large with the time complexity of something like O(2^(2^T)). Initially, I was going to just create the entire set by brute force and then apply constraints on valid subsets after creating the larger set of subsets, but it seem's like I'm going to run into some overflow problems if I don't modify the powerset function with those constraints.
Basically, I only want the lists e within the output of ls = list(powerset(gen_nodes(T))) such that for all i from 0:len(e), e[i] in e implies [e[i] - 1, e[i]] OR [e[i] - 1, e[i] - 1] are in e.
Returning to the binary tree analog, this is basically saying for all [t,i] in [0,t] x [1,t+1], [t,i] in e only if [t-1,i] OR [t-1,i-1] in e, basically if [t,i] is in e, there there must be at least one "path" from [0,1] to [t,i] where each node in the path is also in e. I suspect this will condense the size of subsets output immensely, but I'm unsure of how to implement it. I think I might have to forgo using the powerset function, but I'm not sure how to code it in that case, and would therefore appreciate any help I can get.
EDIT: I should include desired output as commented. Additionally, I've included the function that has been 'working' for me thus far, but it's horribly inefficient currently. First, let pset be the function that solves this problem. and pg(i) = pset(gen_nodes(i)) for brevity. Then
pg(1) = [[0,1]],
pg(2) = [[[0, 1]], [[0, 1], [1, 1]], [[0, 1],
[1, 2]], [[0, 1], [1, 1], [1, 2]]]
Unfortunately, this set still grows very fast (pg(3) is 17 lists of length up to 6 pairs, pg(4) is 97 lists of length up to 10 pairs, etc), so I can't share much more on this post. However, I did develop a function that works, but seems to be horribly inefficient (pg(6) takes half a second, and then pg(7) takes 4 minutes to complete). It is attached below:
import time
def pset(lst):
pw_set = [[]]
start_time = time.time()
for i in range(0,len(lst)):
for j in range(0,len(pw_set)):
ele = pw_set[j].copy()
if lst[i] == [0,1]:
ele = ele + [lst[i]]
pw_set = pw_set + [ele]
else:
if [lst[i][0] - 1,lst[i][1]] in ele or [lst[i][0] - 1,lst[i][1] - 1] in ele:
ele = ele + [lst[i]]
pw_set = pw_set + [ele]
print("--- %s seconds ---" % (time.time() - start_time))
return pw_set[1:]
Here, I just checked if the 'node' being added had at least one of the nodes preceding it in the set: if not, it was skipped. I checked up to pg(3) and the output is as desired, so I'm thinking it's working, just inefficient. Thus, I've (seemingly) solved the memory overflow problem, now I just need to make this efficient.
I am trying to make a function that creates an array from the functions original array, that starts on the second element and multiplies by the previous element.
Example
input: [2,3,4,5]
output: [6,12,20]
I am trying to use a loop to get this done and here is my code so far
def funct(array1):
newarray = []
for x in array1[1:]:
newarray.append(x*array1)
return newarray
I am at a loss as I am just learning python, and i've tried various other options but with no success. Any help is appreciated
try
A = [2, 3, 4, 5]
output = [a*b for a, b in zip(A[1:], A[:-1])]
You can use a list comprehension like so:
inp = [2,3,4,5]
out = [j * inp[i-1] for i,j in enumerate(inp) if i != 0]
Output:
[6,12,20]
First I apologize if this question has already been asked. I've search for it but found nothing.
Given the following code :
RHO = RHOarray(D,nbInter)
print(RHO)
for k in range(N):
for l in range(D):
j=0
Coord=[0 for i in range(D)]
while ((X[k][l]>mini+(j+1)*step) and (j<nbInter)):
j+=1
Coord[l]+=j
RHO[ ]
for k in range(len(RHO)):
RHO[k]/=N
return RHO
RHO is a D-dimensions array, of size nbInter. (RHOarray is a function that creates such an array). The problem is that according to D's value, I'd need to access RHO[n] if D = 1, RHO[n][m] if D = 2 ... RHO[n][m]...[whatever indice] as D increases. Every indices would actually be Coord[0], Coord[1]... and so on, so I know what I have to put into each indices. To make the question "simpler" : how can I do so the number of "[...]" after RHO increases as much as D does ?
I hope I've been clear. I'm french and even in my native language it's still tricky to explain. Thanks in advance
ps The initial code is longer but I don't think there's need to show it entirely.
You could simply do something like
indices = [1, 2, 3, 4, 5]
value = X
for i in indices:
value = value[i]
print(value)
If X is a numpy array, you could directly do
X[(1,2,3)] instead of X[1, 2, 3] or X[1][2][3]
I am very new to python and I am trying to implement a MSE (Mean Squared Error) from my data. I am trying to access each element in the list and subtract the original data from the mean and square it at the end for the separate step so I can sum it up at the end and divide it by the total number of elements in the list.
For now, I am just trying to access each element in the list and find the difference and put it into the newly created list, newList.
Here is my current code:
for i in range(len(X)):
newList[i] = X[i] - tempList[i]
at first, I tried doing
for i in range(len(X)):
newList[i] = X[i] - mean
However, this gave me typeError saying that I cannot subtract float from list.
So I tried making a new list called tempList and put the mean value into the list by doing this:
for i in range(len(X)):
tempList.insert(i, mean) #now my tempList contains [3.995, 3.995, 3.995 ....., 3.995]
Now it is giving me the same typeError:unsupported operand type(s) for -: 'list' and 'float'.
I am more familiar with java and other C languages and I thought that's the way you edit each element in the list, but I guess Python is different (obviously).
Any tips will be greatly appreciated.
Thanks in advance.
You have a problem elsewhere in the code, and that's why you're getting the type error. The snippets you showed are entirely legit.
X = [ 2, 12, 85, 0, 6 ]
tempList = [ 3, 4, 3, 1, 0 ]
newList = list([0] * len(X))
for i in range(len(X)):
newList[i] = X[i] - tempList[i]
print(newList)
Anyhow, back to your original question, you can use functional style
X = [ 2, 12, 85, 0, 6 ]
mean = sum(X) / float(len(X))
print(mean)
Y = map(lambda x: x - mean, X)
print(Y)