0

I am recently solving a coding problem. It ask me to move all 0s in one array to the end of the array. Like [0, 1, 1, 0, 0, 1]->[1, 1, 1, 0, 0, 0].

The reality is there could be any type of data in the original array, for example, [0, "A", 1 , None, False, True, 0, 0, 20, 1, 0.0]

what I am doing is looping the array, compare if it is 0, if it is, put it into another array. If it is not, increase the counter, at the end put the same amount of 0s as the counter. However, it treats the Boolean Value False as 0, so I can't do this, I am just curious if there is a way that can separate False from 0, and put into another array as False in Python. Thanks.

5
  • Is this an assignment where it's asking for algorithm design or can you just use sorted in rev order? Commented Jul 2, 2017 at 14:51
  • 1
    False is implemented as 0 but has an other type. So, check value and type! Commented Jul 2, 2017 at 14:55
  • @KlausD. Try this: isinstance(True, int) Commented Jul 2, 2017 at 14:59
  • @cᴏʟᴅsᴘᴇᴇᴅ That's because isinstance() check for supertypes as well. Use type(False) == int instead. Commented Jul 2, 2017 at 15:02
  • @KlausD. I concur, what I meant to say was that simply checking type isn't enough... Commented Jul 2, 2017 at 15:03

3 Answers 3

1

Use the test in your algorithm, to check if the value is the integer 0 and not the bool.

test = lambda x: True if x is 0 else False

list_ = [0, "A", 1 , None, False, True, 0, 0, 20, 1, 0.0]

print(sorted(list_, key=test)) #['A', 1, None, False, True, 20, 1, 0.0, 0, 0, 0]
Sign up to request clarification or add additional context in comments.

3 Comments

In the problem, 0.0 is treat as 0, if it is detected, it will be put to the end of the array with a 0, not 0.0.
0.0 is 0 >>>False
I tried your way, 0.0 is put back as 0.0, in the problem if a 0.0 need to be 0 and put back. For example, [1, 0, 0, 2, 0.0, 1] should be [1,2,1,0,0,0]
0

You can make use of is which does an identity comparison. Observe the following example:

>>> n = 0
>>> n is 0
True
>>> n is False
False
>>> False is n
False

Comments

0

I run into some issues with 0.0 so, i made some changes

array = [0, "A", 1 , None, False, True, 0, 0, 20, 1, 0.0]
filt = lambda x: True if x==0 and type(x) is not bool else False
print(sorted(array,key=filt))

The x==0 will allow you to filter the float, and type(x) in not bool will help you with the boolean False

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.