Given an array of strings words, sort the words in ascending order of the difference between the number of vowels and the number of consonants in each word (vowels minus consonants). Return the sorted array.
Function Signature
def sort_words_by_vowel_consonant_difference(words: list[str]) -> list[str]:
Rules
-
Vowels are
a
,
e
,
i
,
o
,
u
, in either case.
-
Any other alphabetic character (
A
to
Z
,
a
to
z
) is a consonant. That includes
y
.
-
Non-alphabetic characters such as digits, punctuation and spaces are ignored. They count as neither vowels nor consonants.
-
When two words have the same difference, keep them in their original relative order (a stable sort).
Constraints
-
1 <= len(words) <= 10^4
-
1 <= len(words[i]) <= 100
-
words[i]
consists of printable ASCII characters.
Examples
Input: words = ["hello", "ai", "sky", "ocean", "rhythm"]
Output: ["rhythm", "sky", "hello", "ocean", "ai"]
The differences are hello 2 - 3 = -1, ai 2 - 0 = 2, sky 0 - 3 = -3, ocean 3 - 2 = 1 and rhythm 0 - 6 = -6. Ordering -6, -3, -1, 1, 2 gives the output.
Input: words = ["apple", "banana", "cherry", "date"]
Output: ["cherry", "apple", "banana", "date"]
cherry has one vowel and five consonants (-4), apple is 2 - 3 = -1, and banana and date are both 0. banana stays ahead of date because it comes first in the input.
Input: words = ["Tree!", "123", "AI", "x"]
Output: ["x", "Tree!", "123", "AI"]
Tree! has two vowels and two consonants (0), 123 has no letters (0), AI is 2 and x is -1. Tree! and 123 tie at 0 and keep their input order.