Programming is very rigid. You can't tell a program to "output the banana count", you have to tell it to print(bananas)
.
But when you do that, you end up with a problem: you don't know how many bananas you have beforehand, so you don't know whether to use a plural.
Sometimes, programmers go the lazy way. Instead of checking, they just print there are X banana(s)
.
But that's ugly, so we need a program to fix this.
The method(s)
To remove the ambiguous plurals in a string, follow the following steps:
Split the string on spaces into a list of words.
For every word that ends with
(s)
, do the following:- If the preceding word is
a
,an
,1
orone
, remove the(s)
at the end of the word. - Otherwise, if the word is the first word in the string or the preceding word is not
a
,an
,1
orone
, replace the(s)
at the end of the word withs
.
- If the preceding word is
Join the list of words back together into a string, preserving the original whitespace.
Example(s)
Let's take a string there's a banana(s) and three apple(s)
.
First, we split the string into a list of words: ["there's", "a", "banana(s)", "and", "three", "apple(s)"]
For the second step, we take the two words ending with (s)
: banana(s)
and apple(s)
.
The word before banana(s)
is a
, so we remove the (s)
, making it banana
.
The word before apple(s)
is three
, so we change the (s)
to s
, thus it becomes apples
.
We now have ["there's", "a", "banana", "and", "three", "apples"]
. Joining the list back together, we get there's a banana and three apples
. This is our end result.
The challenge(s)
Create a program or function that takes an ambiguous string in any reasonable format and returns the un-ambiguated version of that string.
You may assume the string contains no newlines, tabs or carriage returns.
I forgot to specify whether to split on groups of spaces or spaces (i.e. whether okay then
with two spaces should be ["okay", "then"]
or ["okay", "", "then"]
) when posting the challenge, so you may assume either form of splitting.
Test case(s)
Input -> Output
there are two banana(s) and one leprechaun(s) -> there are two bananas and one leprechaun
there's a banana(s) and three apple(s) -> there's a banana and three apples
apple(s) -> apples
one apple(s) -> one apple
1 banana(s) -> 1 banana
banana -> banana
preserve original whitespace(s) -> preserve original whitespaces
11 banana(s) -> 11 bananas
an apple(s) -> an apple
this is a te(s)t -> this is a te(s)t
I am a (s)tranger(s) -> I am a (s)tranger
Scoring
As this is code-golf, the submission with the least bytes wins!
apple(s)
test case yieldapples
instead? The challenge statesOtherwise, if the word is the first word in the string . . . replace the (s) at the end of the word with s.
I note that this case yieldedapples
in sandbox for the first three revisions but changed at the fourth. \$\endgroup\$There's a single banana(s)
->There's a single bananas
. \$\endgroup\$