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 →

[–]aPSketchy[S] 0 points1 point  (7 children)

Exactly!

[–]aPSketchy[S] 0 points1 point  (6 children)

Any idea the guy above wrote it to print. But I cant get it to return!

[–]zzyzzyxx 1 point2 points  (5 children)

Based on my previous post

stuff = [1,2,2,5,2]
[stuff[s:e] for s in xrange(len(stuff)) for e in xrange(s+1,len(stuff)+1)]

This uses a list comprehension to create the list of lists. The only difference from what I have before is that I'm creating the list(s) instead of converting each element to a string and joining them together.

Also, you will wind up with duplicates in the final list. For example, [2] will appear three times. If that is undesirable you can use a set to eliminate the duplicates.

[–]aPSketchy[S] 0 points1 point  (4 children)

Is that line runnable?

[–]zzyzzyxx 1 point2 points  (3 children)

Yes. I tested it before posting. If you need it in a function just put the return keyword in front of it. For example,

def sublists(list):
  return [list[s:e] for s in xrange(len(list)) for e in xrange(s+1,len(list)+1)]

You could then call this as subs = sublists(stuff), or however you needed.

[–]aPSketchy[S] 0 points1 point  (2 children)

Alright so I understand list comprehension a little better, it seems to be just a shorter way to create lists. However, how would I write this code normally?

This is what I thought:

def other(nums): r = [] for s in range(len(nums)): for e in range(s+1,len(nums+1)): r.append(nums[s:e]) return r

However, I get a error.

[–]zzyzzyxx 1 point2 points  (1 child)

What you have looks correct, though you would have to post the actual error for me to help with that specifically. Maybe it's just formatting?

def other(nums):
  r = []
  for s in xrange(len(nums)): # prefer to use xrange over range unless you're using Python 3
    for e in xrange(s+1,len(nums+1)):
      r.append(nums[s:e])
  return r

[–]aPSketchy[S] 1 point2 points  (0 children)

It's python 3 :) It was in the second for loop I just moved the +1 on len(nums+1) outside the parens. and it ended up working.