Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to write method/function named movel( s, k) that moves all the elements of the 's' array to the left by 'k' positions (not rotate)?

this is my code below and please help me find out the the expected output[ 4,5,6,0,0,0]

def movel(s, k):
  n=len(s)
  j=0
  n_arr=s[:k]
  return (s[k::]+n_arr[::])
  for j in range(0, n):
    print(s[j], end=' ')


s=[1,2,3,4,5,6]
k=3 
movel(s,k)

*Output : [4,5,6,1,2,3] *

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could do use index slicing

def movel(s, k):
    if k > len(s):
        return [0] * len(s) # you decide how to handle this case
    return s[k:] + [0] * (len(s) - k)

Think of it this way, we change the head of the list and fill the rest with zeros.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading