Need help with coding a function in Python
MRAB
python at mrabarnett.plus.com
Mon Oct 31 18:37:19 EDT 2016
On 2016-10-31 22: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!!!!!
>
> 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):
>
> def reca(n):
> rlist=[0]
> while len(rlist) < n:
> if (rlist[-1]-n) > 0 and (rlist[-1]-n) not in rlist:
> rlist.append(rlist[-1]-n)
>
> else:
> rlist.append(rlist[-1]+n)
>
> return(rlist)
>
When you're calculating a[n], what's n?
Well:
When you're calculating a[1], you already have a[0], or 1 element.
When you're calculating a[2], you already have a[0] and a[1], or 2 elements.
So, in general, when you're calculating a[n], you already have a[0] ...
a[n - 1], or n elements.
The value of n is the length of the list so far.
More information about the Python-list
mailing list