Home > Software engineering >  check two strings have the same numbers of characters and the same character occurrences Python
check two strings have the same numbers of characters and the same character occurrences Python

Time:07-30

I have the following strings, and I need to check if both have the same numbers of characters (I do it with len) and the same character occurrences (I do not know how to do it). I can't use collections or sort; it must be a function. I have tried to resolve with set but it doesn't work.

For s1 and s2 I have to obtain True For s3 and s4 I have to obtain False

s1 = "aabbcc", s2 = "abcabc", s3 = "aab", s4 = "abb"

This is my function (doesn't work for s3 and s4) Can anyone help me?


def check(s3,s4):

    if len(s3) == len(s4) and set(s3)== set(s4):
        print (True)
    else:
        print (False)

check(s3,s4)

CodePudding user response:

You could count the occurrence of each character on your own (using a dict comprehension) and compare afterwards:

def check(a,b):
    res = []
    
    for item in (a,b):
        chars = set(item)
        res.append({c: item.count(c) for c in chars})
    return res[0] == res[1]

s1 = "aabbcc"
s2 = "abcabc"
s3 = "aab"
s4 = "abb"

print(check(s1,s2))
print(check(s3,s4))

Out:

True
False

CodePudding user response:

Here is another handy solution without using set

def check(str1, str2):
    total_str1 = 0
    total_str2 = 0
    if len(str1) != len(str2):
        return False
        
    for char in list(str1):
        total_str1  = ord(char)
    for char in list(str2):
        total_str2  = ord(char)
    
    if total_str1 == total_str2:
        return True
    else:
        return False
    
print(check('AABBCC', 'ABCABC'))
print(check('AABBCC', 'AABBCc')) 

returns

True
False

ord('S') => returns the ASCII value of a character

Basically, we add the ASCII value of each character in the string and the total must be the same because each character has a unique ASCII value and if two strings are the same their total will also always will be the same :-)

Here is a link for ASCII table : https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

  • Related