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.
If I get the point, this could work.
But I don't see the need to pass the second parameter to the method (unless you are looking for something different).
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]
def rotation(l,n):
if len(l) % 2 == 0:
return l[n:] + l[:n]
else:
return l[-n:] + [l[n]] + l[:n]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.