정수 n이 주어졌을 때 알파벳 26자 중에서 동일한 개수의 알파벳을 이용하여 임의의 문자열을 반환하라.
만약 n이 3이면 'abc' 'bcd' 와 같은 결과가 나오면 되고
n이 30인 경우 2개씩 사용하여 'aabbcc ....' 또는 'cccdddeee ...' 와 같은 임의의 문자열이 반환되면 된다.
n이 31일 경우에는 'bbbbbbb .... '와 같이 될 것이다.
import random
def smallest_factor(n):
if n < 2:
return 1 # No prime factors for n < 2
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return i # i is the smallest factor of n
return n # If no factor is found, n is prime
def generate_string(n):
alphabet = [chr(i+97) for i in range(26)]
if n < 27:
return random.sample(alphabet,n)
else:
equalNum = smallest_factor(n)
string = random.sample(alphabet, int(n/equalNum))
newsample = string * equalNum
random.shuffle(newsample)
newsample.sort()
return newsample
# Test the function
print(''.join(generate_string(29)))