Need help with coding a function in Python

Andrea D'Amore and.damore at gmail.com
Tue Nov 1 06:34:46 EDT 2016


On 31 October 2016 at 23:09,  <devers.meetthebadger.jason at gmail.com> wrote:
> http://imgur.com/a/rfGhK#iVLQKSW
> How do I code a function that returns a list of the first n elements
> of the sequence defined in the link? I have no idea!!!!!

For those who didn't open the page (that you should have linked at
least as direct link to the image rather than to the javascript based
frontend of imgur) here's the description: there's a mathematical
sequence where

    a_0 = 0
    a_n = a_{n-1} - n    if a_{n-1} is positive and not already in the sequence
          a_{n-1} + n    otherwise

so it's based off a simple sequence of kind   a_n = a_{n-1} + n   with
a conditional that brings the value back at times.


> So far this is my best shot at it (the problem with it is that the n that
> i'm subtracting or adding in the if/else part does not represent the
> element's position, but just the n that I am plugging into the function):

Since I've been lately trying to tackle small problems in the most
idiomatic way I can (much to Raymond Hettinger's enjoyable talks'
fault) I had my attempt at it.
You tried to build a list and return it while I make a function whose
return value is then iterated upon:


    def sequence(n):
        """Returns a generator for the mathematical sequence

            a_0 = 0
            a_n = a_{n-1} - n    if a_{n-1} is positive and not
already in the sequence
                  a_{n-1} + n    otherwise
        """

        value, past = 0, {}

        for c in range(n):
            t = value - c
            value = t if (t > 0 and t not in past) else (value + c)

            past[value] = True

            yield value



I'm not sure this can be made without the past state in the closure
since the sequence conditional rule depends on it.

Any hints on how to make it better are welcome.


-- 
Andrea



More information about the Python-list mailing list