0
l = [4,5,7,9,10,12]

def rotation(l,n):
    return l[n:] + l[:n]

print rotation(l,3)

Let "l" be the above mentioned list, with the above code I am able to rotate the first half [4,5,7] with the other half [9,10,12], getting the desired output [9, 10, 12, 4, 5, 7]. However what I am trying to do and I cannot figure out, is in the case when we have an odd number of elements. Let's say l = [4,5,7,8,9,10,12] I want the odd number that is in the middle, in this case [8], to remain in the middle, and the first half to rotate with the last half, getting the output in this case [9,10,12,8,4,5,7]

Thanks in advance.

4

2 回答 2

1
def rotation(l,n):
    if len(l) % 2 == 0:
        return l[n:] + l[:n]
    else:
        return l[-n:] + [l[n]] + l[:n]
于 2018-11-10T14:13:51.957 回答
1

如果我明白这一点,这可能会奏效。

但我认为不需要将第二个参数传递给方法(除非您正在寻找不同的东西)。

def rotation(l):
    size = len(l)
    n = size // 2
    res = l[-n:] + l[:n] if size % 2 == 0 else l[-n:] + [l[n]] + l[:n]
    return res

print(rotation([4,5,7,8,9,10])) #=> [8, 9, 10, 4, 5, 7]
print(rotation([4,5,7,8,9,10,12])) #=> [9, 10, 12, 8, 4, 5, 7]
于 2018-11-10T14:11:16.930 回答