How to check if a String contains at least 2 elements from a list

Question:

For e.g the variable is a boolean : char_check = False

For e.g the string is "python i$ cool_123"(the string can vary depending on the input)

And the list is "[$, &, #, @,1,2,3]

If the string contains at least two elements from the list then char_check = True. But i only know how to check if a string contains one item from a list using the any() function, not 2 or multiple items in a list.

Any help or solutions will Be appreciated thank you

I tried using the any(function) but it only checks if a string contains at least one item not 2 or more

Tl:dr
A string inputted should have at least two elements from a list

Asked By: Im Stupid

||

Answers:

This is a possible solution:

def check_chars(s, lst):
    return len(set(s) & set(lst)) >= 2

Examples:

>>> check_chars("abc", ["a", "d"])
False
>>> check_chars("abc", ["a", "c"])
True

Another option:

def check_chars(s, lst):
    it = iter(s)
    return any(c in lst for c in it) and any(c in lst for c in it)
Answered By: Riccardo Bucco
def func(string,lst):
    count=0
    for i in string:
        if i in lst:
            count+=1
    if count>=2:
        return True
    else:
        return False
lst=['$', '&', '#', '@', '1', '2', '3']
string=input("Enter the sting:")
print(func(string,lst))

Hope it helped..

Answered By: Randomuser141144
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.