Consider the following:
nis a length of a string
kis a factor of
We can split
substrings where each subtring,
, consists of a contiguous block of
k characters in
s. Then, use each
to create string
- The characters in are a subsequence of the characters in .
- Any repeat occurrence of a character is removed from the string such that each character in
occurs exactly once. In other words, if the character at some index
jin occurs at a previous index
< jin , then do not include the character in string .
lines where each line
i denotes string
Print each subsequence on a new line. There will be of them. No return value is expected.
- The first line contains a single string,
- The second line contains an integer,
k, the length of each substring.
nis the length of
- It is guaranteed that
nis a multiple of
AB CA AD
equal parts of length
k = 3. Convert each
by removing any subsequent occurrences of non-distinct characters in
Print each on a new line.
Both source codes are implementations of the
merge_the_tools function, which takes a string and a positive integer
k as arguments. The function splits the string into substrings of length
k, removes any repeated characters in each substring, and then prints the resulting substrings.
The first source code uses the
dict.fromkeys method to remove duplicates from each substring. This method creates a new dictionary where each character in the substring is a key, and all the values are set to
None. Then, the
join method is used to convert the dictionary keys back into a string. This approach works because dictionaries can only have unique keys, so any duplicates in the substring are automatically removed.
def merge_the_tools(string, k): l = len(string)//k for i in range(l): print(''.join(dict.fromkeys(string[i*k:(i*k)+k])))
The second source code uses the
OrderedDict.fromkeys method from the
collections module instead. This method works in the same way as
dict.fromkeys, but it preserves the order of the keys in the dictionary. This means that the characters in the resulting substring are in the same order as they appeared in the original string.
from collections import OrderedDict as od def merge_the_tools(string, k): l = len(string)//k for i in range(l): print(''.join(od.fromkeys(string[i*k:(i*k)+k])))
Overall, both implementations achieve the same result of removing duplicates from each substring of length
k. The second implementation using
OrderedDict.fromkeys may be slightly slower due to the extra overhead of creating an ordered dictionary. However, it may be useful in cases where the order of the characters in each substring needs to be preserved.