Need help with coding a function in Python

Larry Hudson orgnut at yahoo.com
Mon Oct 31 22:26:03 EDT 2016


On 10/31/2016 03:09 PM, 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)
>

I'm not looking at your link or your code, just your description of the problem.
Paraphrased:  "A list of the first n elements of a sequence"

No function necessary, just use slicing...

newlist = oldlist[:n]

list:    [1,2,3,4,5,6,7,8,9,10][:5] gives [1,2,3,4,5]
tuple:   (1,2,3,4,5,6,7,8,9,10)[:5] gives (1,2,3,4,5)
string:  "Hello there"[:5] gives "Hello"

Works for sequences shorter than n as well, which gives the full (short) sequence.

list:    [1,2,3][:5] gives [1,2,3]
etc...

-- 
      -=- Larry -=-



More information about the Python-list mailing list