给定一个列表,将列表右转n个位置。
null
例如:
Input : n = 2 List_1 = [1, 2, 3, 4, 5, 6]Output : List_1 = [5, 6, 1, 2, 3, 4]We get output list after right rotating (clockwise) given list by 2.Input : n = 3 List_1 = [3, 0, 1, 4, 2, 3]Output : List_1 = [4, 2, 3, 3, 0, 1]
方法#1: 逐个遍历第一个列表,然后将元素放在第二个列表中所需的位置。
Python3
# Python program to right rotate a list by n # Returns the rotated list def rightRotate(lists, num): output_list = [] # Will add values from n to the new list for item in range ( len (lists) - num, len (lists)): output_list.append(lists[item]) # Will add the values before # n to the end of new list for item in range ( 0 , len (lists) - num): output_list.append(lists[item]) return output_list # Driver Code rotate_num = 3 list_1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] print (rightRotate(list_1, rotate_num)) |
输出:
[4, 5, 6, 1, 2, 3]
时间复杂度:O(n)
方法2: 另一种解决这个问题的方法是使用 切片技术 .对列表进行切片的一种方法是使用 len() 方法
Python3
# Python program to right rotate # a list by n using list slicing n = 3 list_1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] list_1 = (list_1[ len (list_1) - n: len (list_1)] + list_1[ 0 : len (list_1) - n]) print (list_1) |
输出:
[4, 5, 6, 1, 2, 3]
方法#3: 在上述方法中,取列表_1的最后n个元素,然后取列表_1的剩余元素。另一种方法是不使用len()方法。
python
# Right Rotating a list to n positions n = 8 list_1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] if n> len (list_1): n = int (n % len (list_1)) list_1 = (list_1[ - n:] + list_1[: - n]) print (list_1) |
输出:
[4, 5, 6, 1, 2, 3]
时间复杂度:O(n)
注: ListSy1[:]将返回整个列表,因为切片操作符左边的空白是指列表的开始,即0,右边空白空间是指列表的结束位置。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END