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:
[-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]