0

I come from a C-like language background, so the code below looks pretty confusing to me:

#source: https://www.youtube.com/watch?v=4n7NPk5lwbI (timestamp 3:39)
def rotation(t):
    """ Return list of rotations of input string t"""
    tt = t * 2       #why??, and is this concatenation?
    return [ tt[i:i+len(t)] for i in xrange(0, len(t)) ] #what is this for loop return/splice?

This should produce for a given input, say t = "abc$":

[[abc$], [bc$a], [c$ab], [$abc]]

Or some permutation of the above output. Could someone explain what this code is doing? Including an example of input/output. I got a vague idea when typing this out, but it would help me to hear from someone that knows python.

Silver Flash
  • 871
  • 3
  • 7
  • 16

3 Answers3

2

This isn't a normal for lop, rather it is a list comprehension.

In short, a list comprehension iterates over an iterable, and builds a new list from operations over each element.

Python supports operator overloading, so the multiplication line is simply the implementation of multiplication on Python sequences, which is generally to repeat it:

>>> [1, 2] * 2
[1, 2, 1, 2]
>>> "12" * 2
'1212'

Essentially, this code duplicates the sequence, then creates a sliding window over the new double-length sequence.

Note that collections.deque has a method for rotation, so a good solution for this task is simply:

def rotation(t):
  current = collections.deque(t)
  yield list(current)
  for _ in range(len(current)):
    current.rotate(1)
    yield list(current)

(You could of course use "".join() for string results.)

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
1
def rotation(t):
    """ Return list of rotations of input string t"""
    tt = t * 2       #why??, and is this concatenation?
    return [ tt[i:i+len(t)] for i in xrange(0, len(t))]

tt = t * 2 - why is this concatenation needed? So that you can easily choose substring using from index and to index.

abc$ would become abc$abc$

[ tt[i:i+len(t)] for i in xrange(0, len(t))] - This is a list comprehension. It's like a one liner for loop. You are looping and also building a list of different rotations of the string i.e you are using sliding window to get different rotations

And the final output is ['abc$', 'bc$a', 'c$ab', '$abc']. It's not a nested list

bigbounty
  • 16,526
  • 5
  • 37
  • 65
1
def rotation(t):
    tt = t * 2  # 2 copies of the string t, yes this is concatenation

    # The list comprehension you questioned is basically equivalent to this
    result = []
    for i in xrange(0, len(t)):
        result.append(tt[i:i+len(t)])  # the substring from i (inclusive) to i+len(t) (exclusive)
    return result
Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37