MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / check_anagrams

Function check_anagrams

strings/check_anagrams.py:8–41  ·  view source on GitHub ↗

Two strings are anagrams if they are made up of the same letters but are arranged differently (ignoring the case). >>> check_anagrams('Silent', 'Listen') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('This is a str

(first_str: str, second_str: str)

Source from the content-addressed store, hash-verified

6
7
8def check_anagrams(first_str: str, second_str: str) -> bool:
9 """
10 Two strings are anagrams if they are made up of the same letters but are
11 arranged differently (ignoring the case).
12 >>> check_anagrams('Silent', 'Listen')
13 True
14 >>> check_anagrams('This is a string', 'Is this a string')
15 True
16 >>> check_anagrams('This is a string', 'Is this a string')
17 True
18 >>> check_anagrams('There', 'Their')
19 False
20 """
21 first_str = first_str.lower().strip()
22 second_str = second_str.lower().strip()
23
24 # Remove whitespace
25 first_str = first_str.replace(" ", "")
26 second_str = second_str.replace(" ", "")
27
28 # Strings of different lengths are not anagrams
29 if len(first_str) != len(second_str):
30 return False
31
32 # Default values for count should be 0
33 count: defaultdict[str, int] = defaultdict(int)
34
35 # For each character in input strings,
36 # increment count in the corresponding
37 for i in range(len(first_str)):
38 count[first_str[i]] += 1
39 count[second_str[i]] -= 1
40
41 return all(_count == 0 for _count in count.values())
42
43
44if __name__ == "__main__":

Callers 1

check_anagrams.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected