• + 0 comments

    Simple pypy3 solution using itertools lib

    Row / Column tweak logic:

    Comparison: L ^ 0.5 <= row <= col <= L ^ 0.5

    • In the case where L is not a perfect square num, you would increase col by 1
    • After incresement, if row x col is smaller than L, just increase row by 1 as well.
    • Then you should get row, col pair based on challenge's rules.

    zip_longest():

    from itertools import zip_longest
    
    # Use it to combine 2 iterables:
    
    wordlist = ['apple', 'grape', 'rank']
    print(*zip_longest(*wordlist, fillvalue = '_'))
    # Output: ('a', 'g', 'r') ('p', 'r', 'a') ('p', 'a', 'n') ('l', 'p', 'k') ('e', 'e', '_') 
    
    import math
    from itertools import zip_longest
    
    def encryption(s):
        # Write your code here
        # Remove spaces and calculate the length
        new_s = "".join(s.split(" "))
        l = len(new_s)
        row = col = int(math.sqrt(l))
        
        if not math.sqrt(l).is_integer():            
            col = row + 1
            if row * col < l:
                row = col
        
        grid = [new_s[i: i + col] for i in range(0, len(new_s), col)]
        new_grid = zip_longest(*grid, fillvalue="")
        encrypted = " ".join("".join(items) for items in new_grid)
    
        return encrypted