1

I want to split the array at a point s and add it to the end of the array. But my output is my input list.

def split_and_add(arr, s):
    n = len(arr)
    if n >= s or s <=0:
        return arr
    else:
        end = []
        for i in range(0,s):
            end = end + [arr[i]]
        start = []
        for i in range(s,n):
            start = start + [arr[i]]
        return start + end


print(split_and_add([1,2,3,4,5,6],3))



The output is still [1,2,3,4,5,6]. Could somebody help?

2
  • 1
    what is your expected output? Commented Jun 5, 2022 at 19:55
  • Expected output: [4,5,6,1,2,3] for d = 3 Commented Jun 5, 2022 at 19:56

2 Answers 2

1

Only issue in your code is in line

if n >= s or s <=0:

Here, you are checking if length of array n is greater than the break point s and if yes, you are returning the originl array. But what you need to do is check if s is greater than or equal to length of array and if yes, return original array. So, all you need to do is replace n >= s with s >= n. So your condition would be

if s >= n or s <=0:
    return arr

Now, this should work.

Sign up to request clarification or add additional context in comments.

1 Comment

oops :) thanks should have seen something like that.
1

You could do this in a simple way. Just append the left half arr[:s] to the right half arr[s:] like this.

def split_and_add(arr, s):
    n = len(arr)
    if s >= n or s <=0:
        return arr
    return arr[s:] + arr[:s]

For the sample input, this gives:

split_and_add([1,2,3,4,5,6],3)
 # [4, 5, 6, 1, 2, 3] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.