Rotate a List
beginnerUp next
Tuples and Sets
Meet two more collection types: tuples for fixed groups of values and sets for unique items.
Next lessonUp next
Meet two more collection types: tuples for fixed groups of values and sets for unique items.
Next lessonOutput will appear here...
The starter code reads a list of integers and a number k. Rotate the list to the right by k positions, so the last k items move to the front, and print the result on one line separated by spaces.
For the input 1 2 3 4 5 and k = 2, a correct solution prints:
4 5 1 2 3
Note that k can be larger than the length of the list. Rotating by the full length gives you the same list back.
Tip
Slicing does most of the work: take the last k items, then everything before them. For big k, the % operator can shrink it to a rotation that does the same thing.
No comments yet. Start the discussion.