Reputation: 560
I have written a code that takes place the zeros at the top of list and 1's at the end of it , but it increases the space and time complexity . How can I reduce the complexity of code.
Code:
array = [0, 1, 0, 1, 1, 0]
new_list = []
new_list1 = []
for i in array:
if i == 0:
new_list.append(i)
else:
new_list1.append(i)
print(new_list + new_list1)
Upvotes: 1
Views: 65
Reputation: 4975
with sum (in case you are allowed to use sum
, not clear from the question )
array = [0, 1, 0, 1, 1, 0]
n_ones = sum(array)
new_array = [0 for _ in range(len(array) - n_ones)] + [1 for _ in range(n_ones)]
Remark on booleans
In python booleans are considered numeric types so you can do arithmetic as well. Working only with 0 and 1 as integers, so more structured data than boolean True
and False
, could give raise to performance "lack".
Notice also that python considers both boolean states as literals!
boolean approach
array = [0, 1, 0, 1, 1, 0]
n_ones = len([True for _ in array if bool(_)])
new_array = [0 for _ in range(len(array) - n_ones)] + [1 for _ in range(n_ones)]
Upvotes: -1
Reputation: 416
An other way without count and keeping the loops could be that:
array = [0, 1, 0, 1, 1, 0]
new_list = []
for val in array:
if val == 1:
new_list.append(1)
else:
new_list.insert(0, 0)
>> [0, 0, 0, 1, 1, 1]
Upvotes: 0
Reputation: 195428
Slightly modifying your code:
array = [0, 1, 0, 1, 1, 0]
new_list = []
for i in array:
if i == 0:
new_list.append(i)
new_list.extend(1 for _ in range(len(array) - len(new_list)))
print(new_list)
Prints:
[0, 0, 0, 1, 1, 1]
Upvotes: 0
Reputation: 331
If the output needs to be
[0, 0, 0, 1, 1, 1]
you can do the following:
In [17]:
array = [0, 1, 0, 1, 1, 0]
print([0] * array.count(0) + [1] * array.count(1))
Out[17]: [0, 0, 0, 1, 1, 1]
Upvotes: 2