pennant93
pennant93

Reputation: 11

Word of a list with most repeated vowels? More pythonic solution?

Here is my current solution which seems to be operating correctly aside from I am not sure what the code does if two or more words are tied, I need to work on that as well.

def most_repeating_vowel(word):

    vowels = {"a":0,"e":0,"i":0,"o":0,"u":0}
    for i in word:
        if i in vowels:
            vowels[i]+=1
    return max(vowels.values())
       
def most_repeating_word(seq):
    return max(seq, key=most_repeating_vowel)

mylist = ["giraffe","elephant","ox","yyyyyyy","iiiii"]

most_repeating_word(mylist)

Is there a more pythonic way I can handle this?

Upvotes: 1

Views: 184

Answers (2)

Kelly Bundy
Kelly Bundy

Reputation: 27629

I like using str.count:

max(mylist, key=lambda w: max(map(w.count, 'aeiou')))

Benchmark with your example data:

Round 1  Round 2  Round 3 
16.1 us  16.0 us  15.5 us  Stef
 5.2 us   5.0 us   5.1 us  KellyBundy

And with longer words (each word multiplied by 1000):

Round 1  Round 2  Round 3 
1466 us  1476 us  1480 us  Stef
  71 us    71 us    71 us  KellyBundy

Benchmark code (Try it online!)

from timeit import timeit
import collections

def Stef(mylist):
  def count_most_repeated_vowel(w):
    c = collections.Counter(w)
    return max(c[v] for v in 'aeiou')
  return max(mylist, key=count_most_repeated_vowel)

def KellyBundy(mylist):
  return max(mylist, key=lambda w: max(map(w.count, 'aeiou')))

funcs = Stef, KellyBundy

def benchmark(mylist, number, label, format):
  tss = [[] for _ in funcs]
  for r in range(1, 4):
    print(*(label % i for i in range(1, r+1)))
    for func, ts in zip(funcs, tss):
      t = timeit(lambda: func(mylist), number=number) / number
      ts.append(t)
      print(*(map(format, ts)), func.__name__)
    print()

mylist = ["giraffe","elephant","ox","yyyyyyy","iiiii"]
benchmark(mylist, 50000, 'Round %d ', lambda t: '%4.1f us ' % (t * 1e6))
benchmark([w * 1000 for w in mylist], 500, 'Round %d ', lambda t: '%4d us ' % (t * 1e6))

Upvotes: 1

Stef
Stef

Reputation: 15525

A solution using collections.Counter, which is a subclass of dict used to count things:

import collections

mylist = ["giraffe","elephant","ox","yyyyyyy","iiiii"]

def count_most_repeated_vowel(w):
  c = collections.Counter(w)
  return max(c[v] for v in 'aeiou')

print(max(mylist, key=count_most_repeated_vowel))
# 'iiiii'

Upvotes: 0

Related Questions