- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathcheck_anagrams.py
52 lines (40 loc) · 1.54 KB
/
check_anagrams.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
wiki: https://en.wikipedia.org/wiki/Anagram
"""
fromcollectionsimportdefaultdict
defcheck_anagrams(first_str: str, second_str: str) ->bool:
"""
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 string', 'Is this a string')
True
>>> check_anagrams('There', 'Their')
False
"""
first_str=first_str.lower().strip()
second_str=second_str.lower().strip()
# Remove whitespace
first_str=first_str.replace(" ", "")
second_str=second_str.replace(" ", "")
# Strings of different lengths are not anagrams
iflen(first_str) !=len(second_str):
returnFalse
# Default values for count should be 0
count: defaultdict[str, int] =defaultdict(int)
# For each character in input strings,
# increment count in the corresponding
foriinrange(len(first_str)):
count[first_str[i]] +=1
count[second_str[i]] -=1
returnall(_count==0for_countincount.values())
if__name__=="__main__":
fromdoctestimporttestmod
testmod()
input_a=input("Enter the first string ").strip()
input_b=input("Enter the second string ").strip()
status=check_anagrams(input_a, input_b)
print(f"{input_a} and {input_b} are {''ifstatuselse'not '}anagrams.")