Search code examples
pythonstringcomparison

Comparing characters in Two Strings


I receive two string inputs from user: acela laced.

I use the string and split it to form a list. s = ['acela', 'laced'] and I call s1=s[0] and s2=s[1].

Now I have to compare s1 and s2 such that: If len(s1)==len(s2) and all individual characters of S2 are in S1 (sequential matching not relevant) then print 'Yes' else print No.

I have tried some coding for it, but I my outputs are either incorrect or they go yes yes yes yes no for every letter that is compared. I want just one output in the end per comparison - either yes or no for s1 and s2.

def compare(s1,s2):  
    if len(s1) == len(s2):
        for i in s2:
            if i in s1:
                print('yes')
            else:
                print('no')

(The code above is my idea, not an exact copy paste.) Basically, what I want is if the lengths and individual letters of the strings match, then print Yes else No. For ex: in my given example above, the answer should be No, as 'd' of laced doesn't exist in S1. (S1 is master list and S2 should be compared with S1.)

Example: Inputs:

axle lxae
aaabab bacdba
ababa bbaaa

Outputs:

Yes
No
Yes

How do I go about this?


Solution

  • My python skills are the strongest, but this should work. I will not say this is the best implementation, but it will work.

       def compare(s1,s2):  
        if len(s1) == len(s2):
            for i in s2:
                if i in s1:
                    continue
                else:
                    print('no')
                    return;
    
            print('yes')
            return;
        print('no')
    

    I removed an else, this is my personal preference.

    def compare(s1,s2):  
        if len(s1) != len(s2):
            print('no')
            return
    
        for i in s2:
            if i not in s1:
                print('no')
                return
    
        print('yes')