Last active
March 20, 2019 05:37
-
-
Save iamaziz/a4254a4e3e5205db9f5ef93e091fa319 to your computer and use it in GitHub Desktop.
An implementation of string equality comparison case-insensitive e.g. s1.upper() == s2.upper()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def case_insensitive(s1, s2): | |
""" | |
returns True if both s1 and s2 | |
contain the same letters and letters in the same order, | |
regardless of letters case. | |
In other words, | |
this is an implementation for either | |
s1.upper() == s2.upper() | |
or s1.lower() == s2.lower() | |
""" | |
def alpha_range(ord_val): | |
upper_vals = range(65, 91) # unicode code values of A - Z | |
lower_vals = range(97, 123) # unicode code values of a - z | |
valid_values = tuple(list(upper_vals) + list(lower_vals)) | |
return ord_val in valid_values | |
if len(s1) != len(s2): | |
return False | |
for c1, c2 in zip(s1, s2): | |
# diff in Unicode code value | |
diff = abs(ord(c1) - ord(c2)) | |
not_upper_lower_distance = diff != 32 | |
not_same_letter_distance = diff != 0 | |
not_same_distance = not_upper_lower_distance and not_same_letter_distance | |
if not_same_distance: | |
return False | |
# make sure that not any difference of 32 can pass | |
# e.g. diff between ord('?') and ord('_') | |
within_alphabet_range = alpha_range(ord(c1)) and alpha_range(ord(c2)) | |
if not within_alphabet_range: | |
return False | |
return True | |
print(case_insensitive('abc', 'AbC')) # True | |
print(case_insensitive('bbC', 'Bbc')) # True | |
print(case_insensitive('ac c', 'aC')) # False | |
print(case_insensitive('aca', 'acå')) # False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment