Home > front end >  Rewriting for-loop in an understandable form
Rewriting for-loop in an understandable form

Time:10-25

I would like to rewrite the python for loop below in another form that is easier to understand.

def geo_margin(W,b,X,y):
    return np.min([margin(W,b, X,y[i])
                   for i, x in enumerate(X)])

CodePudding user response:

Do you mean like this ?

import numpy as np

def geo_margin(W, b, X, y):
    data = []                  # Declare a list
    for i, x in enumerate(X):  # loop through X as index -> i and item -> x
        data.append(margin(W, b, X, y[i])) # Add the result of the function call to data

    return np.min(data) # return the minimum of the data
  • Related