Home > OS >  How do I iterate over two ranges whilst keeping one the same?
How do I iterate over two ranges whilst keeping one the same?

Time:10-17

I want to iterate for this function that takes parameters theta, X and i.

hypothesis = theta[0]*X[i][0] theta[1]*X[i][1] theta[2]*X[i][2] ...

theta is 1-D array and X is a 2-D array. I tried using for loops like this, but Im not sure how to run through all i for theta[0]*X[i][0] first then run through i for theta[1]*X[i][1] and so on.

for i in range(i):
    for j in range(j):
        hypothesis  = theta[i]*X[j][i]

CodePudding user response:

Do you want to do the dot product of theta with the ith row of X?

If so, then you could do something like this:

def dot_product(theta, x, i):
  hypothesis = 0
  for j in range(len(theta)):
    hypothesis  = theta[j] * x[i][j]
  return hypothesis

or you could make it more concise through Python's generator functionality:

def dot_product(theta, x, i):
  return sum(theta[j] * x[i][j] for j in range(len(theta)))
  • Related