0

i want to write a function that accepts two lists, one of x values and one of y(x) values and returns the corresponding y(x) value when given an x value. i also want to use linear interpolation to find y(x) for values of x between the numbers in the list. for example

f = function([3, 4, 6], [0, 1, 2])

print f(3) should return 0.0

so far i don't have a full code but i am attempting to use

interp1d(numpy.array(xs), numpy.array(ys), 'linear') for the interpolation

for i in range(len(xs)): return ys[i] and this for the values in the list, but i dont really know how to put it together

tribo32
  • 333
  • 3
  • 15

1 Answers1

0

You can zip your lists and convert to a dictionary then pass the dictionary to lambda :

>>> f=lambda x: dict(zip([3, 4, 6], [0, 1, 2]))[x]
>>> f(3)
0
>>> f(4)
1

But as the above solution may be raise an KeyError you can use the following factory-function :

>>> def liner(l1,l2):
...     d=dict(zip(l1,l2))
...     def li(x):
...       try :
...          return d[x]
...       except KeyError:
...          print 'please enter a valid number'
...     return li
... 
>>> f=liner([3, 4, 6], [0, 1, 2])
>>> f(9)
please enter a valid number
>>> f(3)
0
>>> f(6)
2
Mazdak
  • 105,000
  • 18
  • 159
  • 188