+3 votes
in Programming Languages & Algorithms by

Write a function called most_consonants(words) that takes a list of strings called words and returns the string in the list with the most consonants (i.e., the most letters that are not vowels). You may assume that the strings only contain lowercase letters. For example:

>>> most_consonants(['python', 'is', 'such', 'fun'])
result: 'python'

>>> most_consonants(['oooooooh', 'i', 'see', 'now'])
result: 'now'

3 Answers

+2 votes
by (480 points)
selected by anonymous
 
Best answer
def most_const(list):

    largest_count = 0

    largest_const_word = "";

    vowels = ["a", "e", "i", "o", "u"]

    for word in list:

        count = 0;

        for char in word:

            if char not in vowels:

                count += 1

        

        if count > largest_count:

            largest_count = count

            largest_const_word = word

    print(largest_const_word)

sentence1 = ["python", "is", "such", "fun"]

sentence2 = ["oooooh", "i", "see", "now"]

most_const(sentence1)

most_const(sentence2)
by
With this, I can add my own words to the list?
by (2.9k points)
This was really helpful! I found the number of vowels first, then used  consonant_len = len(word) - num_vowels(word) to get the number of consonants. Cheers!
by
Thats great. Good one there!!
by
yes, you can add your own list of words
+1 vote
by (14.7k points)

def num_vowels(s):
  """ returns the number of vowels in the string s
        input: s is a string of 0 or more lowercase letters
  """
  if s == '':
    return 0
  else:
    num_in_rest = num_vowels(s[1:])
    if s[0] in 'aeiou':
      return 1 + num_in_rest
    else:
      return 0 + num_in_rest

# function to return the word with maximum numbers of consonants
def most_consonants(words):
  num_consonants = []

  # calling function to calculate get the number of consonants in each word
  for word in words:

    # determine the number of consonants
    consonant_len = len(word) - num_vowels(word)

    # add to list
    num_consonants.append(consonant_len)

  # find the index of word with the maximum len of consonants
  max_len = max(num_consonants)
  index = num_consonants.index(max_len)

  # return the word at that index
  return words[index]

+1 vote
by (2.9k points)

Test case: print(most_consonants(['oooooooh', 'i', 'see', 'now']))

Python 3.6.8 (default, Jun 11 2019, 01:21:42) [GCC 6.3.0 2017 0516] on linux now

Hope this helps.

Related questions

Welcome to CPEN Talk
Solution-oriented students of computer engineering on one platform to get you that

ONE SOLUTION

...