Maximilian Freitag
Maximilian Freitag

Reputation: 1049

Only print out strings from a list that contain certain characters

Let's assume following list

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']

I want to write a function that takes two parameters as the input where m are the characters as a string that I want to find (e.g. 'ff') and n is the number of strings as an integer that I want to output.

So def contains_strings('ff', 2):

should output:

['coffee', 'insufficient']

Both words contain 'ff' and the output is 2 in total. The second parameter can be random. So I don't care if the function outputs. ['coffee', 'insufficient'] or ['differential', 'insufficient']

I was only able to write a function that is able to output words that start with certain characters:

import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']

def starting_letters(m: str, n: int):
    a = list(filter(lambda x: x.lower().startswith(m), my_list)) 
    print(_random.choices(a, k=n)) 
  

starting_letters('c', 2)

Output:

['coffee', 'cat']

Upvotes: 2

Views: 2333

Answers (4)

Veeresh Hiremath
Veeresh Hiremath

Reputation: 1

import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']

def starting_letters(m: str, n: int): a = list(filter(lambda x: m in x, my_list)) print(_random.choices(a, k=n))

starting_letters('ff',2)

Upvotes: 0

AloneTogether
AloneTogether

Reputation: 26708

Maybe like this:

import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']

def contains_strings(m: str, n: int):
      a = list(filter(lambda x: m in x.lower(), my_list)) 
      return _random.sample(a, k=n)

print(contains_strings('ff', 2))

#['coffee', 'insufficient']

Upvotes: 1

Red
Red

Reputation: 27557

Here is how I would do it:

import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']

def starting_letters(m: str, n: int):
    a = list(filter(lambda x: m in x.lower(), my_list)) 
    print(_random.sample(a, n))

Notice how I replaced the random.choices() method with the random.sample() method. The reason is because with the random.choices() method, you may get the element from the same index multiple times in the output, whereas the random.sample() method ensures that every returned element is from a unique index of the list.

Upvotes: 1

John Byro
John Byro

Reputation: 734

You can use regex here to match patterns in strings

import re
import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']


def contains_pattern(pattern: str, n: int):
    regex = re.compile(f'{pattern}')
    a = [ans for ans in my_list if regex.search(ans)]
    return _random.choices(a, k=n)

print(contains_pattern("ff",2))

# ['insufficient', 'coffee']

Upvotes: 0

Related Questions