0

I have a sorted list. I want to move the values d steps forwards. And I need O(n) time complexity.

For example if d = 2, the value 1, which was in index = 0, now is in index = 2:

lst = [1,2,3,4,5]
d = 2

Expected output: [4,5,1,2,3]

The code:

def cyclic_lst(lst,d):
    mylist = []
    counter = 0
    while(counter <= d):
         mylist = lst[1:] + lst[0]
         counter += 1
    return mylist

I'm getting this error:

TypeError: can only concatenate list (not "int") to list

I can't use for loop with the while loop because of the complexity demand, how can I do this?

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
Programming Noob
  • 1,232
  • 3
  • 14

4 Answers4

2
def cyclic_lst(lst,d):
    return lst[d:] + lst[:d]

But there is no need for cyclic_lst() at all: lst[idx-d-1] gives the same result, witouth calling any function or editing lists.

print(cyclic_lst(lst,d))
[3, 4, 5, 1, 2]

print(lst[0-d-1])
3
print(lst[1-d-1])
4
print(lst[2-d-1])
5
print(lst[3-d-1])
1
print(lst[4-d-1])
2
Colim
  • 1,283
  • 3
  • 11
1

Here is a way to get the desired result:

lst = [1,2,3,4,5]
d = 2
new_lst = [lst[(i - d) % len(lst)] for i in range(len(lst))]

Output:

[4, 5, 1, 2, 3]
constantstranger
  • 9,176
  • 2
  • 5
  • 19
0

Here's another way to do it, using the stylistic conventions of the original post.

def cyclic_lst(lst,d):
    mylist = []
    counter = 0
    while(counter <= d):
         mylist = lst[1:]
         mylist.append(lst[0])
         counter += 1
         lst = mylist
    return mylist

I modified your original algorithm slightly, and substituted the variable "mylst" back into "lst" in the while loop.

But this is really quite inefficient, and can't possibly be the best way of solving this problem.

I am not sure if I have misinterpreted the question or I am missing something here, but the variable new_lst can simply be obtained by slicing "lst" and joining the strings together. The simpler implementation below is O(n)

lst[d+1:] + lst[0:d+1]
DrCorgi
  • 166
  • 4
0
lst[-d%len(lst):] + lst[:-d%len(lst)]
MoRe
  • 2,296
  • 2
  • 3
  • 23