Created
October 28, 2020 11:59
-
-
Save wildonion/488fce183189a744d8bc5bc66544ff0d to your computer and use it in GitHub Desktop.
check string is transformable or not
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
| # check string is transformable or not | |
| def detect_digit(s): | |
| for c in range(len(s)): | |
| if s[c] not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: | |
| return False | |
| else: | |
| return True | |
| s = input("first string ::: ") | |
| t = input("second string ::: ") | |
| assert 1 <= len(s) <= 105, "too long" | |
| assert len(s) == len(t), "length must be equal" | |
| assert len(s) != 1 or len(t) != 1, "can't transform" | |
| assert detect_digit(s) or detect_digit(t), "chars must be digit" | |
| def is_transformable(s): | |
| list_string, list_t, sorted_s_lst = list(s), list(t), list(s) | |
| for i in range(2, len(list_string), 2): # start from 2 beacuse of the upper bound of slicing string | |
| cutted_string = sorted_s_lst[:i] # i doesn't count | |
| sorted_cutted_string = [str(n) for n in sorted(list(filter(lambda n: int(n), cutted_string)))] | |
| sorted_s_lst = sorted_cutted_string+sorted_s_lst[i:] | |
| unequal_indices = [sorted_s_lst.index(i) for i, j in zip(sorted_s_lst, list_t) if i!=j] | |
| if sorted_s_lst == list_string: | |
| return False | |
| else: | |
| greater_val = sorted_s_lst[unequal_indices[0]] | |
| smaller_val = sorted_s_lst[unequal_indices[1]] | |
| sorted_s_lst[unequal_indices[1]] = greater_val | |
| sorted_s_lst[unequal_indices[0]] = smaller_val | |
| sorted_s = "".join(sorted_s_lst) | |
| if sorted_s == t: | |
| return True | |
| if is_transformable(s): | |
| print("|>> is transformable <<|") | |
| else: | |
| print("|>> is NOT transformable <<|") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment