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)
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
There is another wayto do that
s1 = "aabbcc"
s2 = "abcabc"
s3 = "aab"
s4 = "abb"
def check(s1, s2):
return {c: s1.count(c) for c in set(s1)} == {c: s2.count(c) for c in set(s2)}
print(check(s1, s2))
print(check(s3, s4))
True
False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.