Jack
Jack

Reputation: 115

Determining a Common Substring

Given two strings, determine if they share a common substring. A substring may be as small as one character.

Example:

s1 = "and"
s2 = "art"

They share the character "a". Then return a string: either YES or NO

def twoStrings(s1, s2):
    UniqueChar_S1 = (char for char in s1)
    UniqueChar_S2 = (char for char in s2)

    SubStringExists = False
    for i in set(UniqueChar_S1):
        if i in set(UniqueChar_S2):
            SubStringExists = True
            break
        else:
            continue

    return "YES"*int(SubStringExists) + "NO"*(1 - int(SubStringExists))

def main():
    q = int(input())

    for q_itr in range(q):
        s1 = input()

        s2 = input()

        result = twoStrings(s1, s2)

if __name__ == "__main__":
    main()

Example input:

4
wouldyoulikefries
abcabcabcabcabcabc
hackerrankcommunity
cdecdecdecde
jackandjill
wentupthehill
writetoyourparents
fghmqzldbc

Expected Output:

NO
YES
YES
NO

Example Input that Fails:

2
aardvark
apple
beetroot
sandals

Im not getting thrown an error and so im unsure what is the issue with my code, I cannot see any issues with the code and so Im wondering if anyone can point anything out for me. Also any improvements will be appreciated.

Upvotes: 0

Views: 111

Answers (4)

Alain T.
Alain T.

Reputation: 42133

In its simplest form: "NO" if set(s1).isdisjoint(s2) else "YES"

Upvotes: 1

Avo Asatryan
Avo Asatryan

Reputation: 414

UniqueChar_S1 = (char for char in s1) is a generator.

for i in set(UniqueChar_S1):
    if i in set(UniqueChar_S2):

So after checking the 'if' condition once the value of set(UniqueChar_S2) would be empty for second iteration.

So i suggest you the following code:

def twoStrings(s1, s2):
    SubStringExists = set(s1)&set(s2)
    return "YES" if SubStringExists else "NO"

Upvotes: 0

Remy J
Remy J

Reputation: 729

def two_strings(s1, s2):
    return "YES" if set(s1).intersection(set(s2)) else "NO"


def main():
    q = int(input("Numbers: "))
    for q_itr in range(q):
        s1 = input("String 1: ")
        s2 = input("String 2: ")

        result = two_strings(s1, s2)
        print(result)


if __name__ == "__main__":
    main()

Upvotes: 0

Divyessh
Divyessh

Reputation: 2721

Well you need to modify your code as following as it is more optimised:


def twoStrings(s1, s2):
    UniqueChar_S1 = set(s1)
    UniqueChar_S2 = set(s2)

    for i in UniqueChar_S1:
        if i in UniqueChar_S2:
            return "YES"
 
    return "NO"

Upvotes: 0

Related Questions