Homunculus Reticulli
Homunculus Reticulli

Reputation: 68466

How to write a generator for this function

For some bizarre reason, I am struggling to get my head around iterators/generators as used in Python (I write/use them with no problem in C++ - but somehow I can't seem to grok how to write one using Python).

I have a mathematical function of the form:

f(a,b) = ( v1(a) - v1(b) ) / ( v2(a) - v2(b) )

Where v1 and v2 are equal length 1D vectors.

I want to write a function (actually, a generator), that generates the output of f() as defined above.

Can anyone help?

[[Edit]]

My notation may have been confusing. I hope to clarify that. The function described above return a set of values. With the argument b taking on values, in the interval (a,b]

So for example if we call f(1,5), the function will return the following values (not functions -in case my clarification below causes further confusion):

f(1,1)
f(1,2)
f(1,3)
f(1,4)
f(1,5)

Upvotes: 0

Views: 233

Answers (2)

amit
amit

Reputation: 10882

You can use generator expression:

def f(a, b):
  return ((v1[a] - v1[i]) / (v2[a] - v2[i]) for i in xrange(a, b+1))

Or a generator function

def f(a, b):
  for i in xrange(a, b+1)
    yield (v1[a] - v1[i]) / (v2[a] - v2[i])

Upvotes: 1

Tadeck
Tadeck

Reputation: 137410

The generator may look like that, since there is no iteration (as kindall correctly noted).

def f(a, b):
    yield (v1[a] - v1[b]) / (v2[a] - v2[b])  # be careful about division!

Couple notes:

  • there is nothing to iterate through, and generators are generally used in iterations,
  • be careful about divisions: in Python 2.x a / b returns integer if both a and b are integers (so 4 / 3 == 1) - you can avoid this by using floats or by from __future__ import division,

Upvotes: 0

Related Questions