Member-only story
Interview Question: Count the number of zeros and ones in a string
If a person is going to attend an interview to get a position as a Python programmer, he will need to be familiar with many basic components in the language.
One question that he may be asked is to count the number of zeros and ones in a string. I have prepared two answers to this question, using either lists or counters.
The first solution is to use lists to keep a record of the ones and zeros:-
- Define the string, s.
- Define an empty array, zero, to keep track of all of the zeros in the string.
- Define an empty array, one, to keep track of all of the ones in the string.
- Set up a for loop that will iterate through the length of the string. If the element in the string is zero then append ‘0’ to the array, zero. If the element in the string is one then append 1 to the array, one. If the element in the string is neither one or zero then continue with the next iteration.
- Once the for loop has completed its iterations, print the length of the array, zero, and the array, one.