Reputation: 8376
I'm coding a function to produce , being expression.
Given two lists: Xs
and Ys
and so x
I wrote the algorithm below:
#!/usr/bin/env python
#coding: utf8
from sympy import *
from numpy import *
import json
L = {}
x = Symbol('x')
expresion = ''
def lagrange(Xs, Ys, x):
for k in len(Xs):
if k != 0 or k != len(Xs)-1: #si no es el primero o el último término de la sumatoria
expresion = expresion + '+' + Ys[k] + '*'
elif k==0:
expresion = expresion + Ys[k] + '*'
for i in len(Xs):
if k==i:
continue # Si i==k saltamos esta iteración para eliminar división sobre cero
expresion = expresion + '(' + '(' + x + '-' + Xs[i] +' )' + '/' + '(' + Xs[k] + '-' + Xs[i] + ')' +')'
print simpify(expresion)
When I ran:
#!/usr/bin/env python
#coding: utf8
from lagrange import *
lagrange([0,1,2,4],[-1,0,7,4,63],3)
I got:
[......]line 12, in lagrange
for k in len(Xs):
TypeError: 'int' object is not iterable
[Finished in 0.5s with exit code 1]
So how should I iterate over Xs
and Ys
elements and so include condition that if i=k
it will continue
over the loop?
Upvotes: 0
Views: 81
Reputation: 8326
for k in range(len(Xs))
Will give you all the possible indicies in Xs.
len(Xs)
simply returns an int
, which is not iterable. You would want to do the same for your i
loop.
Upvotes: 2