반응형
Notice
Recent Posts
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

500error

[Cos Pro 1급, Python] 4차 8번 : n번째로 작은 수 구하기 본문

알고리즘/파이썬

[Cos Pro 1급, Python] 4차 8번 : n번째로 작은 수 구하기

Internal Server Error 2024. 2. 29. 18:48
반응형

문제

1 이상 9 이하 숫자가 적힌 카드를 이어 붙여 숫자를 만들었습니다. 이때, 숫자 카드를 조합해 만든 수 중에서 n이 몇 번째로 작은 수인지 구하려 합니다.
예를 들어, 숫자 카드 1, 2, 1, 3로 만들 수 있는 수를 작은 순으로 나열하면 [1123, 1132, 1213, 1231, 1312, ... , 3121, 3211]입니다. n이 1312라면, 숫자 카드를 조합해 만든 수 중 n은 n은 5번째로 작은 수입니다.
숫자 카드를 담은 배열 card, card의 길이 card_len, 수 n이 매개변수로 주어질 때 숫자 카드를 조합해 만든 수 중에서 n이 몇 번째로 작은 수인지 return 하도록 solution 함수를 완성해주세요.

 

 

 

 

 

 

 

 

 

 

 

코드

import itertools
def solution(card, n):
	answer = 0
	answer = -1
	card = list(map(str, card))
	nums = list(map(''.join, itertools.permutations(card)))
	nums = list(set(map(int, nums)))
	nums.sort()
	
	for i in range(len(nums)) :
		if n == nums[i] :
			answer = i + 1
	
	
	
	return answer
    
    
    
    
    
card1 = [1, 2, 1, 3]
n1 = 1312
ret1 = solution(card1, n1)

print("solution 함수의 반환 값은", ret1, "입니다.")

card2 = [1, 1, 1, 2]
n2 = 1122
ret2 = solution(card2, n2)

print("solution 함수의 반환 값은", ret2, "입니다.")
반응형
Comments