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

For loop in function to move the item of the list

I want to move the negative numbers to the end of the list until I encounter the positive number.

List:

a=[-1,-2,2,3,4,-5]

The result i want:

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

[-2, 2, 3, 4, -5, -1]
[2, 3, 4, -5, -1, -2]

My function:

def f1(A):
  for i in A:
    if i>=0:
      break
    if 'Z' not in globals() or 'Z' not in locals():
     X=A
     X1=X[0]
     X.remove(X1)
     X.append(X1)
     Z=X 
    else:
      X=Z
      X1=X[0]
      X.remove(X1)
      X.append(X1)
      Z=X
    print(Z)
 
a=[-1,-2,2,3,4,-5]
print (f1 (a))

But the result

[-2, 2, 3, 4, -5, -1]
None

can we solve it with this function?

>Solution :

It’s not a for loop, but:

>>> def shift(lst):
...     while lst[0] < 0:
...         lst = lst[1:] + [lst[0]]
...     return lst
... 
>>> a
[-1, -2, 2, 3, 4, -5]
>>> b = shift(a)
>>> b
[2, 3, 4, -5, -1, -2]
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