Anthony
Anthony

Reputation: 113

Defining a function on an array

def featureScaling(arr):

     arr= [x1,x2,x3]
     y=(x2-x1)/(x3-x1)
     return y

data = [115, 140, 175]
print (featureScaling(data))

I want to define a function on an array that divides the difference of the of the first two terms by the difference of the third and first term but I keep getting an error saying that x1 is not defined. I am new to coding and could really use the help.

Upvotes: 0

Views: 853

Answers (5)

Albin Paul
Albin Paul

Reputation: 3419

You are passing an array to a function this array -> is pointing to some memory location , In you code. you are trying assign you array to point to a different memory location,its fine to do it but the values used must be defined before . Now what i have done is i have just remove that statement and just used the elements , we can address array elements by the index values , arr[0] refers to the first value in array

from __future__ import division
from __future__ import print_function
def featureScaling(arr):
     y=(arr[1]-arr[0])/(arr[2]-arr[0])
     return y

data = [115, 140, 175]
print (featureScaling(data))

This version runs of python3 and python2 with floating point precision

Output

0.416666666667

Upvotes: 0

Raman Kumar
Raman Kumar

Reputation: 129

Use the List Index Concept instead of X1,X2 and X3

 def featureScaling(arr):
        y=(arr[1]-arr[0])/(arr[2]-arr[0])
        return y

 data = [115, 140, 175]
 print (featureScaling(data))

Upvotes: 0

Anurag A S
Anurag A S

Reputation: 731

I guess this would work.
With zero based indexing for a list in Python, you can refer to the elements of a list x by x[0] for the first element, x[1] for the second element and so on.
Since the values of x1 x2 x3 in your code does not have a value, it is not defined and generates an error.

def featureScaling(arr):

     y=(arr[1]-arr[0])/(arr[2]-arr[0])
     return y

data = [115, 140, 175]
print (featureScaling(data))

Upvotes: 0

rahlf23
rahlf23

Reputation: 9019

Your input variable is defined in the scope of your function as arr, but then you proceed to redefine arr to arr=[x1,x2,x3], butx1, x2 and x3 are not defined. Instead, you can use indexing and redefine your function like so:

def featureScaling(arr):

     return (arr[1] - arr[0]) / (arr[2] - arr[0])

data = [115, 140, 175]

print(featureScaling(data))

This returns:

0.4166666666666667

Upvotes: 2

zcleghern
zcleghern

Reputation: 827

arr is an argument in your function, so there's no need to define it in the body of the function. The line arr= [x1,x2,x3] tries to redefine the array that you passed in, which is why x1, x2, and x3 aren't defined. You need to define these 3 items in terms of the array, not the other way around.

Upvotes: 2

Related Questions