Skip to content
Snippets Groups Projects
2.7 Exercises.py 1.14 KiB
Newer Older
# question 1
Michael Mutote's avatar
Michael Mutote committed
def rotateR(val):
Michael Mutote's avatar
Michael Mutote committed
    return val[-1] + val[:-1] if len(val) > 0 else None
Michael Mutote's avatar
Michael Mutote committed


Narender Kumar's avatar
Narender Kumar committed
# question 2
def rotateL(val):
    return val[:-1] + val[0] if len(val) > 0 else None


# question 3
"""
tnbeats's avatar
tnbeats committed
    The functions rotateR(val) rotateL(val) work for both lists and strings
because they use slicing, which is supported by both data types in Python.
Narender Kumar's avatar
Narender Kumar committed

tnbeats's avatar
tnbeats committed
Example rotateR using strings and lists  -- rotateR("abc") == "cab" and rotateR([1,2,3,4]) == [4,1,2,3]
Example rotateL using strings and lists  -- rotateL("abc") == "bca" and rotateL([1,2,3,4]) == [2,3,4,1]
Narender Kumar's avatar
Narender Kumar committed
"""


Michael Mutote's avatar
Michael Mutote committed
# question 4
def rotateRx(val):
tnbeats's avatar
tnbeats committed
    val[:] = [val[-1]] + val[:-1]
Michael Mutote's avatar
Michael Mutote committed


# question 5
tnbeats's avatar
tnbeats committed
'''
    rotateRx cannot be modified to work for strings without returning a value. Python strings are immutable. They cannot be
    modified once they are created:
    ```TypeError: 'str' object does not support item assignment```
    So the only way to achieve this would be to return a value and assign it back.
'''
Michael Mutote's avatar
Michael Mutote committed

tnbeats's avatar
tnbeats committed

Narender Kumar's avatar
Narender Kumar committed
# question 6
Michael Mutote's avatar
Michael Mutote committed
def rotateR2(val):
    return rotateR(rotateR(val))
tnbeats's avatar
tnbeats committed


# question 7
def rotateRx2(val):
    rotateRx(val)
    rotateRx(val)


# question 8
l = [[1, 2, 3]] * 2
print(l)
rotateRx(l[1])
print(l)