III = 3
XII = 12
XXVII = 27입니다.
그런데 4를 표현할 때는 IIII가 아니라 IV 입니다.
9는 IX입니다.
I는 V와 X앞에 와서 4, 9
X는 L, C앞에 와서 40, 90
C는 D, M앞에 와서 400, 900def roman_to_num(s): roman_numerals = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, } answer=roman_numerals[s[-1]] for i in range(len(s)-1, 0, -1): if roman_numerals[s[i]] <= roman_numerals[s[i-1]]: answer += roman_numerals[s[i-1]] elif roman_numerals[s[i]] > roman_numerals[s[i-1]]: answer -= roman_numerals[s[i-1]] return abs(answer)
def more_than_half(nums): harf_n = len(nums) // 2 set_list = set(nums) for i in set_list: if nums.count(i)>=harf_n: return i
밑에 코드는 반복하는 숫자갯수를 카운트 해주고 그다음 제일 큰숫자를 출력한다.
num_list= [] num_set= set(nums) for i in nums: num_list.append(nums.count(i)) return(max(num_list))
s는 여러 괄호들로 이루어진 String 인자입니다.
s가 유효한 표현인지 아닌지 true/false로 반환해주세요.
종류는 '(', ')', '[', ']', '{', '}' 으로 총 6개 있습니다. 아래의 경우 유효합니다.
한 번 괄호를 시작했으면, 같은 괄호로 끝내야 한다. 괄호 순서가 맞아야 한다.
예를 들어 아래와 같습니다.
s = "([)]"
return falsedef is_valid(string): stack= [] bracket = {"(": ")", "{": "}", "[": "]"} if len(string) == 1: return False for i in string: if i in bracket: stack.append(i) elif len(stack) == 0 or bracket[stack.pop()] != i: return False return len(stack) == 0
다른방법
def is_valid(string): left = ['(', '{', '['] right = [')', '}', ']'] stack = [] for letter in string: if letter in left: stack.append(letter) elif letter in right: if len(stack) <= 0: return False if left.index(stack.pop()) != right.index(letter): return False return len(stack) == 0
nums는 숫자로 이루어진 배열입니다.
가장 자주 등장한 숫자를 k 개수만큼 return 해주세요.
nums = [1,1,1,2,2,3], k = 2
return [1,2]def top_k(nums, k): num_count = {} result = [] for i in nums: if i in num_count: num_count[i] += 1 else: num_count[i] = 1 num_count = sorted(num_count.items(), key=lambda x: x[1], reverse=True) for i in range(k): result.append(num_count[i][0]) return result
![]()
def get_max_area(height): l = 0 r = len(height) -1 area = 0 while l < r: area = max(area, min(height[l],height[r]) * (r - l)) if height[l] < height[r]: l += 1 else: r -= 1 return area
다른 답안
def get_max_area(height): result = 0 for i in range(len(height)): for j in range(i + 1, len(height)): temp = 0 w = j - i if height[i] <= height[j]: temp = height[i] * w else: temp = height[j] * w if temp >= result: result = temp return result