0

I'm trying to write a function that takes a string and checks to see if there are multiple matches from a separate list in it.

Let's say the list is:

fruits = ['Apple', 'Orange', 'Pineapple', 'Durian', 'Lychee']

And the input string is:

"Apple, Orange"

I'd like it to return a True if two or more items from the list are in the input string.

So:

"Durian, Apple, Orange"

would return True. But:

"Apple"

would return False.

I'm just not quite sure how to iterate over the input string. Would appreciate any help!

John Smith
  • 125
  • 1
  • 8
  • 1
    You can call `.split()` on the input string which will give you a list, then follow the steps [here](http://stackoverflow.com/questions/6159313/can-python-test-the-membership-of-multiple-values-in-a-list). – tyteen4a03 Feb 04 '17 at 02:27
  • `sum(1 for x in input_str.split(', ') if x in fruits) >= 2` – Steven Summers Feb 04 '17 at 02:29
  • `len([a for a in your_str.split(', ') if a in fruits])>1` – Mohammad Yusuf Feb 04 '17 at 02:30
  • Brilliant, thanks! I think I know what to do from here. :) – John Smith Feb 04 '17 at 02:48
  • @tyteen4a03 The function on the linked page returns a false if another fruit that's not in the list is added.So, "Grape, Apple, Orange" returns **False.** How would I get it to return **True** as long as two or more are in the original list? – John Smith Feb 04 '17 at 03:05

1 Answers1

1

If you also want to count repetition (i.e., input string 'apple, apple' would also return True), then the following line should do the job.

sum(f in fruits for f in fruit_str.split(', ')) > 1

If you want to check for uniqueness as well, you can preprocess the input string and remove the duplicates before checking for their presence in the fruit list.

sum(f in fruits for f in set(fruit_str.split(', '))) > 1
Fallen
  • 4,435
  • 2
  • 26
  • 46
  • You can also use the intersection operator `&` , which should be more efficient than a loop. `len(set(fruit_str.split(', ')) & set(fruits)) >= 2` – Håken Lid Feb 04 '17 at 03:12
  • @HåkenLid: That's another way to do it but I've doubt that & or intersection is faster than a loop. Doesn't that need a loop anyway? – Fallen Feb 04 '17 at 03:16
  • In the underlying C implementation there's presumably a loop. But the lookup is constant time, since set is implemented as a hash map. – Håken Lid Feb 04 '17 at 03:36