-6

I have been given this question and am stuck on it.

W = ['cat', 'audiotape', 'businesswoman', 'dog']

Write a list comprehension to efficiently extract from a random list of words w, the longest word lw, that contains at least one instance of each vowel. Include a helper function in your answer if required. (For w given above, lw is "businesswoman".)

What I have got so far is

lw = max[len(w) for n in w]

I know it isn't a lot I don't understand how to find the word containing all the vowels and how to print the longest word. I am new to Python.

Cccc33
  • 1
  • 2
  • 2
    what did you try so far ? – Trolldejo May 10 '17 at 15:41
  • 2
    Please see [Asking about homework](https://meta.stackoverflow.com/a/334823/7662085). If you want us to help you at least have to try and do it yourself and show us what you tried. – stelioslogothetis May 10 '17 at 15:42
  • You should show what you have tried and what you think of doing instead of just asking us to solve it for you. (This is why you're being downvoted, by the way) – Pedro Castilho May 10 '17 at 15:42

2 Answers2

1

all() Returns true if all of the items in list are True

>>> print(all([True, True, True, True]))
True
>>> print(all([False, True, True, False]))
False

In above problem we need to check if all vowels are present in a string (ex: businesswoman) using all as follows:

>>> all(t in "businesswoman" for t in 'aeiouu')
True

Similarly we need to do it for all items in the W as follows:

>>> W = ['cat', 'audiotape', 'businesswoman', 'dog'] 
>>> [x for x in W if all(t in x for t in 'aeiouu')]
['audiotape', 'businesswoman']
>>> sorted([x for x in W if all(t in x for t in 'aeiouu')], key=len)[-1]
'businesswoman'

Read more about all()

Community
  • 1
  • 1
JkShaw
  • 1,927
  • 2
  • 13
  • 14
0

For the sport:

W = ['cat', 'audiotape', 'businesswoman', 'dog']
lw = sorted([x for x in  W  if all(y in x for y in 'aeiou')], key=lambda x:len(x))[-1] 
Trolldejo
  • 466
  • 1
  • 7
  • 20
  • I find the `-len(x)` more confusing than simply inverting the list and your if is wrong. Just use `all()`. Remove the `[0]` and you'll see it. – Ma0 May 10 '17 at 16:01
  • I'd rather pick the last element out than reverting the whole list.. you're right, I made a mistake, correcting – Trolldejo May 10 '17 at 16:03
  • I am afraid you did not understand me fully. if you use `len(x)` instead of `-len(x)` you still do the same amount of work. And then instead of getting the `[0]` you will get the `[-1]`. – Ma0 May 10 '17 at 16:04
  • yeah, that's is exactly what I said. You were talking about "inverting the list" – Trolldejo May 10 '17 at 16:05