Programmers: Tuples
Conditions
{/* <!– - s의 길이는 5이상 1,000,000 이하.
숫자가 0으로 시작하는 경우는 없음.
s는 중복되는 원소가 없는 튜플을 표현하는 집합이 담긴 문자열.
s가 표현하는 튜플의 원소는 1 이상 100,000 이하인 자연수.
return 하는 배열의 길이가 1 이상 500 이하인 경우만 입력으로 주어짐. –> */}
The length of
sis 5…1,000,000.No number starts with zero.
sis a String containing a set representing a tuple without overlapping elements.The elements of the tuple expresse by
sare 1…100,000.Only given as input if the returning array length is 1…500.
Strategy
{/* <!– - s는 전체가 문자열. 문자열을 split 해서 필요한 숫자 배열로 바꾼다.
각 집합은 순서가 바뀌어도 상관 없는 상태지만 결과 튜플은 순서가 중요하다.
입출력 예시 3번에서 힌트를 얻자면, “{{20,111},{111}}” 이 [111, 20]이 되어야 한다. {111}을 먼저 찾아 결과 튜플에 추가한 후 {20,111}를 확인한다. 이 때 111은 이미 결과 튜플에 있으므로 20만 추가하면 된다.
결과가 정수 배열로 출력되어야 하므로 변환 과정이 필요하다. –> */}
sis a string. Split the string and changes it to the numerical array.Each set is in a different order, but the order is important for the result.
To take hint from I/O Example 3, “{{20,111},{111}}” should be
[111, 20]. Find {111} first, add it to the result tuple, and then check {20,111}. At this time, 111 is already in the result tuple, so you only need to add 20.Conversion process is required because results must be output in integer array.
1def solution(s):
2 answer = []
3
4 s1 = s.lstrip('{').rstrip('}').split('},{')
5 s2 = sorted(s1, key=lambda x:len(x))
6
7 for each in s2:
8 s3 = each.split(',')
9 for ch in s3:
10 if ch not in answer:
11 answer.append(ch)
12
13 return [int(i) for i in answer]
Remember
{/_ _/}
- There be another way to solve without nested for statement… I need to think more.
Comments