Tuesday, June 30, 2020

Merge the Tools!-HackerRank Solution

Merge the Tools!-HackerRank Solution

Consider the following:

  • A string, , of length  where .
  • An integer, , where  is a factor of .

We can split  into  subsegments where each subsegment, , consists of a contiguous block of  characters in . Then, use each  to create string  such that:

  • 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  in  occurs at a previous index  in , then do not include the character in string .

Given  and , print  lines where each line  denotes string .

Input Format

The first line contains a single string denoting .
The second line contains an integer, , denoting the length of each subsegment.

Constraints

  • , where  is the length of 
  • It is guaranteed that  is a multiple of .

Output Format

Print  lines where each line  contains string .

Sample Input

AABCAAADA
3   

Sample Output

AB
CA
AD

Explanation

String  is split into  equal parts of length . We convert each  to  by removing any subsequent occurrences non-distinct characters in :

We then print each  on a new line.


Merge the Tools Solution-

def merge_the_tools(string, k): 
    for part in zip(*[iter(string)] *k):
        print(part)
        d = dict()
        print(''.join([ d.setdefault(c, c) for c in part if c not in d ]))
   
if __name__ == '__main__':
    string, k = input(), int(input())
    merge_the_tools(string, k)

Well, this solution seems a little difficult it's not actually though. We have used two simple concepts like zip and setdefault. Zip function takes iterables (can be zero or more), aggregates them in a tuple, and return it. Iter iterates inside the string and returns a tuple of three characters as 'k' value is 3 in the sample input. Hence our part will appear like ('A', 'A', 'B'), and so on. setdefault function takes two inputs as (key, defaultvalue).  If the key is not present in dict it returns the default value which is also same as the key in our case, and later its joined using join method.

0 comments:

Post a Comment

Feel free to share your thoughts and suggestion...