[Hackerrank] Encryption

이재윤·2025년 2월 11일
0

https://www.hackerrank.com/challenges/encryption/problem

1) 코드

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'encryption' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#




def encryption(s):

    answer = ""
    length = len(s)
    n = 1
    row = -1
    col = -1

    while True:
        if n*n <= length and length <= (n+1)*(n+1):
            row = n
            col = n+1
            break
        else:
            n += 1

    if row*col < length:
        row += 1

    arr = [['0']*col for _ in range(row)]
    pos = 0
    for i in range(row):
        for j in range(col):
            if pos <= length-1:
                arr[i][j] = s[pos]
                pos += 1

    for j in range(col):
        tmp = ""
        for i in range(row):
            if arr[i][j] != '0':
                tmp += arr[i][j]
        if j != col-1:
            answer += tmp
            answer += " "
        else:
            answer += tmp

    return answer 

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = encryption(s)

    fptr.write(result + '\n')

    fptr.close()

2) 해설

0개의 댓글