Make me beautiful (code needs help)

Daniel Dittmar daniel.dittmar at sap.com
Tue Jul 23 11:32:08 EDT 2002


Mark wrote:
> Ok, I have the following data:
>
> data["A"] = [1,2,4,10,50]
>
> and I want to get:
>
> data["new"] = [?, 1, 2, 6, 40]
>
> That is, I want to get the successive differences into their proper
> place. I don't care what is in the question mark spot.  I'll figure
> that out later.
>
> Here's my current code:
>
> for i in range(len(data["A"])):
>      try:
>           data["new"].append(data["A"][i] - data["A"][i-1])
>      except OutOfBounds:
>           data["new"].append("?")
>

from __future__ import generators

def difference (collection):
    iterator = iter (collection)
    yield None
    last = iterator.next ()
    for current in iterator:
        yield current - last
        last = current

print list (difference ([]))
print list (difference ([1,2,4,10,50]))

It's a bit longer, but it works with any collection that is iterable.

> Now, the other problem, is that in general, I want to fill
> data["new"] with an arbitary function of the values in data["A"].  As
> a dumb example, I might want to fill data["new"] with copies of the
> mean (average) of data["A"].  So, in some cases, the new values are
> relative to the current location (ie i and i-1) and in other they are
> absolute (ie all of them).

If you want a moving average, then the solution above is easily generalized.
If you want the simple average, then a simple function should be sufficient,
there is no need to over generalize.

def avg (values):
    sum = 0
    for value in values:
        sum += value
    return sum / float (len (values))

Daniel






More information about the Python-list mailing list