Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python (2.7.3) how do I write a function that answers if any characters in str(x) are in str(y) (or str(y) are in str(x))?

def char_check(x,y):

    if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):

        return True

    else:

        return False

print "You will enter two words that you think use some of the same letters."

x = raw_input('Enter one of the words: ')

y = raw_input('Enter the other word: ')

print char_check(x,y)

What I am trying to do is enter two strings, such as "terrible" for str(x) and "bile" for str(y) and return "True" because the characters 'b', 'i', 'l', and 'e' are shared by both strings.

I'm new and trying to learn but I couldn't seem to figure this one out on my own. Thanks y'all.

like image 736
kalynbaur Avatar asked Jan 23 '26 11:01

kalynbaur


1 Answers

Sets are almost certainly the way to go.

>>> set1 = set("terrible")
>>> set2 = set("bile")
>>> set1.issubset(set2)
False
>>> set2.issubset(set1)  # "bile" is a subset of "terrible"
True
>>> bool(set1 & set2)  # at least 1 character in set1 is also in set2
True
like image 59
mgilson Avatar answered Jan 24 '26 23:01

mgilson