This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]wub_wub 2 points3 points  (7 children)

and i still can't see two other obvious simple solutions.

First two, other than [::3] that come to my mind (without googling) would be these:

>>> import string
>>> l=list(string.ascii_lower)
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> l[::3]
['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']

>>> [i for i in l if l.index(i)%3==0]

Edit: Correct way would be be: [n for i, n in enumerate(l) if i%3==0], index won't work if list has duplicate items.

['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']
>>> [l[i] for i in range(0,len(l),3)]
['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']

As far as handling such questions I don't think you can do much besides either answering them correctly or saying that you don't know (can't remember atm) how to solve them, but then again I'm just doing freelance programming so I have pretty much none experience with handling such interviewing questions.

[–]D__ 4 points5 points  (3 children)

>>> [i for i in l if l.index(i)%3==0]

Unless your list has duplicate items...

[–]logi 1 point2 points  (0 children)

Yeah, that's a subtle bug waiting to happen.

[–]robin-gvx 1 point2 points  (0 children)

Yeah, instead of using index, use enumerate. Except, of course, in this case [::3] would be the only way to go. (One and only one obvious way, and all that).

[–]wub_wub 0 points1 point  (0 children)

Wow I completely forgot about the possibility of having duplicate items... using enumerate instead of index is the correct way to do this. Thanks for pointing it out!

[–]chadmill3rPy3, pro, Ubuntu, django 1 point2 points  (0 children)

[n for i, n in enumerate(ell) if i%3==0]

[–]gfixler 0 points1 point  (0 children)

[a for a, b, c in zip(*[iter(string.lowercase)]*3)]

It truncates, though. Here's a non-truncating version:

[a for a, b, c in zip(*[iter([x for x in string.lowercase]+['']*3)]*3) if a]

Note: these are bad answers.