G1124E
G1124E

Reputation: 417

Writing Min-Max scaler function

I want to write a function for calculating Min-Max scale in python that return a list.

x = [1, 2, 3, 4]

def normalize(x):

    for i in range(len(x)):
        return [(x[i] - min(x)) / (max(x) - min(x))]

Then calling the function:

normalize(x):

results:

[0.0]

I was expecting the result to be:

[0.00, 0.33, 0.66, 1.00] 

Upvotes: 0

Views: 3686

Answers (3)

R4444
R4444

Reputation: 2114

Based on @shehan's solution:

x = [1, 2, 3, 4]

def normalize(x):
    return [round((i - min(x)) / (max(x) - min(x)), 2) for i in x]

print(normalize(x))

gives you exactly what you wanted. The result is rounded up unlike other solutions (as that's what you wanted).

result:

[0.0, 0.33, 0.67, 1.0]

For loop version of the answer so that op could understand:

x = [1, 2, 3, 4]

def normalize(x):
    # A list to store all calculated values
    a = []
    for i in range(len(x)):
        a.append([(x[i] - min(x)) / (max(x) - min(x))])
        # Notice I didn't return here
    # Return the list here, outside the loop
    return a

print(normalize(x))

Upvotes: 3

Reblochon Masque
Reblochon Masque

Reputation: 36662

You are dividing by max(x), then subtracting min(x):

You are also recalculating max(x), and min(x) repeatedly. You could do something like this instead:

x = [1, 2, 3, 4]

def normalize(x):
    maxx, minx = max(x), min(x)
    max_minus_min = maxx - minx
    return [(elt - minx) / max_minus_min for elt in x]

You can round the results, as suggested by @ruturaj, if that is the precision you want to keep:

return [round((elt - minx) / max_minus_min, 2) for elt in x]

Upvotes: 1

Shehan Ishanka
Shehan Ishanka

Reputation: 593

Try this.

def normalize(x):
    return [(x[i] - min(x)) / (max(x) - min(x)) for i in range(len(x))]

Upvotes: 1

Related Questions