Hello,

I'm a newbie to python and I am having a very hard time trying to solve a homework question that I have. Here it is:

Given a list of items, write a program that generates a list of lists of the following form: [a,b,c,…,z] → [[z], [y,z], [x,y,z], … , [a,b,…,y,z]]

I know that I have to use slicing and I even thought list comprehension may be a good way to solve, but I can not up with the syntax. I tried a for loop, but I think this problem can be solve with out it. Any help would be appreciated.

Dani AI

Generated

Good hints from , , and — below are two concise, different approaches that avoid repeating the exact slicing examples already shown. One is a lazy generator (streaming, low overhead until you consume it) and the other is an eager builder that uses a deque for efficient prepends.

from collections import deque

def suffixes(seq):
    """Yield lists: [last], [second_last, last], ..., full sequence."""
    seq = list(seq)          # accept any iterable
    d = deque()
    for item in reversed(seq):
        d.appendleft(item)   # O(1) prepend
        yield list(d)        # yield a fresh list each time

Example usage:

# >>> list(suffixes('abc'))
# [['c'], ['b', 'c'], ['a', 'b', 'c']]

Notes and gotchas:

  • This approach yields fresh lists so later mutation of returned sublists won't affect earlier results. Always copy (here list(d)) when the working container is reused.
  • Time and space complexity are O(n^2) in total (you produce ~n(n+1)/2 elements across all sublists). Use the generator if you only need to process outputs sequentially.
  • If you prefer an eager single-list result but want faster front insertion than list.insert(0, ...), the deque-based loop above can collect into a list with out.append(list(d)) then return out.

Why this can be handy: it sidesteps negative-index slicing and shows a pattern that works uniformly for any iterable, lets you stream results, and avoids accidental aliasing of sublists.

Recommended Answers

All 6 Replies

A hint

from string import ascii_lowercase as letters
print letters[-1:]
print letters[-2:]

print
location=25
print letters[location:]
location -= 1
print letters[location:]

Interesting homework, list() and list-comprehension with step=-1 and slicing [ix:] will get you there easily.

Consider this example:

def ls():
    l = [1,2,3,4,5]
    for i in range(len(l)):
        print l[-(i+1):],

Now try to figure out how to combine those lists and apply what woooee said to get your desired result.

Just a few more hints ...

s = "abcdefg"

for x in range(1, len(s)+1):
    print(s[-x:])
    print(list(s[-x:]))

Thank you everyone for the help!

Came up with this:

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']

S = []

for i in range(len(L)-1,-1,-1):
     S.append(L[i:])

Great job. Here's another version of your problem:

l=[]
print [l[-(j+1):] for j in range(len([l.append(chr(i)) for i in range(97, 123)]))]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.