Odd one Out
Task
You are given a list of words (alphabetic characters only) of same size.
Write a script to remove all words not sorted alphabetically and print the number of words in the list that are not alphabetically sorted.
My solution
I would have thought that by definition the first world would have being defined as sorted alphabetically. However, the second example shows that this is not the case. So I have a bit of code that will return the length of the list if the first word is not the first alphabetically.
I then set the current_word
variable to the first word, and the unsorted_words
variable to 0. I loop through the remaining words, and update the current_word
variable if it is greater than the current current_word
or add one to unsorted_words
if it isn't.
Examples
$ ./ch-1.py abc xyz tsu
1
$ ./ch-1.py rat cab dad
3
$ ./ch-1.py x y z
0
Task 2: Number Placement
Task
You are given a list of numbers having just 0 and 1. You are also given placement count (>=1).
Write a script to find out if it is possible to replace 0 with 1 in the given list. The only condition is that you can only replace when there is no 1 on either side. Print 1 if it is possible otherwise 0.
My solution
Sometimes it is easier to brute force the solution, and that is the approach I took with this one. I start by taken the last value from the input, and assign this to the variable to_place
.
I then loop through the array from the second position to the second last one. If the preceding value, the current value and the next value are all zero, I change the current value to one, and remove from from the to_place
variable. If this is zero (i.e. we have placed all numbers), I print `1 and exit.
If I have ended the loop and to_place
is not zero, I cannot place all the numbers, and print 0
to represent this.
Examples
`bash
$ ./ch-2.py 1 0 0 0 1 1
1
$ ./ch-2.py 1 0 0 0 1 2
0
$ ./ch-2.py 1 0 0 0 0 0 0 0 1 3
1
`
Top comments (0)