I am trying to run a simple loop in Python to avoid having to run the same code over and over but I keep getting an error. I think this is due to the fact that the loop runs in a function. To illustrate this let me show you when the code is not carried in the loop, repeatedly form:
def cosine_sim0(data0, data1):
    tfidf = vectorizer.fit_transform([data0, data1])
    return ((tfidf * tfidf.T).A)[0,1]
print(cosine_sim0(data0, data1))
def cosine_sim1(data1, data2):
    tfidf = vectorizer.fit_transform([data1, data2])
    return ((tfidf * tfidf.T).A)[0,1]
print(cosine_sim1(data1, data2))
def cosine_sim2(data2, data3):
    tfidf = vectorizer.fit_transform([data2, data3])
    return ((tfidf * tfidf.T).A)[0,1]
print(cosine_sim2(data2, data3))
def cosine_sim3(data3, data4):
    tfidf = vectorizer.fit_transform([data3, data4])
    return ((tfidf * tfidf.T).A)[0,1]
print(cosine_sim3(data3, data4)) 
As it can be seen, the loop should create 4 separate functions: cosine_sim%d %i, it should also add a number to the one starting from in the function and in the printing result. Having these into account I attempt by building the loop using the following code:
my_funcs = {}
    for i in range(4):
        def foo(data%d %i, data%d+1 %i):
                tfidf = vectorizer.fit_transform([data%d %i, data%d+1 %i])
                return ((tfidf * tfidf.T).A)[0,1]
        foo.func_name = "cosine_sim%d" % i
        my_funcs["cosine_sim%d" % i] = foo
    globals().update(my_funcs) # Export to namespace
    cosine_sim2(data1, data2)
As most of you can probably guess, the error retrieved states invalid syntax. Any suggestions of where the problem lies?
kind regards